Re: Features for a Python package manager?

2004-12-26 Thread Robert Kern
Georg Brandl wrote:
Robert Kern wrote:
Mike Meyer wrote:
Nick Coghlan <[EMAIL PROTECTED]> writes:

I don't know enough about Portage to answer that question. I do know
any package manager which made it into the standard distribution would
need to work for at least the big three platforms (Windows/Mac/*nix) :)

Being written in python - and hopefully integrated into Distutils -
why shouldn't it work on any platform that Python worked on?
Assumptions about directory structures, and the like.

That is already taken care by the distutils.
More or less. I'm in the middle of packaging up ~40 Python packages for 
the Mac[1]. For a "standard" packaging mechanism, distutils allows for 
some bloody idiosyncratic ways to say "put these files there". This is a 
hard problem, and it's not solved entirely by distutils.

I don't think anyone has satisfactorily solved the problem of 
distributing data with libraries. Well, okay, the *distribution* isn't 
the problem. Having the library be able to locate that data on all 
platforms is difficult. Some packages will more-or-less hardcode 
*nix-type paths which may be inappropriate even on some *nix-type 
platforms (yes, PyX, I'm looking at you :-)). A general package system 
like Portage has the freedom of being able to dictate these things. A 
Python package manager does not. You can establish a standard for each 
of the Big Three platforms, but it may not do you much good if the 
libraries don't know about it.

CPAN is a closer analogue in this regard and would probably be a better 
tool to study and copy from than Portage. I don't know much about it, 
but how it responds to these issues will probably more instructive than 
how Portage does.

You also have problems with distributing non-Python dependencies like 
libraries. You can sometimes punt and require the user to have already 
installed said libraries and headers to compile against. This will 
probably only work for source distributions on *nixes. You can probably 
get away with appropriately placed DLLs on Windows. Macs may be trickier 
(we Mac users are fussy :-)).

Exercise: VTK with its Python and TCL libraries (why TCL? It's necessary 
to use VTK with Tkinter, which the premier VTK-Python application, 
MayaVi, uses) should package up cleanly for all 3 main platforms. 
External libraries *and* data! It's a joy!

Some other "problem packages"[2] to practice on: PyX, ReportLab, PIL, 
Scipy, matplotlib.

[1] http://www.scipy.org/wikis/featurerequests/MacEnthon
[2] In the sense that they are, to some extent, not painless to package 
up in a very neat way on multiple platforms for one reason or another. 
These are all very fine packages; packaging is a hard problem; and I'm 
grateful for how well they *do* package up so far.

The various PEPs already
describe a simple method how to store package metadata, and I will try
to follow these standards as close as possible. Of course, the PyPI
would have to be adapted for that.
Fair enough. What parts of Portage do you intend to steal, then?
Please don't read any of this as discouragement. Python package 
management desperately needs a champion, and I'm very glad to see 
someone tackling these issues. I for one fully intend to use as much of 
what you produce as I can to make MacEnthon fully upgradable.

--
Robert Kern
[EMAIL PROTECTED]
"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Complementary language?

2004-12-26 Thread gene . tani
http://lambda-the-ultimate.org/
http://advogato.org/
http://c2.com/cgi/wiki?WelcomeVisitors
www.artima.com

It's a big world out there, you can glimpse Haskell, LUA, CLU, scheme,
squeak etc.
Disclaimer: going into these sites is liking going into REM sleep when
it's 95 degrees Fahrenheit (hot) and really humid

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


Re: Complementary language?

2004-12-26 Thread Alex Martelli
HackingYodel <[EMAIL PROTECTED]> wrote:

> Hello all!  I'm learning to program at home.  I can't imagine a better
> language than Python for this.  The ideal situation, for me, would be to
> study two languages at the same time.  Probably sounds crazy, but it 
> works out better for me.  Being a newbie, I find almost all languages
> fascinating.  C, D, Objective-C, Ocaml, C++, Lisp, how is a non-tech to
> choose?  Does any single language do a better job in Python's weaker 
> areas? Would anyone care to suggest one to supplement Python.  That is,
> if you could only use Python and one other language, which would it be?

I assume you mean _programming_ language in the strict sense, because,
otherwise, I think SQL (which is more of a _query_ language) or XML
(which is a _markup_ lanugage) might be more "urgent" learning needs
than any second _programming_ language.  So, within programming...:

Probably C, but Pyrex is also a strong contender for _use_.  Problem is,
there are a zillion great books on C, none on Pyrex: thus, having to
choose one of them, C enjoys a huge advantage in _learning_.  Also,
while Pyrex is amazingly mature and solid, it no doubt still has some
little way to go -- for example, the pypy project had to introduce a
small extension to Pyrex (the ability to inject inline C code, namely
labels and goto statements) in order to use Pyrex as the target for code
generation -- while C's completeness and stability are indisputable.

C's key advantages: it has much the same _philosophy_ as Python --
simplicity, lack of redundancy, trust in the programmer -- while aiming
squarely at the LOW end of language levels, closer to the machine, as
much as Python aims squarely at the HIGH end, closer to application
programming needs.  This makes them a great complement for each other.

Pyrex is close to "C with Python syntax" and is designed for ease of
interfacing with Python, generating on your behalf all the boilerplate
code that you'd normally need to do the interfacing with the Python C
API directly.  Still, I've never taught Pyrex to anybody who didn't
already know at least _some_ C, so it feels risky to recommend as "the
one othe language besides Python"...

I haven't looked at D enough to judge whether it's fully portable, fully
stable, and just as easy to interface with Python as C; also, I don't
know how the material available for it compares to C's excellence.

Objective-C is cool... on the Mac; I'm not sure how well-supported it is
elsewhere, though.  In addition to C's advantages, it would let you make
Cocoa GUIs on the Mac easily (with PyObjC &c).  But then, the right way
to study Obj-C from scratch is no doubt to start with C, anyway.

OCAML and other modern functional languages are great, but not
particularly easy to use in cooperation with Python.  If you had to pick
one for purely cultural purposes, though, I'd suggest Haskell... simpler
and sharper... OCAML is relatively Big and Rich, which may be a
practical plus but for study purposes is rather a minus, I think.  Much
the same applies to (Common) Lisp and C++: huge languages, very rich,
which may be a plus for practical production uses but surely isn't for
study purposes.


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


Re: Complementary language?

2004-12-26 Thread Alex Martelli
Robert Kern <[EMAIL PROTECTED]> wrote:

> Common Lisp might be a good one to learn. It's even more 
> "multi-paradigm" than Python. You could very easily learn more 
> approaches to programming through Common Lisp than three other 
> languages. This book[2] looks promising.

If you're looking for SERIOUS multiparadigmaticity, I think Oz may be
best --  (the book's
authors critique the vagueness of the "paradigm" concept, and prefer
"model", but that's much the same thing).

You start with pure declarative programming (aka "functional" in many
circles), move on to concurrency in a purely declarative worldview
(easiest way to see concurrency), then enrich both sequential and
concurrent models as the book progresses, by message-passing, explicit
state ("procedural"), object-oriented, _shared_ state, and finally
relational.  GUI, distributed, and constraint-based programming round
out a grandiose conceptual tour.

"SICP for the 21st Century"...?  (SICP: google for it!).  I currently
think so, though, studying CTMCP (the Oz book) in my spare time, it will
take me a while before I've finished it and can fairly offer such a
lofty recommendation for it... still, I notice from the back-page blurbs
that Peter Norvig has no reservations drawing a parallel with SICP (aka
Abelson and Sussman), and Norvig's assessment must count for more than
mine!


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


Re: WxButton

2004-12-26 Thread M.E.Farmer
ok this is slightly confusing , so I am just gonna throw out some ides.
You could  define an accelerator table and just bind wxACCEL_NORMAL,
and WXK_RETURN to an id number.
then set  an event handler to operate your button(more on that later).
Or you can set an event to just look for a certain key :
Declare this event.

py> EVT_KEY_DOWN(self, self.OnKeyPressed)

And do something like this.

py> def OnKeyPressed(self, event):
...key = event.KeyCode()
...if key == WXK_RETURN:
...BtnPressCode()

Ok now the button thing what are you wanting just to activate the
button or to toggle the button or.?
There are many buttons types and they have very different methods!
I will leave that code up to you ( just do a google search for wxButton
or wxToggleButton or even wxBitmapButton and many more just search the
docs they are very helpful, and always this is covered somewhere in the
wx demo ;)
Hth, 
M.E.Farmer

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


Re: Complementary language?

2004-12-26 Thread Paul Rubin
HackingYodel <[EMAIL PROTECTED]> writes:
> Hello all!  I'm learning to program at home.  I can't imagine a better
> language than Python for this.  The ideal situation, for me, would be
> to study two languages at the same time.  

It's less a matter of languages, than ways of approaching problems.

Have you read SICP yet?  If not, that's your next task.  The full
text is online:

  http://mitpress.mit.edu/sicp/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Features for a Python package manager?

2004-12-26 Thread Georg Brandl
Robert Kern wrote:
> Georg Brandl wrote:
>> Robert Kern wrote:
>> 
>>>Mike Meyer wrote:
>>>
Nick Coghlan <[EMAIL PROTECTED]> writes:



>I don't know enough about Portage to answer that question. I do know
>any package manager which made it into the standard distribution would
>need to work for at least the big three platforms (Windows/Mac/*nix) :)


Being written in python - and hopefully integrated into Distutils -
why shouldn't it work on any platform that Python worked on?
>>>
>>>Assumptions about directory structures, and the like.
>> 
>> 
>> That is already taken care by the distutils.
> 
> More or less. I'm in the middle of packaging up ~40 Python packages for 
> the Mac[1]. For a "standard" packaging mechanism, distutils allows for 
> some bloody idiosyncratic ways to say "put these files there". This is a 
> hard problem, and it's not solved entirely by distutils.
> 
> I don't think anyone has satisfactorily solved the problem of 
> distributing data with libraries. Well, okay, the *distribution* isn't 
> the problem. Having the library be able to locate that data on all 
> platforms is difficult. Some packages will more-or-less hardcode 
> *nix-type paths which may be inappropriate even on some *nix-type 
> platforms (yes, PyX, I'm looking at you :-)). A general package system 
> like Portage has the freedom of being able to dictate these things. A 
> Python package manager does not. You can establish a standard for each 
> of the Big Three platforms, but it may not do you much good if the 
> libraries don't know about it.
> 
> CPAN is a closer analogue in this regard and would probably be a better 
> tool to study and copy from than Portage. I don't know much about it, 
> but how it responds to these issues will probably more instructive than 
> how Portage does.

CPAN, as I understand it, is a mirror system for packages, which
downloads packages and manages those. Correct me if I'm wrong, but the
actual installation is done by each package's Makefile.PL script and not
by CPAN itself.

This is also Portage's philosopy. It only issues those commands needed
to build and install the package (ideally "tar xzf package; cd package;
make install"). Of course one can do additional steps such as applying
patches, but where the files go etc. is the author's responsibility, not
the package system's.

[Problems with dependencies]

I am aware of these problems - however I feel like the package author
has to be the one to address them. There must be a cooperation between
author and packager to clear these issues.

About non-Python-dependencies: The plan is to add a "Non-Py-Requires:"
(or so) field to the metadata that is displayed to the user, and it will
be his responsibility to install these libraries/headers/files first.

>> The various PEPs already
>> describe a simple method how to store package metadata, and I will try
>> to follow these standards as close as possible. Of course, the PyPI
>> would have to be adapted for that.
> 
> Fair enough. What parts of Portage do you intend to steal, then?

Right, that's my weak point. I do not overly like the PEPs' way, but
integrating with distutils is the way to go.

regards,
Georg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about "pure virtual methods"?

2004-12-26 Thread Alex Martelli
Noam Raphael <[EMAIL PROTECTED]> wrote:

> > That's what DbC languages are for. You write the contracts first, then
> > the code to fullfill them. And get exceptions when the implementation
> > doesn't do what the contract claims it does.
> 
> Can you give me a name of one of them? This is a very interesting thing
> - I should learn one of those sometime. However, I'm pretty sure that
> programming in them is hell, or at least, takes a very long time.

If you want to experiment with DbC within Python, I think you might want
to try  -- not sure it's
maintained and up-to-date with today's Python, but I suspect the answer
is "yes", and it would give you a chance to try DbC as a methodology,
quite separately from the issue of changing programming languages.


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


Re: list addition methods compared.

2004-12-26 Thread Terry Reedy

"Ishwor" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi all
> I have just wrote a small script to compare the speed of list addition 
> methods.

There are two meanings of 'list addition':

li = li+[item] *copies* the list and adds item

li += [item] is the same as li.extend([item]) which add item to the end of 
the list *without* copying.

Of course, extending a list is faster than copying + one more.

Terry J. Reedy



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


where is ctypes.py?

2004-12-26 Thread [EMAIL PROTECTED]
Hello,

I'm a complete newbie in learning python.

I was testing some sample codes I found in this newsgroup and seems it
could not locate the module ctypes.py. I installed python 2.4, wxPython
and pywin32. Just could not find this file. I thought it should be in
Lib/site-packages/ directory but it is not there.
Where can I find this file?

Thanks a lot for your help.

- wcc

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


Re: Optional Static Typing - Haskell?

2004-12-26 Thread Alex Martelli
Mike Meyer <[EMAIL PROTECTED]> wrote:

> [EMAIL PROTECTED] (Alex Martelli) writes:
> 
> > Mind you, I personally _like_ the concept of describing
> > an interface separately, even in a different language (Corba's IDL, say)
> > that's specialized for the task.  But it doesn't seem to be all that
> > popular... without such separation, modularity plus static checking
> > appears to imply bottom->up coding: you need to compile modules in some
> > topologically sorted order compatible with the "X uses Y" relation.
> 
> Personally, I hate declaring the interface separately, whether in the
> same language or another language. 

Yeah, so do many people -- as I mentioned, it's not all that popular.
Personally, I don't see _why_, but there's no doubt that the market is
speaking quite loudly in this respect; the concept of using IDL is seen
as a handicap of (e.g.) Corba and pure COM (while I agree with Don Box's
lavish _praise_ for that concept in a COM context!), and the concept of
not having an interface separate from the implementation is touted as a
plus of (e.g.) Java vs C++.

But then, the above criticism applies: if interface and implementation
of a module are tightly coupled, you can't really do fully modular
programming AND static typing (forget type inferencing...).


> On the other hand, generating the
> interface information from the code for type checking (and
> documentation) purposes makes an incredible amount of sense. A type
> inferencing engine to generate that information from Python code -
> with possible a bit of human assistance - would make it possible to
> use pychecker to catch duck typing errors without having to import an
> entire module.

And why should it be a problem to "import an entire module", pray?  I
just fail to see any BIG advantage here.  Sure, you could extend pydoc
to generate a bit more docs than it already does -- big deal.  How much
would that augment your overall productivity?  5%?  10%?  Some tiny
incremental amount, anyway.  If it prompts you to do less unit testing,
it might even have a negative lifecycle-productivity impact;-).


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


Re: where is ctypes.py?

2004-12-26 Thread Alex Martelli
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Hello,
> 
> I'm a complete newbie in learning python.
> 
> I was testing some sample codes I found in this newsgroup and seems it
> could not locate the module ctypes.py. I installed python 2.4, wxPython
> and pywin32. Just could not find this file. I thought it should be in
> Lib/site-packages/ directory but it is not there.
> Where can I find this file?

Download and install ctypes from



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


Re: where is ctypes.py?

2004-12-26 Thread [EMAIL PROTECTED]
Thanks a lot Alex. I got the file.

- wcc

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


Re: Complementary language?

2004-12-26 Thread Robin Becker
Alex Martelli wrote:
.
If you're looking for SERIOUS multiparadigmaticity, I think Oz may be
best --  (the book's
authors critique the vagueness of the "paradigm" concept, and prefer
"model", but that's much the same thing).
according to the language shootout at
http://shootout.alioth.debian.org/benchmark.php?test=all&lang=all&sort=cpu
Mozart/Oz comes last in cpu score. I suspect that may be due to 
unfamilarity or poor implementation of the test codes. Everybody 'knows' 
that benchamrks are always wrong, but which score moves this language to 
the top in your opinion?

Alex

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


WxListCtrl

2004-12-26 Thread LutherRevisited
Is there any way I can disable just the horizontal scroll bar for a listctrl? 
When enough items have been added for it to scroll vertically a horizontal bar
also appears, even though you don't need it at all.  I've played around with
sizing individual columns and haven't seemed to come up with anything
satisfactory.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Complementary language?

2004-12-26 Thread Alex Martelli
Robin Becker <[EMAIL PROTECTED]> wrote:

> Alex Martelli wrote:
> .
> > 
> > If you're looking for SERIOUS multiparadigmaticity, I think Oz may be
> > best --  (the book's
> > authors critique the vagueness of the "paradigm" concept, and prefer
> > "model", but that's much the same thing).
> 
> according to the language shootout at
> 
> http://shootout.alioth.debian.org/benchmark.php?test=all&lang=all&sort=cpu
> 
> Mozart/Oz comes last in cpu score. I suspect that may be due to 
> unfamilarity or poor implementation of the test codes. Everybody 'knows'
> that benchamrks are always wrong, but which score moves this language to
> the top in your opinion?

Hmmm, I'm not sure how to parse this question.  Robert Kern claimed:
"You could very easily learn more approaches to programming through
Common Lisp than three other languages", and I'm pointing out that, if
what you're after is to "learn more approaches to programming" via the
built-in features of a single language, Oz (with the CTMCP book) may
well be numero uno.  Judging from the blurb on the book's back, as I
also mentioned, Norvig, hardly a slouch when it comes to Lisp, appears
to share this assessment.

What the "language shootout" can possibly have to do with this issue
entirely escapes me.  Quite apart from "benchmarks are always wrong", I
don't think they're even _remotely_ trying to benchmark "how much does
learning this language teach you about different approaches to
programming" -- it would seem to be a mighty tall order to even set up a
controlled experiment to measure _that_ quantitatively!


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


Re: Complementary language?

2004-12-26 Thread gabriele renzi
Robin Becker ha scritto:
Alex Martelli wrote:
.
If you're looking for SERIOUS multiparadigmaticity, I think Oz may be
best --  (the book's
authors critique the vagueness of the "paradigm" concept, and prefer
"model", but that's much the same thing).

according to the language shootout at
http://shootout.alioth.debian.org/benchmark.php?test=all&lang=all&sort=cpu
Mozart/Oz comes last in cpu score. I suspect that may be due to 
unfamilarity or poor implementation of the test codes. Everybody 'knows' 
that benchamrks are always wrong, but which score moves this language to 
the top in your opinion?

He's talking of just "multiparadigmaticality", not efficiency.
The mozart/Oz platform have a stronger point on stuff like 
constraint/logic/declarative concurren/etc programming, more than most 
of the CL frameworks (not that this is hard in CL, it's just not as 
central as in Oz).  Btw, I think AliceML (which just hit 1.0) would be 
better than Oz, if accompaniying with python, just to have a 
dynamic/static contrast :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: A Revised Rational Proposal

2004-12-26 Thread Dan Bishop
Mike Meyer wrote:
> This version includes the input from various and sundry people.
Thanks
> to everyone who contributed.
>
>
> PEP: XXX
> Title: A rational number module for Python
...
> Implicit Construction
> -
>
> When combined with a floating type - either complex or float - or a
> decimal type, the result will be a TypeError.  The reason for this is
> that floating point numbers - including complex - and decimals are
> already imprecise.  To convert them to rational would give an
> incorrect impression that the results of the operation are
> precise. The proper way to add a rational to one of these types is to
> convert the rational to that type explicitly before doing the
> operation.

I disagree with raising a TypeError here.  If, in mixed-type
expressions, we treat ints as a special case of rationals, it's
inconsistent for rationals to raise TypeErrors in situations where int
doesn't.

>>> 2 + 0.5
2.5
>>> Rational(2) + 0.5
TypeError: unsupported operand types for +: 'Rational' and 'float'

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


IDLE question

2004-12-26 Thread Rolf Wester
Hi,
I would like to use IDLE as interactively as I can with Emacs. In Emacs 
I can send a marked region to the Python interpreter. Is there any way 
to do the same thing with IDLE?

Thank you in advance
Regards
Rolf Wester
--
http://mail.python.org/mailman/listinfo/python-list


Re: where is ctypes.py?

2004-12-26 Thread Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.
Hi !

See : http://starship.python.net/crew/theller/ctypes/



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


Re: Complementary language?

2004-12-26 Thread Robin Becker
Alex Martelli wrote:
Robin Becker <[EMAIL PROTECTED]> wrote:

Alex Martelli wrote:
.
If you're looking for SERIOUS multiparadigmaticity, I think Oz may be
best --  (the book's
authors critique the vagueness of the "paradigm" concept, and prefer
"model", but that's much the same thing).
according to the language shootout at
http://shootout.alioth.debian.org/benchmark.php?test=all&lang=all&sort=cpu
Mozart/Oz comes last in cpu score. I suspect that may be due to 
unfamilarity or poor implementation of the test codes. Everybody 'knows'
that benchamrks are always wrong, but which score moves this language to
the top in your opinion?

Hmmm, I'm not sure how to parse this question.  Robert Kern claimed:
"You could very easily learn more approaches to programming through
Common Lisp than three other languages", and I'm pointing out that, if
what you're after is to "learn more approaches to programming" via the
built-in features of a single language, Oz (with the CTMCP book) may
well be numero uno.  Judging from the blurb on the book's back, as I
also mentioned, Norvig, hardly a slouch when it comes to Lisp, appears
to share this assessment.
Well your utility function seems to be related to "learn more approaches 
to programming". I suspect there may be some programming language 
measure which would push really high level languages way up.  Simply 
scanning the Mozart documentation seems to indicate it has a number of 
interesting, but not unique features. From the outside it seems 
difficult to say whether say "distributed programming" is uniquely 
easily implemented in Oz or whether it's something like pyro built using 
more primitive constructs.

What the "language shootout" can possibly have to do with this issue
entirely escapes me.  Quite apart from "benchmarks are always wrong", I
don't think they're even _remotely_ trying to benchmark "how much does
learning this language teach you about different approaches to
programming" -- it would seem to be a mighty tall order to even set up a
controlled experiment to measure _that_ quantitatively!
...
I agree entirely with this last, but this is about language comparisons 
and if we're being objective we need to do some measurements. If this is 
impossible then discussion reduces to 'my language is better than yours' 
which is pretty futile.

Alex
 

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


Re: Complementary language?

2004-12-26 Thread beliavsky
Robert Kern wrote:
>If you do numeric calculations, learning just enough FORTRAN to do
loops
>and math can be quite useful. I find that F2PY makes writing FORTRAN
>subroutines for numerical calculations over Numeric arrays much easier

>than C.

I agree with this and would add that Fortran, from the 1990 standard
onwards, is one of the few compiled languages that support both array
operations and multidimensional array slices, like the Python Numeric
and Numarray modules (and lists for 1-D arrays). There is a free
Fortran 95 compiler called g95 at http://www.g95.org .

In some ways, the syntax of Python is closer to free format Fortran
than C.

Maybe the message
http://groups-beta.google.com/group/comp.lang.python/msg/5de999e28ead0dd9
I wrote with comparative statistics on some programming languages could
be informative.

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


Re: A Revised Rational Proposal

2004-12-26 Thread John Roth
"Dan Bishop" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Mike Meyer wrote:
This version includes the input from various and sundry people.
Thanks
to everyone who contributed.
   
PEP: XXX
Title: A rational number module for Python
...
Implicit Construction
-
When combined with a floating type - either complex or float - or a
decimal type, the result will be a TypeError.  The reason for this is
that floating point numbers - including complex - and decimals are
already imprecise.  To convert them to rational would give an
incorrect impression that the results of the operation are
precise. The proper way to add a rational to one of these types is to
convert the rational to that type explicitly before doing the
operation.
I disagree with raising a TypeError here.  If, in mixed-type
expressions, we treat ints as a special case of rationals, it's
inconsistent for rationals to raise TypeErrors in situations where int
doesn't.
2 + 0.5
2.5
Rational(2) + 0.5
TypeError: unsupported operand types for +: 'Rational' and 'float'
I agree that the direction of coercion should be toward
the floating type, but Decimal doesn't combine with Float either.
It should be both or neither.
John Roth
John Roth

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


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 25)

2004-12-26 Thread Fredrik Lundh
> QOTW:  "Python, the language that wraps tightly around a problem and
> swallows it whole." -- Raymond Hettinger

that's taken from an old UnixWorld article by Aaron Watters, from 1995:

   http://www.networkcomputing.com/unixworld/tutorial/005/005.html

 



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


Re: Twisted Non-Admin Installation

2004-12-26 Thread Kartic
Mike - I took the lazy route out.

Since the Twisted installer complained about not finding python for
admin, I exported the registry keys that Python installed my userid and
imported those registry entries back under the admin login. This made
it appear that there was indeed a Python install under admin.

Twisted bought that and installed as Admin!

(Though I am not entire happy about installing it as admin, this should
do it for now)

Thank you for your efforts to help.
--Kartic

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


Re: Twisted Non-Admin Installation

2004-12-26 Thread Rob Williscroft
Kartic wrote in news:[EMAIL PROTECTED] 
in comp.lang.python:

> Hello,
> 
> I downloaded the Win32 installer for Twisted 1.3.0, Python 2.3.
> 
> The installer, when executed under my login, fails as it requires
> administrator rights to install (why they have it as a requirement, I
> don't understand).
> 
> So I started the installer as the admin user. That too failed because I
> have a non-admin install of Python 2.3 on my machine and when I launch
> the Twisted installer as admin, it is unable to find a Python
> installation for the admin user!
> 
> So, can someone let me know how I can install Twisted as a non-admin
> user for a non-admin installation of Python? Installing from source is
> not an option as I do not have MSVC.
> 

Logon as Administrator, add yourself to the Administrators group 
logon as yourself, install twisted. Then remove yourself from
the Administrators group.

This should let you install, but wether it leaves twisted in a 
usable (by a non administrator) state, I don't know.

Also AIUI twisted have a mailing list of there own, the link

http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python

is on there home page: http://twistedmatrix.com

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: WxListCtrl

2004-12-26 Thread Kartic
You might want to try using the SetColumnWidth method and give the
column width in pixels. The user (or you) can the read the entire
contents by dragging the column marker to the right (or you can give a
tooltip that displays the entire list control item when the moused
over)

self.lc.SetColumnWidth(0, 200) # Set the first list control column to
200 pixels.

If you want the column to "auto adjust" to the length of the column
header, no matter how long the row contents are, you cann use

self.lc.SetColumnWidth(0, wx.LIST_AUTOSIZE_USEHEADER)

But when you drag out the column to read more the Horizontal Scroll bar
might appear. In my limited knowledge, I can not tell whether or not
there is anything you can do about it. I don't think there is a way to
just prevent the H. Scroll Bar from appearing at all.

Thanks,
--Kartic

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


Re: Complementary language?

2004-12-26 Thread Alex Martelli
Robin Becker <[EMAIL PROTECTED]> wrote:
   ...
> >>>If you're looking for SERIOUS multiparadigmaticity, I think Oz may be
   ...
> > Hmmm, I'm not sure how to parse this question.  Robert Kern claimed:
> > "You could very easily learn more approaches to programming through
> > Common Lisp than three other languages", and I'm pointing out that, if
> > what you're after is to "learn more approaches to programming" via the
   ...
> Well your utility function seems to be related to "learn more approaches
> to programming".

Which part of "if" do you find hard to parse?

> I suspect there may be some programming language 
> measure which would push really high level languages way up.  Simply 

"Language Level" as defined in
 (first google hit for
"language level" _without_ quotes) might be a starting point.  If one
were to study accurately (as opposed to "eyeball it", as theadvisors.com
does too often) LL for, say, Lisp, Oz, OCAML, Ruby, Perl, Python, I
doubt one would find statistically significant consistent differences
across a broad range of domains, though.

> scanning the Mozart documentation seems to indicate it has a number of
> interesting, but not unique features. From the outside it seems 
> difficult to say whether say "distributed programming" is uniquely 
> easily implemented in Oz or whether it's something like pyro built using
> more primitive constructs.

I've browsed just enough Erlang to get a taste for a way to do
distributed programming that's reasonably higher-level -- Michael Hobbs'
candygram.sf.net might be the Python equivalent, but I believe it only
does the concurrency, not the distribution.  What I expect from Oz
(haven't gotten that far in the book yet) is "more of the same",
didactically speaking -- encompassing various degrees of statefulness in
an elegant and conceptually clear way -- while I believe Erlang only
reaches to single-assignment level.


> I agree entirely with this last, but this is about language comparisons
> and if we're being objective we need to do some measurements. If this is
> impossible then discussion reduces to 'my language is better than yours'
> which is pretty futile.

I do not agree with the underlying axiom that all human endeavours
_must_ be numerically measurable or else can't be meaningfully
discussed.  One could see this restrictive view of discourse as
equivalent to what Wittgenstein in his '20s was exposing in the
Tractatus (although I'd argue that would be a too-narrow reading of the
Tractatus) and my preferred stance as equivalent to Wittgenstein's more
mature reflection e.g. in the Untersuchungen.  There, this is a
self-referential example: would it be futile to compare the worldviews
in Wittgenstein's major works and see the latter, more mature one as
wider and more useful and applicable than the extremist, youthful one,
just because it's silly to even think about quantifying the difference?
I most definitely don't think so.  Ultimately, it's about the natural
history of human beings -- this applies to programming just as well as
(per Wittgenstein) to other allegedly "rigorous" discourse (say, on the
foundations of logic, set theory, &c).

It's not _conceptually impossible_ to measure the didactical values of
different endeavours in terms of enhancing skills at some given target
tasks; it _is_, however, prohibitively costly, in most cases, to perform
properly controlled double-blind experiments of this nature.  In this
case, as in most other similar ones in real life, we're not even given a
precise set of target tasks, just (as is perfectly reasonable) a generic
potential desire to _learn about different approaches to programming_.

I think it would be silly to try to stop people from desiring to learn
something even when they can't quantify the eventual success at such
learning endeavours.  It's not just a matter of _programming languages_:
I have argued in the past that studying Borges or Calvino, Korzibsky or
Wittgenstein, category theory or nonmodal logic, can all be very
effective ways to broaden your thinking towards different approaches to
reasoning about the world, and therefore to design programs.  Can I
quantify the benefits, from this POV, of studying Korzibski for a
semester, versus those of spending the same amount of time and energy
studying Borges?  No, and I believe it's silly to even try to.


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


Re: Complementary language?

2004-12-26 Thread Alex Martelli
gabriele renzi <[EMAIL PROTECTED]> wrote:

> The mozart/Oz platform have a stronger point on stuff like 
> constraint/logic/declarative concurren/etc programming, more than most
> of the CL frameworks (not that this is hard in CL, it's just not as 
> central as in Oz).  Btw, I think AliceML (which just hit 1.0) would be
> better than Oz, if accompaniying with python, just to have a 
> dynamic/static contrast :)

Nolo contendere (not having looked much into Alice yet), but are there
stand-alone didactical materials for Alice as there are for Oz?  It
seemed to me that the available materials for Alice basically take SML
somewhat for granted, while Oz does come with tutorials which make no
analogous assumptions.  If you're recommending Alice as the second
language for somebody whose first and only language so far is Python,
what URLs and/or books would you point them to, for self-stufy?


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


Re: Improving Python (was: Lambda going out of fashion)

2004-12-26 Thread Fredrik Lundh
Aahz wrote:

>>(I've said it before, and I'll say it again: native unicode and
>>generators are the only essential additions I've seen since 1.5.2, with
>>properties and sub-classable C types sharing a distant third place.
>>the rest of the stuff has had zero impact on my ability to write solid
>>code in no time at all, and negative impact on my ability to download
>>stuff that others have written and expect it to work in any Python
>>version but the latest...)
>
> Hmmm...  I find code much more readable and writable now that apply() is
> going away.  And unless you mean "generator" to include iterators in
> general, I believe that iterators are another critical addition.
>
> I'm surprised that you don't include garbage collection and augmented
> assignment, though.  String methods have been a net gain, I think.

garbage collection is a CPython implementation detail, not a language
property (it's a nice implementation detail, sure).

and we had iterators before we got the iterator protocol; the protocol made
things slightly more convenient, but it didn't enable you to do anything you
couldn't do before (using __getitem__ instead of __next__).  generators are
something entirely different.  writing inverted code is hard; yielding is 
trivial.

func(*arg) instead of apply() is a step back -- it hides the fact that functions
are objects, and it confuses the heck out of both C/C++ programmers and
Python programmers that understand the "def func(*arg)" form, because it
looks like something it isn't (there's a false symmetry between the call-form
and the def-form).

and I still do enough 1.5.2-programming to use "x = x + y"; when I find
myself in a situation where my code would benefit a lot from being able to
write "x += y" instead, I go back and fix the design.

string methods are nice, but nothing groundbreaking, and their niceness is
almost entirely offset by the horrid "".join(seq) construct that keeps popping
up when people take the "the string module is deprecated" yada yada too
seriously.  and what do the python-devers do?  they add a "sum" built-in,
but no "join"?  hello?

 



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


Re: A Revised Rational Proposal

2004-12-26 Thread Dan Bishop

Mike Meyer wrote:
> This version includes the input from various and sundry people.
Thanks
> to everyone who contributed.
>
>
> PEP: XXX
> Title: A rational number module for Python
...
> Implementation
> ==
>
> There is currently a rational module distributed with Python, and a
> second rational module in the Python cvs source tree that is not
> distributed.  While one of these could be chosen and made to conform
> to the specification, I am hoping that several people will volunteer
> implementatins so that a ''best of breed'' implementation may be
> chosen.

I'll be the first to volunteer an implementation.

I've made the following deviations from your PEP:

* Binary operators with one Rational operand and one float or Decimal
operand will not raise a TypeError, but return a float or Decimal.
* Expressions of the form Decimal op Rational do not work.  This is a
bug in the decimal module.
* The constructor only accepts ints and longs.  Conversions from float
or Decimal to Rational can be made with the static methods:
- fromExactFloat: exact conversion from float to Rational
- fromExactDecimal: exact conversion from Decimal to Rational
- approxSmallestDenominator: Minimizes the result's denominator,
given a maximum allowed error.
- approxSmallestError: Minimizes the result's error, given a
maximum allowed denominator.
For example,

>>> Rational.fromExactFloat(math.pi)
Rational(884279719003555, 281474976710656)
>>> decimalPi = Decimal("3.141592653589793238462643383")
>>> Rational.fromExactDecimal(decimalPi)
Rational(3141592653589793238462643383, 1000)
>>> Rational.approxSmallestDenominator(math.pi, 0.01)
Rational(22, 7)
>>> Rational.approxSmallestDenominator(math.pi, 0.001)
Rational(201, 64)
>>> Rational.approxSmallestDenominator(math.pi, 0.0001)
Rational(333, 106)
>>> Rational.approxSmallestError(math.pi, 10)
Rational(22, 7)
>>> Rational.approxSmallestError(math.pi, 100)
Rational(311, 99)
>>> Rational.approxSmallestError(math.pi, 1000)
Rational(355, 113)

Anyhow, here's my code:

from __future__ import division

import decimal
import math

def _gcf(a, b):
"Returns the greatest common factor of a and b."
a = abs(a)
b = abs(b)
while b:
a, b = b, a % b
return a

class Rational(object):
"Exact representation of rational numbers."
def __init__(self, numerator, denominator=1):
"Contructs the Rational object for numerator/denominator."
if not isinstance(numerator, (int, long)):
raise TypeError('numerator must have integer type')
if not isinstance(denominator, (int, long)):
raise TypeError('denominator must have integer type')
if not denominator:
raise ZeroDivisionError('rational construction')
factor = _gcf(numerator, denominator)
self.__n = numerator // factor
self.__d = denominator // factor
if self.__d < 0:
self.__n = -self.__n
self.__d = -self.__d
def __repr__(self):
if self.__d == 1:
return "Rational(%d)" % self.__n
else:
return "Rational(%d, %d)" % (self.__n, self.__d)
def __str__(self):
if self.__d == 1:
return str(self.__n)
else:
return "%d/%d" % (self.__n, self.__d)
def __hash__(self):
try:
return hash(float(self))
except OverflowError:
return hash(long(self))
def __float__(self):
return self.__n / self.__d
def __int__(self):
if self.__n < 0:
return -int(-self.__n // self.__d)
else:
return int(self.__n // self.__d)
def __long__(self):
return long(int(self))
def __nonzero__(self):
return bool(self.__n)
def __pos__(self):
return self
def __neg__(self):
return Rational(-self.__n, self.__d)
def __abs__(self):
if self.__n < 0:
return -self
else:
return self
def __add__(self, other):
if isinstance(other, Rational):
return Rational(self.__n * other.__d + self.__d * other.__n,
self.__d * other.__d)
elif isinstance(other, (int, long)):
return Rational(self.__n + self.__d * other, self.__d)
elif isinstance(other, (float, complex)):
return float(self) + other
elif isinstance(other, decimal.Decimal):
return self.decimal() + other
else:
return NotImplemented
__radd__ = __add__
def __sub__(self, other):
if isinstance(other, Rational):
return Rational(self.__n * other.__d - self.__d * other.__n,
self.__d * other.__d)
elif isinstance(other, (int, long)):
return Rational(self.__n - self.__d * other, self.__d)
elif isinstance(other, (float, complex)):
return float(self) - other
elif isinstance(other, decimal.Decimal):
return self.decimal() - other
else:
return NotImplemented
def __rsub__(self, other):
if isinstance(other, (int, long)):
return Rational(other * self.__d - self.__n, self.__d)
elif isinstance(other, (float, complex)):
return other - float(self)
elif isinstance(other, decimal.Decimal):
return other - self.decimal()
else:
return NotImplemented
def __mul__(self, other):
if isinstance(other, Rational):
return Rational(self.__n * other.__n, self.__d * other.__d)
elif isinstance(other, (int, long)):
return Rational(self.__n * other, self.__d)
elif isinstance(other, (float, complex)):
return float(self) * other
elif isinstance(other, decimal.Decimal):
return self.decimal() * 

Re: A Revised Rational Proposal

2004-12-26 Thread Dan Bishop
Dan Bishop wrote:
> Mike Meyer wrote:
> > This version includes the input from various and sundry people.
> Thanks
> > to everyone who contributed.
> >
> > >
> > PEP: XXX
> > Title: A rational number module for Python
> ...
> > Implementation
> > ==
> >
> > There is currently a rational module distributed with Python, and a
> > second rational module in the Python cvs source tree that is not
> > distributed.  While one of these could be chosen and made to
conform
> > to the specification, I am hoping that several people will
volunteer
> > implementatins so that a ''best of breed'' implementation may be
> > chosen.
>
> I'll be the first to volunteer an implementation.

The new Google Groups software appears to have problems with
indentation.  I'm posting my code again, with indents replaced with
instructions on how much to indent.

from __future__ import division

import decimal
import math

def _gcf(a, b):
{indent 1}"Returns the greatest common factor of a and b."
{indent 1}a = abs(a)
{indent 1}b = abs(b)
{indent 1}while b:
{indent 2}a, b = b, a % b
{indent 1}return a

class Rational(object):
{indent 1}"Exact representation of rational numbers."
{indent 1}def __init__(self, numerator, denominator=1):
{indent 2}"Contructs the Rational object for numerator/denominator."
{indent 2}if not isinstance(numerator, (int, long)):
{indent 3}raise TypeError('numerator must have integer type')
{indent 2}if not isinstance(denominator, (int, long)):
{indent 3}raise TypeError('denominator must have integer type')
{indent 2}if not denominator:
{indent 3}raise ZeroDivisionError('rational construction')
{indent 2}factor = _gcf(numerator, denominator)
{indent 2}self.__n = numerator // factor
{indent 2}self.__d = denominator // factor
{indent 2}if self.__d < 0:
{indent 3}self.__n = -self.__n
{indent 3}self.__d = -self.__d
{indent 1}def __repr__(self):
{indent 2}if self.__d == 1:
{indent 3}return "Rational(%d)" % self.__n
{indent 2}else:
{indent 3}return "Rational(%d, %d)" % (self.__n, self.__d)
{indent 1}def __str__(self):
{indent 2}if self.__d == 1:
{indent 3}return str(self.__n)
{indent 2}else:
{indent 3}return "%d/%d" % (self.__n, self.__d)
{indent 1}def __hash__(self):
{indent 2}try:
{indent 3}return hash(float(self))
{indent 2}except OverflowError:
{indent 3}return hash(long(self))
{indent 1}def __float__(self):
{indent 2}return self.__n / self.__d
{indent 1}def __int__(self):
{indent 2}if self.__n < 0:
{indent 3}return -int(-self.__n // self.__d)
{indent 2}else:
{indent 3}return int(self.__n // self.__d)
{indent 1}def __long__(self):
{indent 2}return long(int(self))
{indent 1}def __nonzero__(self):
{indent 2}return bool(self.__n)
{indent 1}def __pos__(self):
{indent 2}return self
{indent 1}def __neg__(self):
{indent 2}return Rational(-self.__n, self.__d)
{indent 1}def __abs__(self):
{indent 2}if self.__n < 0:
{indent 3}return -self
{indent 2}else:
{indent 3}return self
{indent 1}def __add__(self, other):
{indent 2}if isinstance(other, Rational):
{indent 3}return Rational(self.__n * other.__d + self.__d * other.__n,
self.__d * other.__d)
{indent 2}elif isinstance(other, (int, long)):
{indent 3}return Rational(self.__n + self.__d * other, self.__d)
{indent 2}elif isinstance(other, (float, complex)):
{indent 3}return float(self) + other
{indent 2}elif isinstance(other, decimal.Decimal):
{indent 3}return self.decimal() + other
{indent 2}else:
{indent 3}return NotImplemented
{indent 1}__radd__ = __add__
{indent 1}def __sub__(self, other):
{indent 2}if isinstance(other, Rational):
{indent 3}return Rational(self.__n * other.__d - self.__d * other.__n,
self.__d * other.__d)
{indent 2}elif isinstance(other, (int, long)):
{indent 3}return Rational(self.__n - self.__d * other, self.__d)
{indent 2}elif isinstance(other, (float, complex)):
{indent 3}return float(self) - other
{indent 2}elif isinstance(other, decimal.Decimal):
{indent 3}return self.decimal() - other
{indent 2}else:
{indent 3}return NotImplemented
{indent 1}def __rsub__(self, other):
{indent 2}if isinstance(other, (int, long)):
{indent 3}return Rational(other * self.__d - self.__n, self.__d)
{indent 2}elif isinstance(other, (float, complex)):
{indent 3}return other - float(self)
{indent 2}elif isinstance(other, decimal.Decimal):
{indent 3}return other - self.decimal()
{indent 2}else:
{indent 3}return NotImplemented
{indent 1}def __mul__(self, other):
{indent 2}if isinstance(other, Rational):
{indent 3}return Rational(self.__n * other.__n, self.__d * other.__d)
{indent 2}elif isinstance(other, (int, long)):
{indent 3}return Rational(self.__n * other, self.__d)
{indent 2}elif isinstance(other, (float, complex)):
{indent 3}return float(self) * other
{indent 2}elif isinstance(other, decimal.Decimal):
{indent 3}return self.decimal() * other
{indent 2}else:
{indent 3}return NotImplemented
{indent 1}__rmul__ = __mul__
{indent 1}def __truediv__(self, other):
{indent 2}if isinstance(other, Rational):
{indent 3}return Rational(self.__n * other.__d, self.__d * oth

[Parsing] How do I process loops with PLY?

2004-12-26 Thread F. GEIGER
I'm rather new to high level parsing with lex/yacc (and realy impressed so
far).

I'd like to parse *and execute* files like this:

A=12
B=23
G X=A Y=B Z=34 # Move to X, Y, Z
G Z=0

etc.

No problems so far.

But when loops enter the game, things seem to become more difficult:

A=12
B=23
C=45
D=56
DX=0

FOR C # Exec the following lines C times
   G X=A+DX Y=B Z=34 # Move to X, Y, Z

   # more statements...

   DX=DX+67
NEXT

How can I tell PLY to go back to the beginning of the FOR-loop's body to
execute it C-1 more times? A syntax checker would not need to do that, but
an interpreter (which actually I am building) has to.

Any hints are welcome.

Kind regards
Franz GEIGER


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


Re: Complementary language?

2004-12-26 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Robin Becker  <[EMAIL PROTECTED]> wrote:
.
.
.
>interesting, but not unique features. From the outside it seems 
>difficult to say whether say "distributed programming" is uniquely 
>easily implemented in Oz or whether it's something like pyro built using 
>more primitive constructs.
.
.
.
>I agree entirely with this last, but this is about language comparisons 
>and if we're being objective we need to do some measurements. If this is 
>impossible then discussion reduces to 'my language is better than yours' 
>which is pretty futile.
.
.
.
"... distributed ...", "mine is better than yours", and
complements Python:  'sounds like Erlang http://phaseit.net/claird/comp.lang.functional/Erlang.html >
to me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Complementary language?

2004-12-26 Thread Robin Becker
Alex Martelli wrote:
Robin Becker <[EMAIL PROTECTED]> wrote:
.

Well your utility function seems to be related to "learn more approaches
to programming".

Which part of "if" do you find hard to parse?
no part

I suspect there may be some programming language 
measure which would push really high level languages way up.  Simply 

"Language Level" as defined in
 (first google hit for
"language level" _without_ quotes) might be a starting point.  If one
were to study accurately (as opposed to "eyeball it", as theadvisors.com
does too often) LL for, say, Lisp, Oz, OCAML, Ruby, Perl, Python, I
doubt one would find statistically significant consistent differences
across a broad range of domains, though.
so if these languages are equivalent the cpu measure might have some 
value ;)



I agree entirely with this last, but this is about language comparisons
and if we're being objective we need to do some measurements. If this is
impossible then discussion reduces to 'my language is better than yours'
which is pretty futile.

I do not agree with the underlying axiom that all human endeavours
_must_ be numerically measurable or else can't be meaningfully
.
I take this to mean that comparisons can be done some other way. If so a 
 rationalist such as myself would want them used. Discussing 
Wittgenstein will probably not assist me if logic/mathematics can't. 
Human languages are also not comparable numerically, but that doesn't 
stop linguists from comparing and classifying them. I suppose there must 
be an equivalent dissection for the fundamental concepts of CS languages.

It's not _conceptually impossible_ to measure the didactical values of
different endeavours in terms of enhancing skills at some given target
tasks; it _is_, however, prohibitively costly, in most cases, to perform
properly controlled double-blind experiments of this nature.  In this
case, as in most other similar ones in real life, we're not even given a
precise set of target tasks, just (as is perfectly reasonable) a generic
potential desire to _learn about different approaches to programming_.
I was thinking that perhaps indirect measures might assist; perhaps 
teachability, popularity etc could be used. I work with some student 
interns. They are asked to learn haskell, their teachers like it and the 
students mostly hate it. I suspect that Oz has more 'features' so 
teachers will like it.

I think it would be silly to try to stop people from desiring to learn
something even when they can't quantify the eventual success at such
learning endeavours.
I'm certainly not attempting to stop any doing anything.

Alex

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


Re: Improving Python (was: Lambda going out of fashion)

2004-12-26 Thread Just
In article <[EMAIL PROTECTED]>,
 "Fredrik Lundh" <[EMAIL PROTECTED]> wrote:

> func(*arg) instead of apply() is a step back

Strongly disagree. I find func(*args) much more readable than 
apply(func, args).

> -- it hides the fact that functions are objects,

What does this have to do with anything?

> and it confuses the heck out of both C/C++ programmers and
> Python programmers that understand the "def func(*arg)" form, because it
> looks like something it isn't (there's a false symmetry between the call-form
> and the def-form).

What's false about the symmetry?

  Call: you supply a sequence of args
  Def: you receive a sequence of args

Lovely.

> and I still do enough 1.5.2-programming to use "x = x + y"; when I find
> myself in a situation where my code would benefit a lot from being able to
> write "x += y" instead, I go back and fix the design.
> 
> string methods are nice, but nothing groundbreaking, and their niceness is
> almost entirely offset by the horrid "".join(seq) construct that keeps 
> popping
> up when people take the "the string module is deprecated" yada yada too
> seriously.  and what do the python-devers do?  they add a "sum" built-in,
> but no "join"?  hello?

That's what you get for unsubscribing ;-)

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


cosmetic Tkinter question

2004-12-26 Thread Sean McIlroy
I've got a bunch of Frames, all packed into the root window with
side=TOP, and in each Frame I've got a Checkbutton packed with
side=LEFT. I expected the Checkbuttons to be flush with the left edge
of the window, but they're not, and it looks a little gross. How do I
get them to align?
-- 
http://mail.python.org/mailman/listinfo/python-list


SimpleHTTPServer, queries unhandled?

2004-12-26 Thread Bryan Rasmussen
Hey just doing some preliminary testing with SimpleHTTPServer, and i noticed
that when i request a resource with a query string parameters that this was not
handled. 

is this correct, or is there a method to set query string handling?
-- 
Bryan Rasmussen





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


Re: Jython & IronPython Under Active Development?

2004-12-26 Thread Cameron Laird
In article <[EMAIL PROTECTED]>, Robert Kern  <[EMAIL PROTECTED]> wrote:
.
.
.
>It should be noted that Jim Hugunin no longer works on Jython although 
>he did start the project (possibly with others, I'm not sure).
.
.
.
Mostly he started it with others discouraging him, arguing,
"*That*'s one project that'll never fly."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Improving Python (was: Lambda going out of fashion)

2004-12-26 Thread Aahz
In article <[EMAIL PROTECTED]>,
Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>
>func(*arg) instead of apply() is a step back -- it hides the fact
>that functions are objects, and it confuses the heck out of both
>C/C++ programmers and Python programmers that understand the "def
>func(*arg)" form, because it looks like something it isn't (there's a
>false symmetry between the call-form and the def-form).

For me, it works the other way around, but I can see how you perceive it
that way.

>and I still do enough 1.5.2-programming to use "x = x + y"; when I find
>myself in a situation where my code would benefit a lot from being able
>to write "x += y" instead, I go back and fix the design.

Okay, it wasn't clear in your original post that you're still stuck with
1.5.2.  That makes a huge difference in the convenience of newer
features.

>string methods are nice, but nothing groundbreaking, and their niceness
>is almost entirely offset by the horrid "".join(seq) construct that
>keeps popping up when people take the "the string module is deprecated"
>yada yada too seriously. and what do the python-devers do? they add a
>"sum" built-in, but no "join"? hello?

While I'm in complete agreement about the "".join() construct on the
basis of looks, I have come to appreciate the fact that I *never* mess up
the order of arguments any more.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"19. A language that doesn't affect the way you think about programming,
is not worth knowing."  --Alan Perlis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cosmetic Tkinter question

2004-12-26 Thread Michael Fuhr
[EMAIL PROTECTED] (Sean McIlroy) writes:

> I've got a bunch of Frames, all packed into the root window with
> side=TOP, and in each Frame I've got a Checkbutton packed with
> side=LEFT. I expected the Checkbuttons to be flush with the left edge
> of the window, but they're not, and it looks a little gross. How do I
> get them to align?

You can see what's happening if you create the frames with options
like relief=RIDGE, bd=1.  Read up on how the packer works and how
to control layout with expand, fill, and anchor.

-- 
Michael Fuhr
http://www.fuhr.org/~mfuhr/
-- 
http://mail.python.org/mailman/listinfo/python-list


AttributeError of a module instance

2004-12-26 Thread Paolino
I'd like to catch AttributeError on the module level,so that  I can 
declare default bindings for useds defore definition.How is this  to be 
done?Thanks for help.
Paolino

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


Re: A Revised Rational Proposal

2004-12-26 Thread Steven Bethard
Dan Bishop wrote:
Mike Meyer wrote:
PEP: XXX
I'll be the first to volunteer an implementation.
Very cool.  Thanks for the quick work!
For stdlib acceptance, I'd suggest a few cosmetic changes:
Use PEP 257[1] docstring conventions, e.g. triple-quoted strings.
Use PEP 8[2] naming conventions, e.g. name functions from_exact_float, 
approx_smallest_denominator, etc.

The decimal and math modules should probably be imported as _decimal and 
_math.  This will keep them from showing up in the module namespace in 
editors like PythonWin.

I would be inclined to name the instance variables _n and _d instead of 
the double-underscore versions.  There was a thread a few months back 
about avoiding overuse of __x name-mangling, but I can't find it.  It 
also might be nice for subclasses of Rational to be able to easily 
access _n and _d.

Thanks again for your work!
Steve
[1] http://www.python.org/peps/pep-0257.html
[2] http://www.python.org/peps/pep-0008.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: A Revised Rational Proposal

2004-12-26 Thread John Roth
"Steven Bethard" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Dan Bishop wrote:
Mike Meyer wrote:
PEP: XXX
I'll be the first to volunteer an implementation.
Very cool.  Thanks for the quick work!
For stdlib acceptance, I'd suggest a few cosmetic changes:
Use PEP 257[1] docstring conventions, e.g. triple-quoted strings.
Use PEP 8[2] naming conventions, e.g. name functions from_exact_float, 
approx_smallest_denominator, etc.

The decimal and math modules should probably be imported as _decimal and 
_math.  This will keep them from showing up in the module namespace in 
editors like PythonWin.

I would be inclined to name the instance variables _n and _d instead of 
the double-underscore versions.  There was a thread a few months back 
about avoiding overuse of __x name-mangling, but I can't find it.  It also 
might be nice for subclasses of Rational to be able to easily access _n 
and _d.
I'd suggest making them public rather than either protected or
private. There's a precident with the complex module, where
the real and imaginary parts are exposed as .real and .imag.
John Roth
Thanks again for your work!
Steve
[1] http://www.python.org/peps/pep-0257.html
[2] http://www.python.org/peps/pep-0008.html 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Configuration Files

2004-12-26 Thread flamesrock
thanks for the replies, guys!

MEFarmer, that example helps remove a lot of the confusion, thanks!
I've looked through the SDL but there are so many different ways to do
it, I wasn't which one was hands down best

And Mike, I wish they would stick explanations like that in the SDL!
Would help make breaking into the language a lot easier for newbs like
me.

(Spending time on these newsgroups is giving me more questions that
answers heh )

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


Tricks to install/run Python on Windows ?

2004-12-26 Thread StepH
Hi,
I'm new to Python.  I'm working under XP, and I've alot of prob. (not 
with the langage itself, but with the tools):

I've install Pyhton 2.4 in C:\Python24, using the .msi windows installer.
Then, I've install "PythonWin" (the last build-203).
I'll try to summerize my prob.:
1./ The PythonWin IDE is not stable at all.  Sometimes it exit without 
reason, or don't stop on breakpoint, etc...  Are some of you aware of 
bugs in the last PyhtonWin IDE release ?  I've to open the TaskManager. 
 AT some point, i'm not able to (p.e.) open a file under it !!!

2./ I've try to download Komode (he 3.1 personnal).  I've also prob. 
with it !  Also, the breakpoint seems to not always work...

3./ So, i've try to use the command line, but i've to manualy change the 
code page od my dos box from 437 to 1252 (i'm live in belgium).  And 
i've not try how to do that permanently !

4./ Before, I had Python23 and it seems that when unstalling it, all the 
keys in the registry are not removed at all.  When i've install the 2.4, 
I had a mismatch which force me to complety re-install the machine (I'm 
not an expert of the registry)...

5./ Installing komodo seems to "block" pythonwinIDE completly...
What's wrong ?  Python seems terific, but the tools...
So... maybe i've to try BlackAdder ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Parsing] How do I process loops with PLY?

2004-12-26 Thread Edwin Young
"F. GEIGER" <[EMAIL PROTECTED]> writes:

> But when loops enter the game, things seem to become more difficult:
> 
> A=12
> B=23
> C=45
> D=56
> DX=0
> 
> FOR C # Exec the following lines C times
>G X=A+DX Y=B Z=34 # Move to X, Y, Z
> 
># more statements...
> 
>DX=DX+67
> NEXT
> 
> How can I tell PLY to go back to the beginning of the FOR-loop's
> body to execute it C-1 more times? A syntax checker would not need
> to do that, but an interpreter (which actually I am building) has
> to.

Typically, you would separate parsing from executing the code. Use PLY
to parse the whole thing once and produce a data structure
representing the code (usually called an 'abstract syntax tree') then
write an interpreter which uses that tree as its input.

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


program in interactive mode

2004-12-26 Thread B.G.R.
Hi all,

I'm working on an interpreter for a university subject, which is programmed
in python under linux.
I got most of the work done and I'm just trying to settle some problems I've
found on my way.
Right now, the most important is reading the user input. Everything goes
through the standard input, and now I got something like this:

numline=0
for line in sys.stdin:
numline+=1
workwithline(line)

A little bit more complex, but that's the idea. That will work if the user
does something like "./myprog.py < code" or "cat code | ./myprog.py", and
that's ok, but if the user only does "./myprog.py" then I got to get into
interactive mode and show a prompt in every line expecting the user input
for that line. Problem is I don't know how to tell if I've been "piped" or
not.
I used to think that the piped program doesn't know anything and it's just
OS dependant to close and open the right descriptors, but I'm not sure
anymore. Any help or pointer in the right direction would be greatly
appreciated.

Happy christmas everyone,

RGB




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


Re: program in interactive mode

2004-12-26 Thread M.E.Farmer
B.G.R. wrote:
> Hi all,
[snip]
> A little bit more complex, but that's the idea. That will work if the
user
> does something like "./myprog.py < code" or "cat code | ./myprog.py",
and
> that's ok, but if the user only does "./myprog.py" then I got to get
into
> interactive mode and show a prompt in every line expecting the user
input
> for that line. Problem is I don't know how to tell if I've been
"piped" or
> not.
> I used to think that the piped program doesn't know anything and it's
just
> OS dependant to close and open the right descriptors, but I'm not
sure
> anymore. Any help or pointer in the right direction would be greatly
> appreciated.
>
> Happy christmas everyone,
>
> RGB
Hello RGB,
what you are loking for is sys.stdin.isatty()

py> if sys.stdin.isatty():
...print 'Console'
... else:
...print 'Redirected'

Hth,
M.E.Farmer

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


Re: A Revised Rational Proposal

2004-12-26 Thread Dan Bishop

Steven Bethard wrote:
> Dan Bishop wrote:
> > Mike Meyer wrote:
> >>
> >>PEP: XXX
> >
> > I'll be the first to volunteer an implementation.
>
> Very cool.  Thanks for the quick work!
>
> For stdlib acceptance, I'd suggest a few cosmetic changes:

No problem.

"""Implementation of rational arithmetic."""

from __future__ import division

import decimal as decimal
import math as _math

def _gcf(a, b):
"""Returns the greatest common factor of a and b."""
a = abs(a)
b = abs(b)
while b:
a, b = b, a % b
return a

class Rational(object):
"""This class provides an exact representation of rational numbers.

All of the standard arithmetic operators are provided.  In
mixed-type
expressions, an int or a long can be converted to a Rational
without
loss of precision, and will be done as such.

Rationals can be implicity (using binary operators) or explicity
(using float(x) or x.decimal()) converted to floats or Decimals;
this may cause a loss of precision.  The reverse conversions can be
done without loss of precision, and are performed with the
from_exact_float and from_exact decimal static methods.  However,
because of rounding error in the original values, this tends to
produce
"ugly" fractions.  "Nicer" conversions to Rational can be made with
approx_smallest_denominator or approx_smallest_error.
"""
def __init__(self, numerator, denominator=1):
"""Contructs the Rational object for numerator/denominator."""
if not isinstance(numerator, (int, long)):
raise TypeError('numerator must have integer type')
if not isinstance(denominator, (int, long)):
raise TypeError('denominator must have integer type')
if not denominator:
raise ZeroDivisionError('rational construction')
factor = _gcf(numerator, denominator)
self._n = numerator // factor
self._d = denominator // factor
if self._d < 0:
self._n = -self._n
self._d = -self._d
def __repr__(self):
if self._d == 1:
return "Rational(%d)" % self._n
else:
return "Rational(%d, %d)" % (self._n, self._d)
def __str__(self):
if self._d == 1:
return str(self._n)
else:
return "%d/%d" % (self._n, self._d)
def __hash__(self):
try:
return hash(float(self))
except OverflowError:
return hash(long(self))
def __float__(self):
return self._n / self._d
def __int__(self):
if self._n < 0:
return -int(-self._n // self._d)
else:
return int(self._n // self._d)
def __long__(self):
return long(int(self))
def __nonzero__(self):
return bool(self._n)
def __pos__(self):
return self
def __neg__(self):
return Rational(-self._n, self._d)
def __abs__(self):
if self._n < 0:
return -self
else:
return self
def __add__(self, other):
if isinstance(other, Rational):
return Rational(self._n * other._d + self._d * other._n,
self._d * other._d)
elif isinstance(other, (int, long)):
return Rational(self._n + self._d * other, self._d)
elif isinstance(other, (float, complex)):
return float(self) + other
elif isinstance(other, _decimal.Decimal):
return self.decimal() + other
else:
return NotImplemented
__radd__ = __add__
def __sub__(self, other):
if isinstance(other, Rational):
return Rational(self._n * other._d - self._d * other._n,
self._d * other._d)
elif isinstance(other, (int, long)):
return Rational(self._n - self._d * other, self._d)
elif isinstance(other, (float, complex)):
return float(self) - other
elif isinstance(other, _decimal.Decimal):
return self.decimal() - other
else:
return NotImplemented
def __rsub__(self, other):
if isinstance(other, (int, long)):
return Rational(other * self._d - self._n, self._d)
elif isinstance(other, (float, complex)):
return other - float(self)
elif isinstance(other, _decimal.Decimal):
return other - self.decimal()
else:
return NotImplemented
def __mul__(self, other):
if isinstance(other, Rational):
return Rational(self._n * other._n, self._d * other._d)
elif isinstance(other, (int, long)):
return Rational(self._n * other, self._d)
elif isinstance(other, (float, complex)):
return float(self) * other
elif isinstance(other, _decimal.Decimal):
return self.decimal() * other
else:
return NotImplemented
__rmul__ = __mul__
def __truediv__(self, other):
if isinstance(other, Rational):
return Rational(self._n * other._d, self._d * other._n)
elif isinstance(other, (int, long)):
return Rational(self._n, self._d * other)
elif isinstance(other, (float, complex)):
return float(self) / other
elif isinstance(other, _decimal.Decimal):
return self.decimal() / other
else:
return NotImplemented
__div__ = __truediv__
def __rtruediv__(self, other):
if isinstance(other, (int, long)):
return Rational(other * self._d, self._n)
elif isinstance(other, (float, complex)):
return other / float(self)
elif isinstance(other, _decimal.Decimal):
return other / self.decimal()
else:
return NotImplemented
__rdiv__ = __rtruediv__
def __floordiv__(self, other):
truediv = self / other
if isinstance(truediv, Rational):
return truediv._n // truediv._d
else:
return truediv // 1
def __rfloordiv__(self, other):
return (other / self) // 1
def __mod__(self, other):
return self - self // other * other
def __rmod__(self, other):
ret

Re: Configuration Files

2004-12-26 Thread M.E.Farmer
>thanks for the replies, guys!

Your welcome, glad I could help.

>(Spending time on these newsgroups is giving me more questions that
>answers heh )
Thats good as long as it motivates you to learn ;)
M.E.Farmer

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


Re: IDLE question

2004-12-26 Thread Kartic
Rolf,

IDLE presents you with an interactive python prompt where you can enter
your code : single statments, class definitions, functions and it will
execute interactively.

>From the IDLE editor, I doubt if you can do what you want. In fact IDLE
will force you to save your code in a file before you can execute it.

To achieve what you describe (select a portion and execute) in IDLE, I
use exec() or alternatively the compiler module both of which can take
statements in a string variable and execute it. This works for me; may
be there is a better way.

Thanks,
--Kartic

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


Re: program in interactive mode

2004-12-26 Thread Alex Martelli
B.G.R. <[EMAIL PROTECTED]> wrote:
   ...
> numline=0
> for line in sys.stdin:
> numline+=1
> workwithline(line)

Consider the alternative:
for numline, line in enumerate(sys.stdin):

Nothing to do with your main program, but still neater...

> that's ok, but if the user only does "./myprog.py" then I got to get into
> interactive mode and show a prompt in every line expecting the user input
> for that line. Problem is I don't know how to tell if I've been "piped" or

sys.stdin.isatty() should serve you well.


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


Re: Complementary language?

2004-12-26 Thread HackingYodel
Thanks for all the suggestions!
I'm going to investigate all of them as time allows.  I must say that 
Eiffel would most certainly expand my mind.  My initial reaction, when
looking at a "Hello World!" program, was "No way!". I had just read
some of SICP and "Pascal is for building pyramids ­ imposing, 
breathtaking, static structures built by armies pushing heavy blocks 
into place. Lisp is for building organisms ­ imposing, breathtaking, 
dynamic structures built by squads fitting fluctuating myriads of 
simpler organisms into place." sprang to mind, with Eiffel replacing 
Pascal in this quote.  Attempting to be fair, I surfed over to 
eiffel.com.  Eiffel has a lot of "high-minded" concepts, and it's easy 
for a rookie, such as myself, to become inundated.  Ironically, while 
watching Eiffel.com's presentation of "Design by Contract", my Gnome 
desk top's control-panel crashed with a segmentation fault error 
(seconds before the spill about how reliable DBC made Eiffel).  Much I 
could learn from Eiffel.

SICP was another invaluable suggestion!  MIT uses it as part of their 
OpenCourse program, so now I have a complete and free course in addition 
to this excellent text.  Thank you.

I will inspect Fortran, Mozart/Oz, Erlang, AliceML, and all other 
recommendations.  Thanks again for the help.  Perhaps I will be able to 
contribute to the Python community soon.
--
http://mail.python.org/mailman/listinfo/python-list


Re: program in interactive mode

2004-12-26 Thread B.G.R.

"Alex Martelli" <[EMAIL PROTECTED]> escribió en el mensaje
news:[EMAIL PROTECTED]
> B.G.R. <[EMAIL PROTECTED]> wrote:
>...
> > numline=0
> > for line in sys.stdin:
> > numline+=1
> > workwithline(line)
>
> Consider the alternative:
> for numline, line in enumerate(sys.stdin):
>
> Nothing to do with your main program, but still neater...
>
> > that's ok, but if the user only does "./myprog.py" then I got to get
into
> > interactive mode and show a prompt in every line expecting the user
input
> > for that line. Problem is I don't know how to tell if I've been "piped"
or
>
> sys.stdin.isatty() should serve you well.
>
>
> Alex


Thank you all very much for your help and tips, that's exactly what I was
looking for.
I guess my knowledge of the libraries is still quite limited. Time to work
on that too.

Regards
RGB



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


Re: sql server support from linux

2004-12-26 Thread Scott David Daniels
Simon Wittber wrote:
I considered doing exactly the same thing a while ago, but was worried
about running into an annoyance like that.  

FWIW, The synchronous Pyro server performed much faster than the
multithreaded version, even under heavy use from 3 machines.
It appeared that while the database queries were serialized, network
IO was not. I infered this from the observation that a large result
set would take around 15 seconds to complete, yet other smaller
queries were able to run about 2-3 seconds after the large query was
started.
Sw.
This is standard "real DB" behavior.  The transactions must appear to
have been executed in _some_ serial order, not the order of arrival.
If the small ops are simply retrieving data, they may return data
from "before" the transaction of of the larger, slower transaction.
Even if they mutate the DB, they may be inserted early if the larger
transaction has not in fact "read" the data they will right.  Also,
in some cases, the smaller ones may be allowed to proceed and force
the larger one to abort if it attempts to acquire locks on the data
they write.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


need some help with threading module...

2004-12-26 Thread chahnaz.ourzikene
Hi all,

This is the first i post in this newsgroup, i hope my english is not too
bad...
Let's get straight to the point ! I have a little probleme using threads in
my little training example :
I wish to create two threads in my application, one thread (the subject)
will increment a variable, and another thread (the controller) will print a
message saying "i am waiting..." or someting like that, until the counter of
the first thread reaches 10 or higher. It will query the first thread object
about the value of that counter in a while loop until that counter reaches
10 or higher...

Here is the code i wrote (it doesn't work):

from threading import *



class Subject(object):


def __init__(self) :

self.counter = 0

t = Timer(0.1,self.doIteratingStuff)

t.start()


def incrementCounter(self,n=1) :

self.counter = self.counter + n

def doIteratingStuff(self) :

for i in range(10) :

self.incrementCounter(4)

print "the counter is now", self.counter


def count(self):

return self.counter



class Controller(object):

def __init__(self, objectToControl) :

self.controlled = objectToControl

self.th = Thread(target = self.stopCounting)

def start(self):

self.th.start()


def stopCounting(self):

i = 0

#while(1):

for i in range(10) :

print "###> waiting... ", i

i = i + 1

if self.controlled.count() >= 10 :

print "it is ten"

return



class Application (object) :

def __init__(self) :

pass

def launch(self) :

self.sub = Subject()

self.control = Controller(self.sub)

self.control.start()





a = Application()

a.launch()

Of course, the indentations are lost since i copied this code from my emacs
on linux, and then paste it on my outlook express (i don't have the net on
linux :(...).

The probleme with the code is that the controler thread never stops !!
that's why the while loop is now commented and replaced by a for loop... I
wish the problem is clear for all and that somebody can give some help !



Thanks for all and merry x-mas and blablablah.

Yacine Chaouche, France.


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


Re: Jython & IronPython Under Active Development?

2004-12-26 Thread HackingYodel
Cameron Laird wrote:
In article <[EMAIL PROTECTED]>, Robert Kern  <[EMAIL PROTECTED]> wrote:
.
.
.
It should be noted that Jim Hugunin no longer works on Jython although 
he did start the project (possibly with others, I'm not sure).
.
.
.
Mostly he started it with others discouraging him, arguing,
"*That*'s one project that'll never fly."
Short story at http://hugunin.net/story_of_jython.html from Jim himself.
:)
--
http://mail.python.org/mailman/listinfo/python-list


Re: program in interactive mode

2004-12-26 Thread Scott David Daniels
B.G.R. wrote:
numline=0
for line in sys.stdin:
numline+=1
workwithline(line)
I'd use:
for numline, line in enumerate(sys.stdin):
workwithline(line)
Note: The line numbers start at 0, but that is often acceptable.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: list IndexError

2004-12-26 Thread Scott David Daniels
Ishwor wrote:
On Thu, 23 Dec 2004 13:57:55 -0300, Batista, Facundo
<[EMAIL PROTECTED]> wrote:
#- True, true.  Maybe you could lobby for copy as a builtin in 
#- Python 3000? 

That's a good idea to me. But copy() as a builtin is not clear if it's
shallow or deep. 
IMHO its preferable to use shallow one as the built-in because deep is
expensive op. for CPU. ~;-)
"deepcopy" is an operation that is less well defined than shallow copy
anyway (and hence shouldn't be a default).  Objects representing
constants may contain a cache (for example) as an efficiency measure,
and "deepcopy" needn't copy such objects.  The only way to safely
do deepcopy is to copy down to immutables, but usually there is a
shallower and faster implementation that depends on application
semantics.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: need some help with threading module...

2004-12-26 Thread M.E.Farmer
> Thanks for all and merry x-mas and blablablah
There is no X in Christmas, and blablablah should read Happy New Year!

>Of course, the indentations are lost since i copied this code from my
emacs
>on linux, and then paste it on my outlook express (i don't have the
net on
>linux :(...).

I have had problems with whitespace being stripped before,  but I just
cannot understand WHY would you post KNOWING it was missing indents.
Fix-it repost and maybe someone might help you.

Hth, 
M.E.Farmer

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


Python 3000, zip, *args and iterators

2004-12-26 Thread Steven Bethard
So, as I understand it, in Python 3000, zip will basically be replaced 
with izip, meaning that instead of returning a list, it will return an 
iterator.  This is great for situations like:

zip(*[iter1, iter2, iter3])
where I want to receive tuples of (item1, item2, item3) from the 
iterables.  But it doesn't work well for a situation like:

zip(*tuple_iter)
where tuple_iter is an iterator to tuples of the form
(item1, item2, item3) and I want to receive three iterators, one to the 
 item1s, one to the item2s and one to the item3s.  I don't think this 
is too unreasonable of a desire as the current zip, in a situation like:

zip(*tuple_list)
where tuple_list is a list of tuples of the form (item1, item2, item3), 
returns a list of three tuples, one of the item1s, one of the item2s and 
one of the item3s.

Of course, the reason this doesn't work currently is that the fn(*itr) 
notation converts 'itr' into a tuple, exhausting the iterator:

>>> def g(x):
... for i in xrange(x):
... yield (i, i+1, i+2)
... print "exhausted"
...
>>> zip(*g(4))
exhausted
[(0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5)]
>>> it.izip(*g(4))
exhausted

>>> x, y, z = it.izip(*g(4))
exhausted
>>> x, y, z
((0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5))
What I would prefer is something like:
>>> zip(*g(4))

>>> x, y, z = zip(*g(4))
>>> x, y, z
(, 
Of course, I can write a separate function that will do what I want 
here[1] -- my question is if Python's builtin zip will support this in 
Python 3000.  It's certainly not a trivial change -- it requires some 
pretty substantially backwards incompatible changes in how *args is 
parsed for a function call -- namely that fn(*itr) only extracts as many 
of the items in the iterable as necessary, e.g.

>>> def h(x, y, *args):
... print x, y, args
... print list(it.islice(args, 4))
...
>>> h(*it.count())
0 1 count(2)
[2, 3, 4, 5]
So I guess my real question is, should I expect Python 3000 to play 
nicely with *args and iterators?  Are there reasons (besides backwards 
incompatibility) that parsing *args this way would be bad?

Steve
[1] In fact, with the help of the folks from this list, I did:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302325
--
http://mail.python.org/mailman/listinfo/python-list


Re: need some help with threading module...

2004-12-26 Thread chahnaz.ourzikene
I think it is more suitable in this form...



from threading import *



class Subject(object):


def __init__(self) :

self.counter = 0

t = Timer(0.1,self.doIteratingStuff)

t.start()


def incrementCounter(self,n=1) :

self.counter = self.counter + n

def doIteratingStuff(self) :

for i in range(10) :

self.incrementCounter(4)

print "the counter is now", self.counter


def count(self):

return self.counter



class Controller(object):

def __init__(self, objectToControl) :

self.controlled = objectToControl

self.th = Thread(target = self.stopCounting)

def start(self):

self.th.start()


def stopCounting(self):

i = 0

#while(1):

for i in range(10) :

print "###> waiting... ", i

i = i + 1

if self.controlled.count() >= 10 :

print "it is ten"

return



class Application (object) :

def __init__(self) :

pass

def launch(self) :

self.sub = Subject()

self.control = Controller(self.sub)

self.control.start()





a = Application()

a.launch()



Thanls for all.



Yacine Chaouche, France.


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


Re: Optional Static Typing

2004-12-26 Thread Luis M. Gonzalez
Robert Kern wrote:
> Automatic type inferencing is great, but sometimes the inference is
> "object". Being able to supply more information about types helps
> Starkiller keep the inferences tight and specific.

Hmm... I'm not an expert in this subject at all, but I think that when
the  inference is "object", as you said, is because the type couldn't
be inferred so it defaults to object, which is the more general type of
all.
For example, this is what happens in Boo, which is the only language I
know (a little bit) that uses type inference.

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


anit alias and vpython

2004-12-26 Thread FLChamp
I have created a simulation of the solar system which is graphically
represented using vpython. I was wondering in there is some way to make
the orbit paths look better (I was thinking of anti aliasing the
lines). I havent been able to find any information on this so I assume
its not supported but just wanted to check, or see if anyone had
suggestions on how to make the graphics look better

Many Thanks

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


Re: Complementary language?

2004-12-26 Thread gabriele renzi
Alex Martelli ha scritto:

Nolo contendere (not having looked much into Alice yet), but are there
stand-alone didactical materials for Alice as there are for Oz?  
> It
> seemed to me that the available materials for Alice basically take SML
> somewhat for granted, while Oz does come with tutorials which make no
> analogous assumptions.  If you're recommending Alice as the second
> language for somebody whose first and only language so far is Python,
> what URLs and/or books would you point them to, for self-stufy?
>
>
> Alex
probably not, AFAIK, and that's something I did'nt think of, thanks for 
pointing out.
Anyway, the Alice homepage references some ml tutorials for that subset 
of the language and documentation for the specific extensions.
Probably a unified tutorial would be much better, anyway, I agree.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tricks to install/run Python on Windows ?

2004-12-26 Thread Luke Skywalker
On Sun, 26 Dec 2004 19:43:24 +0100, StepH
<[EMAIL PROTECTED]> wrote:
>What's wrong ?  Python seems terific, but the tools...

You could uninstall both Python and PyWin32 a.k.a. PythonWin, and
install ActiveState Python which includes both in one tool. Then,
check if the PythonWin IDE works fine.

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


Re: need some help with threading module...

2004-12-26 Thread M.E.Farmer

Just a warning!
Threads and newbies don't mix well,
many pitfalls and hard to find bugs await you.
I would avoid using threads if at all possible.

Now we have all that over lets see some code.

py> import threading
py> class Test(threading.Thread):
...def run(self):
... x = 0
... while x < 10:
... print x
... x += 1
... print " Ending"
Use it like this:
py> Test().start()

There are other ways to do this, but you need to do a web  search on
threading.py , there are many examples out there. 
hth,
M.E.Farmer

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


Re: list addition methods compared.

2004-12-26 Thread Ishwor
On Sun, 26 Dec 2004 04:57:17 -0500, Terry Reedy <[EMAIL PROTECTED]> wrote:
> 
> "Ishwor" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> > Hi all
> > I have just wrote a small script to compare the speed of list addition
> > methods.
> 
> There are two meanings of 'list addition':
> 
> li = li+[item] *copies* the list and adds item
> 
> li += [item] is the same as li.extend([item]) which add item to the end of
> the list *without* copying.
> 
> Of course, extending a list is faster than copying + one more.
> 

I agree with you that list extending is faster way to add as compared
to method 1. also that method 2 is mapped to 'extend()' anyway, but
why is the method 3 ( l3.extend() ) in my example code talking only
nearly 1% of time to complete as compared to method 1/2??? I think
there is a problem with the code but i don't see where. :-(

> Terry J. Reedy
Thanks Terry for yet another small (really small) step towards enlightment. 

[snip]

-- 
cheers,
Ishwor Gurung
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: IDLE question

2004-12-26 Thread Ishwor
On Sun, 26 Dec 2004 13:02:01 +0100, Rolf Wester <[EMAIL PROTECTED]> wrote:
> Hi,
> 
> I would like to use IDLE as interactively as I can with Emacs. In Emacs
> I can send a marked region to the Python interpreter. Is there any way
> to do the same thing with IDLE?
Although i don't use anything much beside IDLE,  vim for coding, AFAIK
IDLE can't do that.
IDLE opens up python shell. Within that shell you type in your script
, commands and create objects as such..The interpreter will
execute your code then.
IDLE looks like this when you fire it up.

Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.


Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface.  This connection is not visible on any external
interface and no data is sent to or received from the Internet.


IDLE 1.1  
>>> # this is the Python shell.
>>> 
>>> l = ['spam','eggs'] # you assign and create a list variable called l
>>> l # prints the content of l. 
['spam', 'eggs']

[snip]

-- 
cheers,
Ishwor Gurung
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list addition methods compared.

2004-12-26 Thread Terry Reedy

"Ishwor" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Sun, 26 Dec 2004 04:57:17 -0500, Terry Reedy <[EMAIL PROTECTED]> wrote:
>>
>> "Ishwor" <[EMAIL PROTECTED]> wrote in message
>> news:[EMAIL PROTECTED]
>> > Hi all
>> > I have just wrote a small script to compare the speed of list addition
>> > methods.
>>
>> There are two meanings of 'list addition':
>>
>> li = li+[item] *copies* the list and adds item
>>
>> li += [item] is the same as li.extend([item]) which add item to the end 
>> of
>> the list *without* copying.
>>
>> Of course, extending a list is faster than copying + one more.
>>
>
> I agree with you that list extending is faster way to add as compared
> to method 1. also that method 2 is mapped to 'extend()' anyway,

As near as I could tell from what you posted (and I snipped), method 2 was 
about the same as 1 and not mapped to extend().

> but
> why is the method 3 ( l3.extend() ) in my example code talking only
> nearly 1% of time to complete as compared to method 1/2???

Because writing 1 pointer takes 1/100th as long as writing 100 pointers (in 
the C code of CPython).  You used lists long enough for the difference 
between O(n) and O(n**2) behavior to show.

> Thanks Terry for yet another small (really small) step towards 
> enlightment.

You're welcome.  Hope this is another small step ;-)

Terry J. Reedy



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


Re: list addition methods compared.

2004-12-26 Thread Ishwor
On Sun, 26 Dec 2004 18:37:35 -0500, Terry Reedy <[EMAIL PROTECTED]> wrote:
> 
> "Ishwor" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> > On Sun, 26 Dec 2004 04:57:17 -0500, Terry Reedy <[EMAIL PROTECTED]> wrote:
> >>
> >> "Ishwor" <[EMAIL PROTECTED]> wrote in message
> >> news:[EMAIL PROTECTED]
> >> > Hi all
> >> > I have just wrote a small script to compare the speed of list addition
> >> > methods.
> >>
> >> There are two meanings of 'list addition':
> >>
> >> li = li+[item] *copies* the list and adds item
> >>
> >> li += [item] is the same as li.extend([item]) which add item to the end
> >> of
> >> the list *without* copying.
> >>
> >> Of course, extending a list is faster than copying + one more.
> >>
> >
> > I agree with you that list extending is faster way to add as compared
> > to method 1. also that method 2 is mapped to 'extend()' anyway,
> 
> As near as I could tell from what you posted (and I snipped), method 2 was
> about the same as 1 and not mapped to extend().
ah.. wellwhat to tell?? i wanted the method 2 to be l2.extend() @[EMAIL 
PROTECTED]
hhah.. thanks for that anyway.
 
> > but
> > why is the method 3 ( l3.extend() ) in my example code talking only
> > nearly 1% of time to complete as compared to method 1/2???
> 
> Because writing 1 pointer takes 1/100th as long as writing 100 pointers (in
> the C code of CPython).  You used lists long enough for the difference
> between O(n) and O(n**2) behavior to show.

theres the correct output AFAIK is -

C:\Python24\file\PyFiles>python -O listadditioncompare.py
@@@
Method 1 done in (average finish time(out of 3)) - 1.358676
Method 2 done in (average finish time(out of 3)) - 0.0213334560
Method 3 done in (average finish time(out of 3)) - 0.0256667137
@@@

C:\Python24\file\PyFiles>python -O listadditioncompare.py
@@@
Method 1 done in (average finish time(out of 3)) - 1.3593332767
Method 2 done in (average finish time(out of 3)) - 0.0306665897
Method 3 done in (average finish time(out of 3)) - 0.0213334560
@@@

C:\Python24\file\PyFiles>python -O listadditioncompare.py
@@@
Method 1 done in (average finish time(out of 3)) - 1.3593332767
Method 2 done in (average finish time(out of 3)) - 0.0203335285
Method 3 done in (average finish time(out of 3)) - 0.0203332901
@@@

so indeed method 2 (l2.extend() ) is the fastest ?? In 2/3 times,
method 3 (l3 += [x] seems faster than method 1/2 in my P2.4GHZ machine
with 512mb??? :-(
Could u run the code in your machine and perhaps and let me know what
the average speed is??
The code is -

#compare the speeds of 3 different type of list element addition
import time
def method(TYPE):
if TYPE == 1:
l1 = [];
finish = 0;
start = 0;
start = time.time();
for y in range(0,3):
for x in range(0,1):
l1 = l1 + [x];# type 1
l1 = [];
finish += time.time();
averageFinish = finish/3;
#m = float(finish-start);
print "Method 1 done in (average finish time(out of 3)) -
%.10f" %(averageFinish-start);

if TYPE == 2:
l2 = [];
finish = 0;
start = 0;
start = time.time();
for y in range(0,3):
for x in range(0,1):
l2.extend([x]);# type 2
l2 = [];
finish += time.time();  
averageFinish = finish/3;
#m = float(finish-start);
print "Method 2 done in (average finish time(out of 3)) -
%.10f" %(averageFinish-start);

if TYPE == 3:
l3 = [];
finish = 0;
start = 0;
start = time.time();
for y in range(0,3):
for x in range(0,1):
l3 +=  [x];# type 3
l3 = [];
finish += time.time();
averageFinish = finish/3;
#m = float(finish-start);
print "Method 3 done in (average finish time(out of 3)) -
%.10f" %(averageFinish-start);

print "@@@";
method(1);
method(2);
method(3);
print "@@@";


[snip]


Thanks. ;-)
-- 
cheers,
Ishwor Gurung
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: need some help with threading module...

2004-12-26 Thread Daniel Bickett
I found your object-oriented approach, while admirable, a little
muddled. So rather than modify your code, I simply took the paragraph
you wrote describing the scenario and wrote my own.[1]

Instead of having the Controller query the Subject (not exactly
plausible), I had it wait for a signal (threading.Event) as set by the
Subject. You could also have it query a queue, as that is a generally
accepted and thread-safe object to use, but for this purpose I chose an
event and a global variable. (I'm aware that some would look down on
this, but I didn't see a problem, as it was only modified by one thread
amd printed by the other.)

Daniel Bickett

NOTES:

[1] Google killed my whitespace (as spaces _and_ tabs...) in the
previews, so I pasted it on Nopaste:
http://rafb.net/paste/results/KilM6t70.html

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


Re: Tricks to install/run Python on Windows ?

2004-12-26 Thread Ishwor
On Sun, 26 Dec 2004 19:43:24 +0100, StepH
<[EMAIL PROTECTED]> wrote:
> Hi,
> 
> I'm new to Python.  I'm working under XP, and I've alot of prob. (not
> with the langage itself, but with the tools):
> 
> I've install Pyhton 2.4 in C:\Python24, using the .msi windows installer.
> Then, I've install "PythonWin" (the last build-203).
> 
Doesn't IDLE come with Python2.4??? Its pretty good if you haven't tried it ;-)
If you haven't searched for it yet, try looking in
C:\Python24\lib\idlelib for "idle.py".
To start it simply do "python idle.py" in the prompt. You should also
probably have a batch script named idle.bat which wraps the idle.py.

> I'll try to summerize my prob.:
> 
> 1./ The PythonWin IDE is not stable at all.  Sometimes it exit without
> reason, or don't stop on breakpoint, etc...  Are some of you aware of
> bugs in the last PyhtonWin IDE release ?  I've to open the TaskManager.
>  AT some point, i'm not able to (p.e.) open a file under it !!!
> 
> 2./ I've try to download Komode (he 3.1 personnal).  I've also prob.
> with it !  Also, the breakpoint seems to not always work...
> 
> 3./ So, i've try to use the command line, but i've to manualy change the
> code page od my dos box from 437 to 1252 (i'm live in belgium).  And
> i've not try how to do that permanently !
> 
> 4./ Before, I had Python23 and it seems that when unstalling it, all the
> keys in the registry are not removed at all.  When i've install the 2.4,
> I had a mismatch which force me to complety re-install the machine (I'm
> not an expert of the registry)...
> 
> 5./ Installing komodo seems to "block" pythonwinIDE completly...
> 
> What's wrong ?  Python seems terific, but the tools...
> 
I have no clue what the *tools* are doing for you and i feel sorry for
that but as i said if you try IDLE its pretty good.
the link http://www.python.org/idle/ should be able to provide you with info.



> So... maybe i've to try BlackAdder ?
> --
> http://mail.python.org/mailman/listinfo/python-list
> 


-- 
cheers,
Ishwor Gurung
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tricks to install/run Python on Windows ?

2004-12-26 Thread Daniel Bickett
While I don't have any solutions for your problems outlined above, you
certainly don't need to limit yourself to the "tools" you've been
exposed to (nor should you make a generalization based on them).

If PythonWin is giving you that much trouble, you could optionally use
a different editor. I use DrPython[1] from time to time.

Also, when you say that you had to reinstall your "machine", surely
you didn't mean your operating system? I don't think it would be too
difficult to find a list of registry keys that Python uses, (or,
indeed, inquiring towards the values of those that 2.4 uses and
manually adding them) but I seriously doubt it involves any that your
system's stability balances on.

Daniel Bickett

NOTES:
[1] http://drpython.sf.net/


On Sun, 26 Dec 2004 19:43:24 +0100, StepH
<[EMAIL PROTECTED]> wrote:
> Hi,
> 
> I'm new to Python.  I'm working under XP, and I've alot of prob. (not
> with the langage itself, but with the tools):
> 
> I've install Pyhton 2.4 in C:\Python24, using the .msi windows installer.
> Then, I've install "PythonWin" (the last build-203).
> 
> I'll try to summerize my prob.:
> 
> 1./ The PythonWin IDE is not stable at all.  Sometimes it exit without
> reason, or don't stop on breakpoint, etc...  Are some of you aware of
> bugs in the last PyhtonWin IDE release ?  I've to open the TaskManager.
>   AT some point, i'm not able to (p.e.) open a file under it !!!
> 
> 2./ I've try to download Komode (he 3.1 personnal).  I've also prob.
> with it !  Also, the breakpoint seems to not always work...
> 
> 3./ So, i've try to use the command line, but i've to manualy change the
> code page od my dos box from 437 to 1252 (i'm live in belgium).  And
> i've not try how to do that permanently !
> 
> 4./ Before, I had Python23 and it seems that when unstalling it, all the
> keys in the registry are not removed at all.  When i've install the 2.4,
> I had a mismatch which force me to complety re-install the machine (I'm
> not an expert of the registry)...
> 
> 5./ Installing komodo seems to "block" pythonwinIDE completly...
> 
> What's wrong ?  Python seems terific, but the tools...
> 
> So... maybe i've to try BlackAdder ?
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3000, zip, *args and iterators

2004-12-26 Thread Terry Reedy

"Steven Bethard" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> So, as I understand it, in Python 3000, zip will basically be replaced 
> with izip, meaning that instead of returning a list, it will return an 
> iterator.

I think it worth repeating that Python 3 is at yet something of a 
pipedream, as indicated by the joke name Python 3000 (that also being in 
part a satire on Windows 2000, and the like).  So, while Guido has said he 
would like to make Python iterator-oriented in the way that it used to be 
list-oriented, nothing is set in stone, certainly not the details.

Guido has also said that he would like there to be funding to pay him to 
spend a year on its development.  He wants to take that long so there will 
be adequate discussion, thought, and testing so he can 'get it right' as 
least in the sense of having everything work well together.

Terry J. Reedy



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


Re: Unicode entries on sys.path

2004-12-26 Thread "Martin v. Löwis"
Just wrote:
The real question here is: why does Python not support arbitrary
Unicode strings on sys.path? It could, in principle, atleast on
Windows NT+ (and also on OSX). Patches are welcome.

Works for me on OSX 10.3.6, as it should: prior to using the sys.path 
entry, a unicode string is encoded with Py_FileSystemDefaultEncoding. 
I'm not sure how well it works together with zipimport, though.
As Vincent's message already implies, I'm asking for Windows patches.
In a Windows system, there are path names which just *don't have*
a representation in the file system default encoding. So you just
can't use the standard file system API (open, read, write) to access
those files - instead, you have to use specific Unicode variants
of the file system API.
The only operating system in active use that can reliably represent
all file names in the standard API is OS X. Unix can do that as
long as the locale is UTF-8; for all other systems, there are
restrictions when you try to use the file system API to access
files with "funny" characters.
Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: list addition methods compared.

2004-12-26 Thread Steven Bethard
Ishwor wrote:
Could u run the code in your machine and perhaps and let me know what
the average speed is??
The code is -
[snip code not using timeit]
Are you aware of the timeit module?  It can do most of these timings for 
you.  Here's the code I used:

-- extend.py --
def add(items):
lst = []
for item in items:
lst = lst + [item]
def iadd(items):
lst = []
for item in items:
lst += [item]
def extend(items):
lst = []
for item in items:
lst.extend([item])
def extend_ext(items):
lst = []
ext = lst.extend
for item in items:
ext([item])
def append(items):
lst = []
for item in items:
lst.append(item)
--
and here's the commands I ran (using Python 2.4)[1]:
$ python -m timeit -s "import extend; items = range(1)" 
"extend.add(items)"
10 loops, best of 3: 588 msec per loop

$ python -m timeit -s "import extend; items = range(1)" 
"extend.iadd(items)"
100 loops, best of 3: 9.68 msec per loop

$ python -m timeit -s "import extend; items = range(1)" 
"extend.extend(items)"
100 loops, best of 3: 11.5 msec per loop

$ python -m timeit -s "import extend; items = range(1)" 
"extend.extend_ext(items)"
100 loops, best of 3: 9.09 msec per loop

$ python -m timeit -s "import extend; items = range(1)" 
"extend.append(items)"
100 loops, best of 3: 4.5 msec per loop

A few things worth noting:
(1) I didn't see the top of this thread, but I'm assuming that you've 
got a conditional or something in your real loop or you could just use 
lst.extend(items) without ever iterating over the items list.  Your real 
code may actually require extend-style functionality, but as the results 
above show, if you really only have one item to add, list.append is 
definitely the better way to go.

(2) Yes, using += is slightly faster than list.extend, but only because 
"lst.extend" requires an extra attribute lookup.  If you factor that out 
(like I did with the line "ext = lst.extend") then list.extend is 
slightly faster.  (Not surprising, as the function list_inplace_concat 
(+=) calls the function listextend (list.extend) in listobject.c)

(3) That being said, extend_ext is almost certainly premature 
optimization. =)

Steve
[1] You can still use timeit without Python 2.4, but you'll have to call 
timeit.py directly instead of the "python -m timeit" command I used.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3000, zip, *args and iterators

2004-12-26 Thread Steven Bethard
Terry Reedy wrote:
"Steven Bethard" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

So, as I understand it, in Python 3000, zip will basically be replaced 
with izip, meaning that instead of returning a list, it will return an 
iterator.
I think it worth repeating that Python 3 is at yet something of a 
pipedream, as indicated by the joke name Python 3000 (that also being in 
part a satire on Windows 2000, and the like).
True, true.  And worth repeating.
So, while Guido has said he 
would like to make Python iterator-oriented in the way that it used to be 
list-oriented, nothing is set in stone, certainly not the details.
Right, though my understanding of PEP 3000[1] is that though "Python 
3000"  may never exist, the PEP is there as a road-map of where Python 
as a language would like to go.  I guess the point of my question is to 
find out if this kind of nice interaction of *args and iterators is 
something that's in the road-map.  If it is, then maybe there are parts 
of it that could be implemented in a way that's backwards compatible, 
even if the full system wouldn't be available for some time.  (Perhaps 
something along the lines of "from __future__ import iter_args".)

Steve
[1] http://www.python.org/peps/pep-3000.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: WxButton

2004-12-26 Thread LutherRevisited
That's kindof where I want to go, how can I detect whether or not my button has
focus.  Basically I only want to press it with enter if it has focus.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python on Linux

2004-12-26 Thread Austin
On Red Hat 9, Python is installed by default and it's version is 2.2.2
If I want to upgrade Python to 2.3.4(newer version), how could I do?
If I compile source code of Python, how do I uninstall the old version?
I tried rpm packages but failed with dependence.
Could everyone give me a advise?


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


Re: Python on Linux

2004-12-26 Thread Paul Rubin
"Austin" <[EMAIL PROTECTED]> writes:
> On Red Hat 9, Python is installed by default and it's version is 2.2.2
> If I want to upgrade Python to 2.3.4(newer version), how could I do?
> If I compile source code of Python, how do I uninstall the old version?
> I tried rpm packages but failed with dependence.


I didn't try the rpm's.  Just get the source tarball, configure, make,
and make install.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows XP - cron or scheduler for Python?

2004-12-26 Thread Esmail Bonakdarian
[EMAIL PROTECTED] wrote:
Hi,
I thought I'd throw in my 2 cents worth.
I have written a freeware task scheduler that might be of interest to
you.
It's called Kirby Alarm And Task Scheduler.
Over 16000 people around the world use it.
Hi,
Was this written in Python? If so 2 quick questions:
1. what did you use to write the GUI?
2. any chance we could see some of the code for this? (I understand
   if not of course)
Thanks,
Esmail
ps: I downloaded the program just a few minutes ago to check out.
--
http://mail.python.org/mailman/listinfo/python-list


Re: list addition methods compared.

2004-12-26 Thread Nick Coghlan
Steven Bethard wrote:
(1) I didn't see the top of this thread, but I'm assuming that you've 
got a conditional or something in your real loop or you could just use 
lst.extend(items) without ever iterating over the items list.  Your real 
code may actually require extend-style functionality, but as the results 
above show, if you really only have one item to add, list.append is 
definitely the better way to go.
Just to prove Steven's point about avoiding the for loop if you can (timings 
here use the same timeit command as Steven did):

"extend.add(items)"
10 loops, best of 3: 469 msec per loop
"extend.iadd(items)"
100 loops, best of 3: 6.88 msec per loop
"extend.extend(items)"
100 loops, best of 3: 8.77 msec per loop
"extend.extend_ext(items)"
100 loops, best of 3: 6.56 msec per loop
"extend.append(items)"
100 loops, best of 3: 3.68 msec per loop
"extend.extend_no_loop(items)"
1 loops, best of 3: 82.3 usec per loop
The definition of 'extend_no_loop' is:
def extend_no_loop(items):
  lst = []
  lst.extend(items)
Note that if you do have a conditional expression in the for loop (e.g. "only 
add items greater than zero", it is worth checking the timings for calling 
extend with a generator expression or list comprehension that filters out the 
values you don't want)

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: A Revised Rational Proposal

2004-12-26 Thread Nick Coghlan
Mike Meyer wrote:
Regarding str() and repr() behaviour, Ka-Ping Yee proposes that repr() have
the same behaviour as str() and Tim Peters proposes that str() behave like the
to-scientific-string operation from the Spec.
This looks like a C & P leftover from the Decimal PEP :)
Otherwise, looks good.
Regards,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Windows XP - cron or scheduler for Python?

2004-12-26 Thread ian
Hi Esmail,
Kirby Alarm is written in Clarion.
Sorry, but I want to keep the source code to myself.
Ian

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


Re: Tricks to install/run Python on Windows ?

2004-12-26 Thread It's me
Try running with the latest version of Python 2.3 instead of 2.4.   May be
you would have better luck.

I've found similar stability problems with some of the tools (eventhough
they have 2.4 releases) as well.

I switched back to 2.3 and so far I have no complains.



"StepH" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hi,
>
> I'm new to Python.  I'm working under XP, and I've alot of prob. (not
> with the langage itself, but with the tools):
>
> I've install Pyhton 2.4 in C:\Python24, using the .msi windows installer.
> Then, I've install "PythonWin" (the last build-203).
>
> I'll try to summerize my prob.:
>
> 1./ The PythonWin IDE is not stable at all.  Sometimes it exit without
> reason, or don't stop on breakpoint, etc...  Are some of you aware of
> bugs in the last PyhtonWin IDE release ?  I've to open the TaskManager.
>   AT some point, i'm not able to (p.e.) open a file under it !!!
>
> 2./ I've try to download Komode (he 3.1 personnal).  I've also prob.
> with it !  Also, the breakpoint seems to not always work...
>
> 3./ So, i've try to use the command line, but i've to manualy change the
> code page od my dos box from 437 to 1252 (i'm live in belgium).  And
> i've not try how to do that permanently !
>
> 4./ Before, I had Python23 and it seems that when unstalling it, all the
> keys in the registry are not removed at all.  When i've install the 2.4,
> I had a mismatch which force me to complety re-install the machine (I'm
> not an expert of the registry)...
>
> 5./ Installing komodo seems to "block" pythonwinIDE completly...
>
> What's wrong ?  Python seems terific, but the tools...
>
> So... maybe i've to try BlackAdder ?


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


Re: A Revised Rational Proposal

2004-12-26 Thread Nick Coghlan
Dan Bishop wrote:
Mike Meyer wrote:
This version includes the input from various and sundry people.
Thanks
to everyone who contributed.
  
PEP: XXX
Title: A rational number module for Python
...
Implicit Construction
-
When combined with a floating type - either complex or float - or a
decimal type, the result will be a TypeError.  The reason for this is
that floating point numbers - including complex - and decimals are
already imprecise.  To convert them to rational would give an
incorrect impression that the results of the operation are
precise. The proper way to add a rational to one of these types is to
convert the rational to that type explicitly before doing the
operation.

I disagree with raising a TypeError here.  If, in mixed-type
expressions, we treat ints as a special case of rationals, it's
inconsistent for rationals to raise TypeErrors in situations where int
doesn't.

2 + 0.5
2.5
Rational(2) + 0.5
TypeError: unsupported operand types for +: 'Rational' and 'float'
Mike's use of this approach was based on the discussion around PEP 327 
(Decimal).
The thing with Decimal and Rational is that they're both about known precision. 
For Decimal, the decision was made that any operation that might lose that 
precision should never be implicit.

Getting a type error gives the programmer a choice:
1. Take the precision loss in the result, by explicitly converting the Rational 
to the imprecise type
2. Explicitly convert the non-Rational input to a Rational before the operation.

Permitting implicit conversion in either direction opens the door to precision 
bugs - silent errors that even rigorous unit testing may not detect.

The seemingly benign ability to convert longs to floats implicitly is already a 
potential source of precision bugs:

Py> bignum = 2 ** 62
Py> bignum
4611686018427387904L
Py> bignum + 1.0
4.6116860184273879e+018
Py> float(bignum) != bignum + 1.0
False
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: methods of addition in Python

2004-12-26 Thread Nick Coghlan
Ishwor wrote:
As my earlier mail didn't make it c.l.py because it had the heading
"LIST Addition compared", probably it was blocked by the mail server.
;-)
The original made it - just remember that Usenet and mailing lists aren't 
instant messaging. It can take time for things to show up :)

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: WxButton

2004-12-26 Thread Kartic
Have you explored the wxPython Demo application? It is a pretty helpful
learning tool.

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


Re: Python on Linux

2004-12-26 Thread Nick Coghlan
Paul Rubin wrote:
"Austin" <[EMAIL PROTECTED]> writes:
On Red Hat 9, Python is installed by default and it's version is 2.2.2
If I want to upgrade Python to 2.3.4(newer version), how could I do?
If I compile source code of Python, how do I uninstall the old version?
I tried rpm packages but failed with dependence.

I didn't try the rpm's.  Just get the source tarball, configure, make,
and make install.
Although one might argue that make altinstall is a safer approach ;)
(Any scripts using "/usr/bin/env python" would then continue to use Python 2.2)
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Windows XP - cron or scheduler for Python?

2004-12-26 Thread Esmail Bonakdarian
[EMAIL PROTECTED] wrote:
Hi Esmail, Kirby Alarm is written in Clarion. Sorry, but I want to
keep the source code to myself.
Hi, thanks for the info, and no problem.
I'm learning Python, and looking at other's code has been a
great way to learn. (As an aside, I was thinking of this
sort of application as a good project).
cheers,
Esmail
--
http://mail.python.org/mailman/listinfo/python-list


Are tuple really immutable?

2004-12-26 Thread Chris
Hi

Consider the following tuples:
>>> t = ([1],[2])
>>> u = (1,2)
>>> v = ('1','2')
>>> t
([1], [2])
>>> u
(1, 2)
>>> v
('1', '2')
>>> t.__hash__()
Traceback (most recent call last):
File "", line 1, in ?
TypeError: list objects are unhashable
>>> u.__hash__()
219750523
>>> v.__hash__()
-1786881095
>>> d = dict()
>>> d[t] = 't'
Traceback (most recent call last):
File "", line 1, in ?
TypeError: list objects are unhashable
>>> d[u] = 'u'
>>> d[v] = 'v'
>>> d
{('1', '2'): 'v', (1, 2): 'u'}

t, u and v are all tuples. t and v elements are sequences.
Yet, t cannot be a dictionnary key because its elements are mutable.

1) Given a tuple, how can I know if it can be a dictionnary key or not?

Of course I could call __hash__ and catch for a TypeError exception,
but I'm  looking for a better way to do it.

2) Would it be possible to have a "ismutable" function or method? Like:
>>> t.ismutable()
True, well maybe not...
>>> u.ismutable()
False
>>> u.ismutable()
False

3) In this example, is t considered mutable or not?
"Tuple are immutable" says the doc, but:
>>> t[0].append(0)
>>> t
([1, 0], [2])

The tuple is immutable but its elements can be mutable: I tend to think
that it means that the tuple is mutable. Indeed, it changed!

4) Even more confusing: I had the following strange result:
(with both Python 2.3.3 and 2.4)
>>> t[0]+=[1]
Traceback (most recent call last):
File "", line 1, in ?
TypeError: object doesn't support item assignment
>>> t
([1, 0, 1], [2])
There was an exception, but the list was still changed!?

Chris

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


Detecting if a program is currently running.

2004-12-26 Thread Brian
On a Slackware 9.1 box, I'm trying to detect if mpg123 is currently 
running/playing a song so that when the song is done, it'll play the next 
in the list.  The problem is that popen'ing ps doesn't always give a 
correct return.  My function is below and I added a second check that runs 
1 second later which sometimes works, sometimes doesn't.

Here's my function:

def pid_defunct():
#1 = defunct processes
#2 = show is currently playing
#0 = no mpg123 processes found
t = os.popen( "ps axc | grep '[mpg123] '" ).read()
if len(t) > 0:
return 1
else:
t = os.popen( "ps axc | grep 'mpg123'" ).read()
if len(t) > 0:
return 2
else:
print "Check 1: mpg123 is dead"
#Check twice, because popen doesn't always return 
   #correct value
time.sleep(1)
t = os.popen( "ps axc | grep 'mpg123'" ).read()
if len(t) > 0:
print "Check 1 was wrong"
return 2
else:
print "Check 2: mpg123 is dead"
return 0


This function is run during each iteration of a loop with a time.sleep(1) 
executed right before it.  Is there a better way to make this work?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedding: forcing an interpreter to end

2004-12-26 Thread dan charnitsky
>> I may need to reconsider if Python is appropriate;
>> the other possibiities are javascript or lua.
> Lisp/Scheme?
> (See http://tinyscheme.sourceforge.net/download.html

Thanks for the pointer.  After some preliminary
evaluation, I'll probably try to move forward
prototyping with Lua.  I't looks like it will be much
simpler to port and the resulting library will be much
smaller (less than 100kB).  One nice thing about the
Lua C API that I liked is that the interpreter state
is passed in each call.  So, there is no need for GIL
or saving/restoring thread state.  I wish (hope)
Python will move in that direction along with scaling
down more easily for embedded use.

> The problem is with Python's build proces, it 1'st
> created pgen and then
> use it for the next stage.
> This makes cross compilation very intersting :-)

Have you been able to cross compile Python and port it
to ucLinux (or a smaller OS)?  I'd hate to just give
up on Python.  Do you know if there are an embedded
Python SIGs?



__ 
Do you Yahoo!? 
Yahoo! Mail - Find what you need with new enhanced search.
http://info.mail.yahoo.com/mail_250
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: WxButton

2004-12-26 Thread LutherRevisited
Yes I have actually, I still can't figure out how to have my application detect
if a control has focus.  If I could, I could just use the keydown event with an
if statement to push my button when it has focus and enter is pressed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are tuple really immutable?

2004-12-26 Thread John Roth
"Chris" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
Hi
3) In this example, is t considered mutable or not?
"Tuple are immutable" says the doc, but:
t[0].append(0)
t
([1, 0], [2])
The tuple is immutable but its elements can be mutable: I tend to think
that it means that the tuple is mutable. Indeed, it changed!
Well, it did and it didn't. If you went in and did an
id() on each element, you'd discover that the actual
objects didn't change: the exact same ids were in
the exact same slots before and after. What you're
seeing is the way the str() and repr() functions print
the values of embedded objects, not the ids.
4) Even more confusing: I had the following strange result:
(with both Python 2.3.3 and 2.4)
t[0]+=[1]
Traceback (most recent call last):
File "", line 1, in ?
TypeError: object doesn't support item assignment
t
([1, 0, 1], [2])
There was an exception, but the list was still changed!?
I consider that an error, but I've had several people
tell me that it's the way it's supposed to be.
I simply quit trying to get the point across.
As far as I'm concerned, the behavior is simply
wrong. Since mutating the object didn't change
the id, it shouldn't try to replace the object in
the tuple.
John Roth
Chris
--
http://mail.python.org/mailman/listinfo/python-list


Re: Complementary language?

2004-12-26 Thread Mike Meyer
[EMAIL PROTECTED] (Alex Martelli) writes:

> Objective-C is cool... on the Mac; I'm not sure how well-supported it is
> elsewhere, though.  In addition to C's advantages, it would let you make
> Cocoa GUIs on the Mac easily (with PyObjC &c).  But then, the right way
> to study Obj-C from scratch is no doubt to start with C, anyway.

Objective-C is part of the Gnu Compiler Collection. As such, it's
probably easy to find a working compiler. But I agree - you probably
want to start with C.

As an aside, if you want to study Eiffel, the book to buy is _Object
Oriented Software Construction_, second edition, by Bertrand
Meyer. Everybody doing OO software should read this book, as the
lessons about constructing inheritance hierarchies are invaluable,
even if the language won't enforce them for you.

   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: Optional Static Typing - Haskell?

2004-12-26 Thread Mike Meyer
[EMAIL PROTECTED] (Alex Martelli) writes:

> Mike Meyer <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] (Alex Martelli) writes:
>> > Mind you, I personally _like_ the concept of describing
>> > an interface separately, even in a different language (Corba's IDL, say)
>> > that's specialized for the task.  But it doesn't seem to be all that
>> > popular... without such separation, modularity plus static checking
>> > appears to imply bottom->up coding: you need to compile modules in some
>> > topologically sorted order compatible with the "X uses Y" relation.
>> Personally, I hate declaring the interface separately, whether in the
>> same language or another language. 
> Yeah, so do many people -- as I mentioned, it's not all that popular.
> Personally, I don't see _why_

Because it violates the principle of "Once and only once". If the
interface is described in two places, that means it's possible to
update one and forget to update the other. That's not possible if the
interface is defined once and only once. I've forgotten to update my
IDL more than once.

> But then, the above criticism applies: if interface and implementation
> of a module are tightly coupled, you can't really do fully modular
> programming AND static typing (forget type inferencing...).

I beg to differ. Eiffel manages to do this quite well. Then again,
every Eiffel environment comes with tools to extract the interface
information from the code. With SmartEiffel, it's a command called
"short". Doing "short CLASSNAME" is like doing "pydoc modulename",
except that it pulls routine headers and DbC expression from the code,
and not just from comments.

>> On the other hand, generating the
>> interface information from the code for type checking (and
>> documentation) purposes makes an incredible amount of sense. A type
>> inferencing engine to generate that information from Python code -
>> with possible a bit of human assistance - would make it possible to
>> use pychecker to catch duck typing errors without having to import an
>> entire module.
> And why should it be a problem to "import an entire module", pray?

It isn't. I was just thinking out loud. If you had a type inferencing
engine that created the type signatures of everything in a module,
that would let you do type checking without importing the module. It's
actually more interesting for compiled languages than for interpreted
ones.

  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: A Revised Rational Proposal

2004-12-26 Thread Mike Meyer
"Dan Bishop" <[EMAIL PROTECTED]> writes:

> Mike Meyer wrote:
>> This version includes the input from various and sundry people.
> Thanks
>> to everyone who contributed.
>>
>>>
>> PEP: XXX
>> Title: A rational number module for Python
> ...
>> Implementation
>> ==
>>
>> There is currently a rational module distributed with Python, and a
>> second rational module in the Python cvs source tree that is not
>> distributed.  While one of these could be chosen and made to conform
>> to the specification, I am hoping that several people will volunteer
>> implementatins so that a ''best of breed'' implementation may be
>> chosen.
>
> I'll be the first to volunteer an implementation.

I've already got two implementations. Both vary from the PEP.

> I've made the following deviations from your PEP:
>
> * Binary operators with one Rational operand and one float or Decimal
> operand will not raise a TypeError, but return a float or Decimal.
> * Expressions of the form Decimal op Rational do not work.  This is a
> bug in the decimal module.
> * The constructor only accepts ints and longs.  Conversions from float
> or Decimal to Rational can be made with the static methods:
> - fromExactFloat: exact conversion from float to Rational
> - fromExactDecimal: exact conversion from Decimal to Rational
> - approxSmallestDenominator: Minimizes the result's denominator,
> given a maximum allowed error.
> - approxSmallestError: Minimizes the result's error, given a
> maximum allowed denominator.
> For example,

Part of finishing the PEP will be modifying the chosen contribution so
that it matches the PEP. As the PEP champion, I'll take that one (and
also write a test module) before submitting the PEP to the pep list
for inclusion and possible finalization.

If you still wish to contribute your code, please mail it to me as an
attachment.

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


  1   2   >