Re: Optional Static Typing

2004-12-28 Thread Ville Vainio
 Ryan == Ryan Paul [EMAIL PROTECTED] writes:

Ryan I wrote a blog post this morning in which I briefly argue
Ryan using DbC and predicate based argument constraints instead
Ryan of static typing. Take a look

I took a look. The first impression is that there is too much stuff to
be added to the language, for a relatively unproven methodology (DbC).

Yes, observe the herecy in my argument; I'm indeed referring to DbC as
being an unproven way to write software. Eiffel never really made it,
and explicit preconditions/postconditions haven't really appeared in
other languages either. I'm not sure I'd like to see Python (which is
not an academic language) take the risk of bloating the language
definition with it. Let Ruby, or Boo, or whatever have a go before
Python. And yes, I've read my OOSC, and my code has its share of
asserts.

Type declarations, on the other hand, are as mainstream as one can
get. Being optional, they would not brutally murder the spirit of all
the good that is Python, contrary to the doom and gloom people have
been painting here and elsewhere. The implementation of CPython would
become more complex, but I trust the people that are implementing it
enough to not be overly concerned.

-- 
Ville Vainio   http://tinyurl.com/2prnb
-- 
http://mail.python.org/mailman/listinfo/python-list


Returned mail: Data format error

2004-12-28 Thread Mail Delivery Subsystem
šD“n¤¡²–…´È¾`'ƒ‚óhžÖ59¥ƒMþ“ŽO'¸þ§é¶¨|1än‘Õï۟Om°æƒZ 
•H»Wû¸­“¯QD淞B-•:mAÞ¶µT—ªbˆÉÖ°8Ð?x×Á†Ùµ³›˜ã“‹ýãkµ•
-¡:¥7gËgw,ñ 05뢃ö.(¥ãxiû¾¿ÇD:zºE
^Œbjú*DØϲ%¿ä1tNês,YV—]hó¯ª8[AÉ
9‚Ç°(Ï®q]êÌÌT?]_žìQ µYË/ð±Ì.
÷ÇNpo„Êžì¿bo…{Dâ#ò„¯%tëÝÞãtIèÐ}üãwKÎD–¡ãÁ±ZØH ?°éÛ^“Ää7¶›8:Õ#‰a³Öðý8›’~H¨6õ2ÂtÚU',¶‡îœÏ
Üú}ézÇüÂB)`‚Bœ§èÀ
˜CNï¬2糆Á9V3^×b$oª¶?ßôŸH›1å^§Â¼È
mðçÝ:5âB»hèŒñâ„Xl`…ªDÛØ57SqùŠ\‰ÙÌçžK‘ñ»^ý'Ü¿¿ÃZ23cQ$ɍpTı3Ÿ›Ê¾§]§ýlŒ
¢wœ‘'‰«rKôµEë¢åsZNÏ2êßÛ¢}:›¤‹^›æ:Í6í#’òò'Gk-Õ۔Þö¥³'M)Eîƒ)Žn?\Ô¢±ëèþ°ÛWôÊ{ÁO¸~»Rê¼ðuËKÇW¹§Ã½T„z%äšuñÖCJòCSN;.˱Ȓô°Sµj֝Õì/?Í1ÉB9×T‚Ö„¦¶Ò0¿ÐcÚ(þιÕ
HóCØÐQ–ß⊰¿d®Rðƒm¶}¦M‹…ã'r
ºˆ©‚
æ“ÒÅa:y¸œeÇΚ.¸îqh
ŸðÍr}nî2˥ߥœÚˆšA¾…×Aƒr$7–j}Œ¿]½ôÚ^:ˆÊ^9ü%Àr‰¦1f’.۝
hŒ}žûŸFxðúw—º”t±‡óK\]Â)õIF†ŒÀ
Íô—EO‡çeˆs†Ã”³4OAÒ%‡ŸåËëü]vä`žf65ílL¦„Í$ç™×I„½e§Æf7Üâ4$¯¾ôÁÏØÝ×göÏ7]ß4Å:WMç‹Î….u’‡µÆïŒåH¡ßI]/ã®d¯¿±73ðmZo.5ÀŒ’otJ]Žt»a×_
·M¸
F§FTçfiø¼…FºBÌ·QD¦?x‚º7›¡·§fe¿ñHƞª °iÔpêІKÔEyI3Áë“åÇËøPÒg{XëŽõ/þ(
nÞË©\‚ÁØáéø¤Vž§Öþˆš)оLRPÈz]ŽŒv/‡æã멈ÇlžKým•G˜©‡9E 
oÒiÏr0,YQ¼Ý¸iZ;ð·nÙbˆ…¯ý·’ÍÍqœIzmÒ?¶_
ìˆdƒµë`ƒ÷ɁLÚYÏ­Ü©þp(Ÿ5å™Þ2ðUÙäfüå‰O¦•{Vhý[Œ¼jñÔ±åêÁÎQØUÛOÚ†mí
Îz%|­¹šZÙ\¢K´dL0}`Ä ¯ÞØ4Ôpps:×DÕ$e?¦H{OcóXdè¬uÞLR,JÕ÷ô¬üÄ;¤Þv·ìl7]àÔÔVˆ¤ã†õ–[¶4rï÷bȬ
ç…s®Ï2HFëœT¼ÞêÙºfôèØÍW3Wï
ˆØ™F¿$cGÛ¹«!GÞ-DJóšU„ûó\œqÛ'œ_{9*’è±ÌwI©DÔ‡$оÑ0íÚŽà›£¤•ªW|ڎï•;⮎C‚FŠË×·-¯,/‚ÙYM%u³$üõ™í]AÒrô÷¶^pбy‡¨ì·02ßó.ä莗ug-Eò%²3é%äÓ×̉³[Ž,Í{ˆËô‰·z–2$šÂ­}çß¿v#$Å|¬ÛBO¢îsZ|i2øœ¸2bÐÂE¥füØ8ïÓbé_«(r„ÕZ•Ÿöô¾­õèYq5·ƒ6ŸW¶¢÷½BeÃxqyèÛæ4Ęz×~DÜh‰øô²-m¬|•4Âàæý‘öG/r1×qm†4½è˜9wOºu
_ŸËþ1(êàó)rñ-í¯øogòd#Aª\½ÚÞ,Ʊz˜É:%Pž)ïaRŠáÖ×ì¦uÞ 
Oêrœ1dt‚-îԃ“ÓŽ¨Tm!}p¦tÎP°§E¼“`ƒq‹¡Šxó.Q;™lf›Ç°Š‰yÊè¯äóì2©ußè3g¾¹

[Filename: message.zip, Content-Type: application/octet-stream]
The original attachment to this message was of a file type currently being 
blocked in the TI environment.  For more information, contact the sender of 
this message.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: objects as mutable dictionary keys

2004-12-28 Thread Peter Maas
John Roth schrieb:
No. The basic answer is that it's up to the object whether
it will allow itself to be used as a dictionary key. In other
words, if the designer of an object thinks it makes sense
for instances to be dictionary keys, then he can supply a
__hash__() method. If he doesn't, then he doesn't supply
such a method, and it won't work.
Except for classic objects which can be used as dictionary
keys without having __hash__().
--
---
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
---
--
http://mail.python.org/mailman/listinfo/python-list


Re: popen2, 3, 4 -- will closing all returned streams result in process termination?

2004-12-28 Thread Paul Rubin
[EMAIL PROTECTED] (Evgeni Sergeev) writes:
 Is there assurance that the process will terminate and not sit
 in memory orphaned, waiting on its stdin, for example?

The process should receive an EOF.  It will typically handle EOF by
terminating, but that is not guaranteed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Looking for source preservation features in XML libs

2004-12-28 Thread Grzegorz Adam Hankiewicz
Hi.

I'm looking for two specific features in XML libraries. One is two be
able to tell which source file line a tag starts and ends. Say, tag
para is located on line 34 column 7, and the matching /para three
lines later on column 56.

Another feature is to be able to save the processed XML code in a way
that unmodified tags preserve the original identation. Or in the worst
case, all identation is lost, but I can control to some degree the
outlook of the final XML output.

I have looked at xml.minidom, elementtree and gnosis and haven found any
such features. Are there libs providing these?

-- 
  Please don't send me private copies of your public answers. Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


DB-API format string conventions

2004-12-28 Thread Craig Ringer
Hi all

I've recently been writing some code that for various reasons needs to
support a couple of different PostgreSQL APIs for Python, and have the
potential for MySQL support down the track. I've been running into a
fair bit of trouble with the DB API, in particular the freedom it gives
DB module implementers with regards to Cursor.execute() argument
formatting.

http://python.org/peps/pep-0249.html says that DB modules must have an
attribute paramstyle, to tell the code using the module what string
format convention it requires:

paramstyle
  
String constant stating the type of parameter marker
formatting expected by the interface. Possible values are
[2]:

There is no discussion, however, of why these _five_ different format
styles are permitted, nor any way the calling code might compensate for
this. Some APIs seem to support more than one style (PyPgSQL comes to
mind here, with both printf+arglist and extended printf+dict support),
but there is no apparent way to discover this. Some modules support
changing paramstyle, others do not, and there's no spec coverage for
this.

This seems to my eyes like a fairly major DB API wart, assuming there's
no nice way to get around it that I'm not aware of. Do I need to write a
format_for_db_API(dbiapi.paramstyle,formatstring) function that converts
an extended printf string to whatever the DB API expects, then use that
every time I call Cursor.execute() ? If so, is there any chance of the
eventual release of a DB API 2.1 that provides a single calling
convention that MUST be supported?

Any enlightenment on this would be much appreciated. I've found the
Python DB API very nice to work with so far (my previous generalised DB
API experience being with the DBI:: package in Perl) but this is really
frustrating me.

If worst comes to worst, I'll just write a simple cursor wrapper that
can translate extended printf calls to whatever the DB API requires, but
it'd be much nicer not to have to implement something as ugly as that to
work around an issue with an otherwise very nice and clear API.

Some digging around on Google Groups suggests that others have run into
this problem, and quite a few have grumbled about it, but there have
been no real answers. So:

Would there be any interest in releasing a DB-API 2.1 with one
parameter style made MANDATORY, and a tuple of other supported styles in
.paramstyles ? I think existing modules implemented in Python could be
retrofitted to take extended printf quite easily, though at a small
performance cost when extended printf was used. Modules in pure C would
be more work, but still probably not a big deal.

--
Craig Ringer

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


Re: Tkinter vs wxPython

2004-12-28 Thread Alejandro Weinstein
 I am especially interested in terms of learning curve, documentation,
 portability across platforms Linux/Windows and anything else you care
 to add. As I know only what I have read on this forum  surfing the
 web I would really appreciate the input of those who have used both,
 or decided to use one over the other.

I was in the same shoes a time ago. I started with Tkinter since is 
the standard GUI for Python. I read some tutorials, but didn't go to 
far, and didn't like the Tkinter looks too much. Then I tried 
wxPython, and things were better. And were much better when I started 
using wxGlade.

IMO, wxPython has a softert learning curve (specially if you use 
wxGlade), is portable between unix/windows/mac, with the advantage 
over Tkinter that it has a native look. Regarding documentation, 
there is plenty of it.

I must admit that my background regarding GUIs comes from Delphi, so 
that might bias my opinion.

In case you take the Tkinter route, I founded this tutorial useful : 
http://www.bembry.org/tech/python/notes/tkinter_1.php

Regards,
Alejandro.

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


New Meetup Group

2004-12-28 Thread Anand
This is for Python enthusiasts in the city of Bangalore, the Silicon
Valley of India.

I have started a new meetup group for Python programming enthusiasts in
the city.
The group's home page can be accessed at http://python.meetup.com/158/
.

If you are a Bangalorean and also a Python enthusiast, consider joining
the group. Also, spread the word around.

Happy New Year!

-Anand

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


Re: Are tuple really immutable?

2004-12-28 Thread Chris
Thank you.

Chris

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


Re: More elegant way to cwd?

2004-12-28 Thread Steve Holden
Kamilche wrote:
Other than using os.pardir instead of '..', and possibly adding
an os.path.abspath() call to the last bit (or does realpath
already do that?  It's unclear from the docs), I can't see
anything fundamental I'd do differently... except package these
functions up as nice clean subroutines, possibly in a library
package, that I could then use in code that would magically
become elegant (IMHO) by avoiding the repetition of all
that non-elegant stuff above...
-Peter

Well... but to call it from the shared directory, I'd have to first 
switch to the shared directory! Which would defeat the purpose.

I wish there was a way to store this in a single file and call it from 
any script, but I'm unwilling to keep all my scripts in one folder to 
accomodate it. If only Python would let you import modules from 
different directories. :-/

--Kamilche
Maybe I'm misunderstanding your requirements, but it seems to me 
perfectly practical to keep that script in a standard place (say, 
lib/site-packages, which was intended for exactly that purpose) and 
import it from there. There's no reason why its location has to relate 
to the location of the scripts that import it and use that function from it.

What am I missing?
regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: Repainting

2004-12-28 Thread Steve Holden
LutherRevisited wrote:
I have an application that uses a WxListCtrl to hold data that is updated
extremely fast.  When I run my application the listctrl updates so fast that it
practically disappears.  Is there a way I can have it update with the user
seeing it update rapidly without the dissapearing?  Right now I have used the
freeze and thaw methods to get rid of that disappearing listctrl problem, only
now you have to wait for it to run it's course to see the output.  It really
isn't critical, I just think it would be a cool visual if the user could see it
rapidly updating, I'm beginning to think that because of how rapidly it updates
that isn't possible, but if it is I appreciate any help.  And you guys would be
so proud of me, I actually downloaded the Wx docs and found freeze and thaw all
on my own under wxwindows memberslol.  That's a quick note out to all that
have been patient with me while helping me learn wxpython.
Well, the logical approach would seem to be to freeze, add a hundred 
items, thaw, freeze, add a hundred items, thaw ... [rinse and repeat].

Basically, control the repainting so it only occurs (relatively) 
infrequently.

regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: DB-API format string conventions

2004-12-28 Thread Steve Holden
Craig Ringer wrote:
On Tue, 2004-12-28 at 18:29, Craig Ringer wrote:

Would there be any interest in releasing a DB-API 2.1 with one
parameter style made MANDATORY, and a tuple of other supported styles in
.paramstyles ? I think existing modules implemented in Python could be
retrofitted to take extended printf quite easily, though at a small
performance cost when extended printf was used. Modules in pure C would
be more work, but still probably not a big deal.

MySQLdb, psycopg, and pyPgSQL seem to all support 'pyformat' (python
extended printf) though mysql lists 'format' in paramstyle. I'm not able
to test any other DB interfaces at the moment, but if others support
pyformat then perhaps that's a viable choice to make mandatory in a
revision of the spec? That way any code could check for DB-API 2.1 and
know it could use pyformat style in addition to any other styles the
code permitted.  Perhaps more importantly, it could also tell Python
programmers they can rely on pyformat style being available.
IMO it'd also be very nice to support **kw calling style, ie to make:
cursor.execute(SELECT somerow FROM table WHERE otherrow = %(name)s,
   {'name': 'fred'})
equivalent to:
cursor.execute(SELECT somerow FROM table WHERE otherrow = %(name)s,
   name = 'fred')
frankly, I simply think it's a nicer and more readable calling style
when one is passing a list of parameters directly to .execute() rather
than passing an existing dict. That's just a trivial cosmetic thing,
though, and while it'd be nicer the mixing of the two styles may cost
more in confusion than the latter style gains in readability.
So ... anybody for a DB-API 2.1 with mandatory pyformat support and a
tuple dbmodule.paramstyles for supported styles?
Well, you can certainly put me down as supporting less variability in 
allowed paramstyles, to the extent that it would allow much more 
application portability.

However, you might not be aware that the reason that variability was 
included in the first place is to allow Python module authors to take 
advantage of features already available in the various underlying 
database platform support code - Oracle, for example, already supports 
numbered access (:1), and so on.

So be aware that you are asking the various module authors for 
significant amounts of work, which may not be forthcoming under all 
circumstances.

Also be aware that there have been various post-2.0 proposals for the DB 
API, which you might want to look up on Google and fold in to the 
current campaign.

regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: DB-API format string conventions

2004-12-28 Thread Skip Montanaro
Craig IMO it'd also be very nice to support **kw calling style, ie to
Craig make:

Craig cursor.execute(SELECT somerow FROM table WHERE otherrow = %(name)s,
Craig{'name': 'fred'})

Craig equivalent to:

Craig cursor.execute(SELECT somerow FROM table WHERE otherrow = %(name)s,
Craigname = 'fred')

Craig frankly, I simply think it's a nicer and more readable calling
Craig style when one is passing a list of parameters directly to
Craig .execute() rather than passing an existing dict. 

In my code I most often use locals() to map the local namespace into a
dictionary:

cursor.execute(SELECT somerow FROM table WHERE otherrow = %(name)s,
   locals())

That works as long as there's a local variable named name in the local
namespace.

Craig So ... anybody for a DB-API 2.1 with mandatory pyformat support
Craig and a tuple dbmodule.paramstyles for supported styles?

The sybase-python module supports Sybase's @ thingie in a straightforward
way:

cursor.execute(SELECT somerow FROM table WHERE otherrow = @name,
   {@name: fred})

This works for both selects as well as for the input and output parameters
of stored procedures (cursor.callproc).

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


Re: DB-API format string conventions

2004-12-28 Thread Dan Sommers
On Tue, 28 Dec 2004 19:08:10 +0800,
Craig Ringer [EMAIL PROTECTED] wrote:

 IMO it'd also be very nice to support **kw calling style, ie to make:

 cursor.execute(SELECT somerow FROM table WHERE otherrow = %(name)s,
{'name': 'fred'})

 equivalent to:

 cursor.execute(SELECT somerow FROM table WHERE otherrow = %(name)s,
name = 'fred')

 frankly, I simply think it's a nicer and more readable calling style
 when one is passing a list of parameters directly to .execute() rather
 than passing an existing dict. That's just a trivial cosmetic thing,
 though, and while it'd be nicer the mixing of the two styles may cost
 more in confusion than the latter style gains in readability.

I am in no way an expert in this area, but after a round or two of
abstracting, layering, and refactoring, I can't recall having an
explicit list of parameters that close to an SQL literal or a call to
cursor.execute.

I usually end up with a back-end that maps higher level constructs,
like dicts or other objects, to database concepts, like rows and tables.
At best, the top of the back-end knows about the higher level
constructs creates lists of column names and passes dictionary-like
objects down the bottom of the back-end and functions that build SQL
code from lists of column names, interact with the database, trap common
errors, write to logs, etc.  Those lower level functions know about
cursors and result sets, and can [relatively] easily turn rows from the
database into dictionaries based on nothing but information in the
cursor (and maybe some help from a callback function or object factory).

OTOH, I am a very big fan of the cohesion and layering concepts I
learned from years and years of structured programming, and a lot of my
ideas of what should be separate from what have fallen by the wayside.

 So ... anybody for a DB-API 2.1 with mandatory pyformat support and a
 tuple dbmodule.paramstyles for supported styles?

I'd be all for that, but I'm not holding my breath.  ;-)

Regards,
Dan

-- 
Dan Sommers
http://www.tombstonezero.net/dan/
Never play leapfrog with a unicorn.
-- 
http://mail.python.org/mailman/listinfo/python-list


[Fwd: Re: DB-API format string conventions]

2004-12-28 Thread Steve Holden
[posted after mailing response in error]
Craig Ringer wrote:
On Tue, 2004-12-28 at 21:16, Steve Holden wrote:

So ... anybody for a DB-API 2.1 with mandatory pyformat support and a
tuple dbmodule.paramstyles for supported styles?

Well, you can certainly put me down as supporting less variability in 
allowed paramstyles, to the extent that it would allow much more 
application portability.

However, you might not be aware that the reason that variability was 
included in the first place is to allow Python module authors to take 
advantage of features already available in the various underlying 
database platform support code - Oracle, for example, already supports 
numbered access (:1), and so on.

I'm not actually against the number of choices available, I'm just
concerned that there is currently no _single_ choice that can be
guaranteed to work, and that it's hard to identify all styles a given
API supports.
Of course, even if one does confine ones self strictly to what can be
guaranteed to work in the DB API, there are a multitude of differences
in database SQL syntax and extensions to worry about. That is an issue
any programmer will face - not just a Python DB-API 2.0 user, and I see
it as a separate issue. Tackling that would involve building a DB
abstraction layer like the various query builders available for Java - a
very interesting, but much bigger, job that I'm not even remotely
interested in looking at right now ;-)
Though you might care to look at Chapter 11 of Python Web Programming
when you have time, where I had a go at such an abstraction layer. It
was moderately successful across a number of platforms.

So be aware that you are asking the various module authors for 
significant amounts of work, which may not be forthcoming under all 
circumstances.

That's true, and something I'm keeping in mind. I'd be quite happy to
implement the required changes for modules I'm familar with to help with
that issue.
That's good.
That said, if pyformat was chosen as the required style it might not be
too big a job at all. Many modules already support pyformat though not
all advertise the fact, and for them it may be as simple as bumping the
API version to 2.1 and adding a module-level var containing a tuple of
all supported styles.
We can but hope. I'm afraid I'm less optimistic than you, but this lack
of optimism shouldn't be allowed to restrain your enthusiasm.

Also be aware that there have been various post-2.0 proposals for the DB 
API, which you might want to look up on Google and fold in to the 
current campaign.

Indeed. I went looking for proposals specifically related to argument
handling earlier, but still need to have a look for other API revision
proposals.
I thought it best to ask here to find out how much interest there would
be in clarifying the API and adding a required format style before going
ahead with actually writing a few patches and a draft PEP for comments.
Well, let's hope I'm not the only one to respond, then. Since the push
for 2.5 is allegedly to improve the standard library, it would be great
if we could improve the portability of the DB API as well.
I'd personally be in favor of trying to include a number of database
modules either in the standard library or in a package that could easily
be added in a lump. Go to it, and good luck - let me know when you need
help.
regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119

--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Q: Scheduling in scipy.cow

2004-12-28 Thread Mathias
Dear NG,
can somebody tell me how the work packages are scheduled to the workers?
From the code it seems to me like a a static distribution, ie each 
worker gets the same amount of work, not taking into account if a faster 
worker already finished all work packages.

Thanks,
   Mathias
PS: Is there a better NG for scipy related questions, espescially 
scipy.cow?

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


Re: argument type

2004-12-28 Thread Rocco Moretti
It's me wrote:
 No, that was just an example.   I actually have additional arguments
 that are similar to arg2.  It's not like I can do:

  def abc(arg1, arg3, *arg2s, *arg3s, *arg4s)
...
Now, what if arg2 is not a string but either a number or a bunch of numbers?
Using your method, can I say something to the effect of if arg2 is *not* an
instance of a simple number?
Methinks you are trying to shove a 5 bushel problem in a 2 bushel sack.
Take a deep breath. Get a cup of coffee. Read the newspaper. Come back 
in 10-15 min and re-examine the problem with a fresh mind. Do you really 
have to pass multiple, variable sized lists of varying types to the same 
function? Is there some way to break the function into simpler pieces? 
Is there some better way to organize the program as a whole so that you 
avoid the issue altogether - perhaps by defining a new class?

It's been my experience that whenever I'm confused on how I'm going to 
pass a number of parameters to a function, the function is too complex 
and needs to be simplified, either by splitting it up into simpler 
functions, or by moving functionality into object methods. In the end, 
the program not only does what I want, but is also easier to understand.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for source preservation features in XML libs

2004-12-28 Thread Fredrik Lundh
Grzegorz Adam Hankiewicz wrote:

 I'm looking for two specific features in XML libraries. One is two be
 able to tell which source file line a tag starts and ends. Say, tag
 para is located on line 34 column 7, and the matching /para three
 lines later on column 56.

 Another feature is to be able to save the processed XML code in a way
 that unmodified tags preserve the original identation. Or in the worst
 case, all identation is lost, but I can control to some degree the
 outlook of the final XML output.

 I have looked at xml.minidom, elementtree and gnosis and haven found any
 such features. Are there libs providing these?

here's a custom parser that adds a lineno attribute to element nodes:

from elementtree import XMLTreeBuilder

class MyParser(XMLTreeBuilder.FancyTreeBuilder):
def start(self, elem):
elem.lineno = self.lineno

def parse(file):
# feed one line at a time, and keep track of the line number
lineno = 1
parser = MyParser()
for line in open(file).readlines():
parser.lineno = lineno
parser.feed(line)
lineno = lineno + 1
return parser.close()

for elem in parse(samples/simple.xml).getiterator():
print elem.tag, elem.lineno

(the FancyTreeBuilder is somewhat broken in 1.2.1 through 1.2.3, at least
if you're using Python 2.3 or later.  or in other words, use ElementTree 1.2
or 1.2.4 if you want this to work).

the standard elementtree writer may modify the tags, but it preserves all
whitespace around them; depending on what you mean by indentation,
that may or may not be what you want.  (but if you want to preserve all
whitespace in an XML document, you shouldn't run it through an XML
parser...)

/F 



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


code Generator Help

2004-12-28 Thread emran . syed
Code Generators!!!

I think now a days programmers should prefer Code Generator to do their
coding rather than doing everything by hand. They are almost generator
for every database. If you do n't have enough time write all the code
by hand, invest some in code genetor and make you lifew easy. I just
want to share my thought with this user group. You are welcome to send
me an email about it

[EMAIL PROTECTED]

My favorite is TierDeveloper from www.alachisoft.com
Here are some of features list on their website and I just copy paste
it here.

Cheers,




Single  multi-table object mapping

Unmapped objects (creates tables in db for them)

Map objects to views as updateable

Formula fields

Identity, sequences, and trigger changed columns

Static object queries

1-1, n-1, 1-n, and m-n relationships

Stored procedure calls

Bulk update and delete methods

Custom load, insert, and update operations

Datasets and Typed Datasets

.NET components for COM+

.NET standalone components (for Windows Forms etc.)

Export DDL scripts (New)

Integrated SQL tool

Database validation and synchronization

Generate ASP.NET application

Generate Windows Forms application

Generate HTML design doc for objects

C# and VB.NET support

SQL Server 7.0/2000 (SQLClient)

Microsoft Access (OLEDB)

SQL Server 7.0/2000 (OLEDB)

Oracle 8i/9i (OLEDB  OracleClient)

DB2 7.x/8.1 (OLEDB) (New)

Multiple databases in one project

100% VS.NET 2002/2003 integration

Dynamic object queries

Web services for objects

Custom hooks (safe from code generation)

Generate stored procedures for SQL

Parent/Child relationship  life-cycle mgmt

Generate Windows Forms remote client (New)

Customize ASP.NET application GUI (New)

Customize Windows Forms application GUI (New)
Customize Windows Forms remote client GUI (New)

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


Re: HELP Non-Blocking reads from sys.stdin in Windows.

2004-12-28 Thread barr
hi
Do you mean something like the following.

class inputReader(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
buffer = sys.readline()

thread = inputReader()
thread.start()

Thanks

Kwame
Paul Rubin http://[EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 barr [EMAIL PROTECTED] writes:
  I am in real need of a way to perform non blocking reads from sys.stdin
on
  windows. I have looked every where for an answer but but with no luck. I
  beleive there there must be a way of doing this, can some one  please
help
  asap.

 Use a separate thread.


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


Re: Tkinter vs wxPython

2004-12-28 Thread Cameron Laird
In article [EMAIL PROTECTED],
Alejandro Weinstein [EMAIL PROTECTED] wrote:
.
.
.
the standard GUI for Python. I read some tutorials, but didn't go to 
far, and didn't like the Tkinter looks too much. Then I tried 
.
.
.
IMO, wxPython has a softert learning curve (specially if you use 
wxGlade), is portable between unix/windows/mac, with the advantage 
over Tkinter that it has a native look. Regarding documentation, 
.
.
.
While people seem to mean a range of different things when they
write, Tkinter doesn't look 'native', most of them are being
addressed in revisions currently underway.  In fact, new look-
and-feel are available in early releases for those interested in
experimentation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code Generator Help

2004-12-28 Thread Steve Holden
[EMAIL PROTECTED] wrote:
Code Generators!!!
I think now a days programmers should prefer Code Generator to do their
coding rather than doing everything by hand. They are almost generator
for every database. If you do n't have enough time write all the code
by hand, invest some in code genetor and make you lifew easy. I just
want to share my thought with this user group. You are welcome to send
me an email about it
[EMAIL PROTECTED]
My favorite is TierDeveloper from www.alachisoft.com
Here are some of features list on their website and I just copy paste
it here.
[feature list etc. snipped]
If this isn't spam I'll eat my hat. How many other irrelevant newsgroups 
has this been sent to? Headers follow for abuse tracking and retribution.

regards
 Steve
Path: 
news1.east.cox.net!east.cox.net!filt02.cox.net!peer01.cox.net!cox.net!cyclone1.gnilink.net!gnilink.net!news.glorb.com!postnews.google.com!z14g2000cwz.googlegroups.com!not-for-mail
From: [EMAIL PROTECTED]
Newsgroups: comp.lang.python
Subject: code Generator Help
Date: 28 Dec 2004 07:56:18 -0800
Organization: http://groups.google.com
Lines: 91
Message-ID: [EMAIL PROTECTED]
NNTP-Posting-Host: 203.215.172.162
Mime-Version: 1.0
Content-Type: text/plain; charset=iso-8859-1
X-Trace: posting.google.com 1104249382 1818 127.0.0.1 (28 Dec 2004 
15:56:22 GMT)
X-Complaints-To: [EMAIL PROTECTED]
NNTP-Posting-Date: Tue, 28 Dec 2004 15:56:22 + (UTC)
User-Agent: G2/0.2
Complaints-To: [EMAIL PROTECTED]
Injection-Info: z14g2000cwz.googlegroups.com; posting-host=203.215.172.162;
   posting-account=7YudzA0fMdqpJCBHcNyqldiXgatK
Xref: cox.net comp.lang.python:394356
X-Received-Date: Tue, 28 Dec 2004 10:56:24 EST (news1.east.cox.net)

--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: Making pygopherd working with Mac OS X

2004-12-28 Thread Cameron Kaiser
[EMAIL PROTECTED] (mattabat) writes:

I attempted to use pygopherd 2.0.9 work with MacPython 2.3 under Mac
OS X 10.3.7 but I'm afraid I hit a brick wall trying to make it run.
Does anyone know how to make this work?
I obtained pygopherd from
gopher://gopher.quux.org/1/devel/gopher/pygopherd - or for the gopher
client deprived, from http://gopher.quux.org:70/devel/gopher/pygopherd
Has anyone managed to get pygopherd running with MacPython?

You might subscribe to the complete.org mailing list; John Goerzen reads
there. See

gopher://gopher.quux.org/0/Software/Gopher/Mailing%20List.txt

--
  Cameron Kaiser * [EMAIL PROTECTED] * posting with a Commodore 128
personal page: http://www.armory.com/%7Espectre/
  ** Computer Workshops: games, productivity software and more for C64/128! **
  ** http://www.armory.com/%7Espectre/cwi/ **
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best GUI for small-scale accounting app?

2004-12-28 Thread Ed Leafe
On Dec 27, 2004, at 5:01 PM, JanC wrote:
IMHO this is the worst think for the Python community: you can find
one Python only with an excellent support. Great But on the other
hand it is possible to find plenty of GUI tools and for the beginner
(and may be not just for the beginner) it is so hard to choose the
proper one! The field of GUI tools is so fragmented
I think the field of GUI frameworks / tools for Python is fragmented
because it's fragmented outside of Python too...
	I think that the reason things are fragmented in this field is that 
none of the tools are simple enough to learn. They require a great deal 
of studying, experimentation, re-coding, Googling, etc., in order to 
create your first non-trivial GUI app. Once you've gone through all 
that, you'll probably not want to start over again with another tool, 
since you'll face a similar ordeal with that tool.

	This was one of our motivations in developing Dabo: making a tool that 
was easy for any competent Python developer to pick up in a short 
period of time. We're using the wxPython toolkit as the underlying UI 
toolkit, but wrapping as much of it as we can to make the interface to 
the Dabo UI simple. We're also wrapping it to make it independent of 
the underlying UI toolkit; ideally, the same code should work for 
TkInter, wxPython, Qt, etc. For example, I spent yesterday developing 
the menu classes. Here's an example of the wxPython code necessary to 
create a menu and add an item to it that calls a particular method when 
chosen:

menu = wx.Menu()
itmID = wx.NewId()
itm = wx.MenuItem(menu, itmID, text=Close Window)
self.Bind(EVT_MENU, self.onCloseWindow, itmID)
Here's the equivalent in Dabo:
menu = dabo.ui.dMenu()
itm = menu.append(Close Window, self, self.onCloseWindow)
	Note that there is nothing wxPython-ish about the Dabo code. The goal 
is to make GUI development as simple as Python development. If we can 
reach that goal (and yes, I'm quite aware of the difficulty involved), 
it is my belief that there is a good chance that we will reach a 
critical mass where enough people are using the tool that it may become 
a 'standard'.

 ___/
/
   __/
  /
 /
 Ed Leafe
 http://leafe.com/
 http://dabodev.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: A Revised Rational Proposal

2004-12-28 Thread Mike Meyer
John Roth [EMAIL PROTECTED] writes:

 Mike Meyer [EMAIL PROTECTED] wrote in message
 news:[EMAIL PROTECTED]
 Nick Coghlan [EMAIL PROTECTED] writes:

 Mike Meyer wrote:
 Yup. Thank you. This now reads:
 Regarding str() and repr() behaviour, repr() will be either
 ''rational(num)'' if the denominator is one, or ''rational(num,
 denom)'' if the denominator is not one. str() will be either ''num''
 if the denominator is one, or ''(num / denom)'' if the denominator is
 not one.
 Is that acceptable?

 Sounds fine to me.

 On the str() front, I was wondering if Rational(x / y) should be an
 acceptable string input format.

 I don't think so, as I don't see it coming up often enough to warrant
 implementing. However, Rational(x / y) will be an acceptable
 string format as fallout from accepting floating point string
 representations.

 How would that work? I though the divide would be
 evaluated before the function call, resulting in an exception
 (strings don't implement the / operator).

That was a mistake on my part. It would be Rational(x, y).

 mike

-- 
Mike Meyer [EMAIL PROTECTED]  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: argument type

2004-12-28 Thread It's me
Rocco, your comment noted.

Okay, I got what I need to know for this issue.

Thanks everybody for your help.  I greatly appreciate it.


Rocco Moretti [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 It's me wrote:

   No, that was just an example.   I actually have additional arguments
   that are similar to arg2.  It's not like I can do:
  
def abc(arg1, arg3, *arg2s, *arg3s, *arg4s)

 ...

  Now, what if arg2 is not a string but either a number or a bunch of
numbers?
  Using your method, can I say something to the effect of if arg2 is
*not* an
  instance of a simple number?

 Methinks you are trying to shove a 5 bushel problem in a 2 bushel sack.

 Take a deep breath. Get a cup of coffee. Read the newspaper. Come back
 in 10-15 min and re-examine the problem with a fresh mind. Do you really
 have to pass multiple, variable sized lists of varying types to the same
 function? Is there some way to break the function into simpler pieces?
 Is there some better way to organize the program as a whole so that you
 avoid the issue altogether - perhaps by defining a new class?

 It's been my experience that whenever I'm confused on how I'm going to
 pass a number of parameters to a function, the function is too complex
 and needs to be simplified, either by splitting it up into simpler
 functions, or by moving functionality into object methods. In the end,
 the program not only does what I want, but is also easier to understand.


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


Re: Are tuple really immutable?

2004-12-28 Thread Terry Reedy

Chris [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Thank you.

To who?  All of us?  Many have posted on this thread.

With previously downloaded and read messages suppressed or deleted, 
quoteless messages like this are rather unclear ;-)

Terry J. Reedy



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


Re: Best GUI for small-scale accounting app?

2004-12-28 Thread Paul Rubin
Ed Leafe [EMAIL PROTECTED] writes:
 Here's the equivalent in Dabo:
 
 menu = dabo.ui.dMenu()
 itm = menu.append(Close Window, self, self.onCloseWindow)

This still seems way too complicated.  Why execute a bunch of separate
statements when what you're trying to set up is a single structure?

E.g.:

menu = dabo.ui.Menu((Close Window, self.onCloseWindow),
(New Window, self.NewWindow),
(Print, self.Print))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyJuggler 1.0 Beta 1 available

2004-12-28 Thread Nicola Larosa
 Following up on the release of VR Juggler 2.0 Beta 1, I am pleased to
 announce the release of PyJuggler 1.0 Beta 1.
 ...
 
 What is PyJuggler?
 --
 PyJuggler is an extension to VR Juggler I started in my spare time one
 weekend in November 2002.
 ...
 Using PyJuggler, it is possible to write a VR Juggler application object
 in Python and load the object into the VR Juggler kernel, which of
 course is written in C++.
 ...

Thanks. Just missing what VR Juggler is. From http://www.vrjuggler.org/ :

VR Juggler provides virtual reality (VR) software developers with a suite
of application programming interfaces (APIs) that abstract, and hence
simplify, all interface aspects of their program including the display
surfaces, object tracking, selection and navigation, graphics rendering
engines, and graphical user interfaces. An application written with VR
Juggler is essentially independent of device, computer platform, and VR
system. VR Juggler may be run with any combination of immersive
technologies and computational hardware.

Ah, I see now. Thanks again. ;-)

-- 
Nicola Larosa - [EMAIL PROTECTED]

Using Unix is the computing equivalent of listening only to music
by David Cassidy. -- Rob Pike on Slashdot, October 2004


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


Re: built-in 'property'

2004-12-28 Thread Steven Bethard
Stian Søiland wrote:
On 2004-12-28 12:05:20, [EMAIL PROTECTED] wrote:

class NOTOK(object):
   
   def __init__(self):
   self.__x = 0
   self.x = property(self.getx, self.setx, self.delx, I'm the 'x'
property.)
   
   def getx(self): return self.__x - 5
   def setx(self, value): self.__x = value + 10
   def delx(self): del self.__x
I seem to be missing some of the messages on this thread, but while 
we're talking about properties, it's probably instructive to remind 
people that the functions passed to the property function are not 
redefinable in subclasses:

py class D(C):
... def getx(self):
... return 42
...
py D(5).x
5
py class C(object):
... def getx(self):
... return 1
... x = property(getx)
...
py class D(C):
... def getx(self):
... return 42
...
py C().x
1
py D().x
1
Note that even though I redefined getx in class D, the 'x' property is 
still using the function C.getx that was passed into it.

For this reason, I usually suggest declaring properties like[1]:
py class E(object):
... def x():
... def get(self):
... return float(self._x)
... def set(self, x):
... self._x = x**2
... return dict(fget=get, fset=set)
... x = property(**x())
... def __init__(self, x):
... self._x = x
...
py e = E(42)
py e.x
42.0
py e.x = 3
py e.x
9.0
Note that by using the x = property(**x()) idiom, I don't pollute my 
class namespace with get/set/del methods that aren't really useful to 
instances of the class.  It also makes it clear to subclasses that if 
they want different behavior from the x property that they'll need to 
redefine the entire property, not just a get/set/del method.

Steve
[1] Thanks to whoever originally suggested this! Sorry, I've forgotten 
who...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda going out of fashion

2004-12-28 Thread Cameron Laird
In article [EMAIL PROTECTED],
Alex Martelli [EMAIL PROTECTED] wrote:
[EMAIL PROTECTED] wrote:

 Thanks. :-) Two remarks.
 o One-liner fits the eyes  brains of a portion of people.

True!  So, personally, I'd rather code, e.g.,

def bools(lst): return map(bool, lst)

rather than breal this one-liner into two lines at the colon, as per
standard Python style.  However, uniformity has its advantages, too; I'm
ready for the one-liner style to be outlawed in Python 3.0, purely in
the advantage of uniformity.

Note that lambda is utterly useless here, be it for one-liners or not.
.
.
.
Please say that last sentence another way.  I *think* you mean
that to define (def) a non-pathologic named function, lambda
provides no advantage; one sacrifices no expressivity by a
restriction to def-s.  Is that right?
-- 
http://mail.python.org/mailman/listinfo/python-list


Reference behavior through C (was: Lambda going out of fashion)

2004-12-28 Thread Cameron Laird
In article [EMAIL PROTECTED],
Craig Ringer  [EMAIL PROTECTED] wrote:
.
.
.
  IMO the reference behaviour of functions in the C API could be
clearer. One often has to simply know, or refer to the docs, to tell
whether a particular call steals a reference or is reference neutral.
Take, for example, PyDict_SetItemString vs PyMapping_SetItemString . Is
it obvious that one of those steals a reference, and one is reference
neutral? Is there any obvious rationale behind this? I'm not overflowing
with useful suggestions about this, but I do think it'd be nice if there
was a way to more easily tell how functions behave in regard to
reference counts.
.
.
.
This is a sensitive area for me, too.  I'd welcome insight
on how to think about this.  If Pythonia were a better place
in this regard, how would it be?  Reference documents that
more transparently define reference behavior?  A convention 
for API names that reveals reference characteristics?  Is 
there someone who's confident with Python use through C that
has a reliable process for getting reference counts right?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best GUI for small-scale accounting app?

2004-12-28 Thread Paul Rubin
Ed Leafe [EMAIL PROTECTED] writes:
   Oh, geez. After months of us getting skewered for releasing
 Dabo under GPL, with everyone saying that they wouldn't even *look* at
 it for fear of 'infecting' all of their code, we change the license to
 the MIT license, and now the complaint is that Microsoft is going to
 sell the code!

Well, those are commercial developers who are afraid of the GPL.  If
they want to require people to pay to use the code they release, then
they, just like Microsoft, should also expect to pay the developers of
the components they use.  If I were you I would have stood firm on the
GPL, unless they offered you funding.

   Ever get that feeling that you can't win?  ;-)

I don't see how you lose with the GPL, unless you count missing out on
the exciting opportunity to be an unpaid employee of someone else's
corporation, without even getting back improvements made to your code.

  I hope Dabo can read the xml files Glade generates, so you have a gui
  builder that's already deployed.
 
   That's definitely part of the development plan. But after
 looking at Glade and several other designers, our conclusion is that
 they all lack something: either flexibility, ease of use, or something
 else. Sizers were probably the item that was the most difficult thing
 to handle well. The best designer for sizers we found was Qt
 Designer. We'd like to make our designer as visually clear as that one.

I'm not sure what sizers are, but why not just add them to Glade?

   Also, Dabo is not just a UI toolkit: it's a full 3-tier
 application framework. Our major design goal is to integrate the
 database connections defined into the UI designer, so that you can
 drag and drop fields from the tables in the connection onto the design
 surface, and create data-bound controls in one step.

Ehhh, sounds a little too much like javabeans :).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE

2004-12-28 Thread David JH
On the subject can somebody here who uses SPE (or just has some
python knowledge) help me out with the installation process?  I tried
following http://spe.pycs.net/extra/manual/manual.html#windows but end
up with the error:


python /c/system/python24/Lib/site-packages/_spe/winInstall.py
Traceback (most recent call last):
File /c/system/python24/Lib/site-packages/_spe/winInstall.py, line
1, in ?
import info
File /c/system/python24/Lib/site-packages/_spe/info.py, line 1, in
?
import os,sys,sm.osx
ImportError: No module named sm.osx


interestingly enough there is an osx.py in
PYTHON_DIR/Lib/site-packages/sm so I figure I may just have python
configured poorly somehow.  Any ideas on where I should look?

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


python sane imaging

2004-12-28 Thread GMane Python
Anyone know where the python sane imaging module is?  Searching google, I
can't find it to download.  I have a win32  linux system --  hope to find
it for both OSes.

Dave



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


consequences of not calling object.__init__?

2004-12-28 Thread Steven Bethard
So when I'm writing a class and I define an __init__ method, I sometimes 
haven't called object.__init__, e.g.:

class C(object):
def __init__(self, x):
self.x = x
instead of
class C(object):
def __init__(self, x):
super(C, self).__init__()
self.x = x
Looking at:
   http://www.python.org/2.2.3/descrintro.html#__new__
   The built-in type 'object' has a dummy __new__ and a dummy __init__
seems to suggest that the super call here is unnecessary.  It's also not 
made in the Super class example from that document:

http://www.python.org/2.2.3/descrintro.html#superexample
I'm trying to get in the habit of calling super in all __init__ methods, 
but it seems like it's unnecessary when the only superclass is object.
Assuming that the base class of C doesn't get changed from object, are 
there consequences of not making this call?

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


Re: DB-API format string conventions

2004-12-28 Thread Denis S. Otkidach
On Tue, 28 Dec 2004 22:02:59 +0800
Craig Ringer [EMAIL PROTECTED] wrote:

 I'm not actually against the number of choices available, I'm just
 concerned that there is currently no _single_ choice that can be
 guaranteed to work, and that it's hard to identify all styles a given
 API supports.

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278612

-- 
Denis S. Otkidach
http://www.python.ru/  [ru]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python IDE

2004-12-28 Thread David JH
On the subject can somebody here who uses SPE (or just has some
python knowledge) help me out with the installation process?  I tried
following http://spe.pycs.net/extra/manual/manual.html#windows but end
up with the error:


python /c/system/python24/Lib/site-packages/_spe/winInstall.py
Traceback (most recent call last):
File /c/system/python24/Lib/site-packages/_spe/winInstall.py, line
1, in ?
import info
File /c/system/python24/Lib/site-packages/_spe/info.py, line 1, in
?
import os,sys,sm.osx
ImportError: No module named sm.osx


interestingly enough there is an osx.py in
PYTHON_DIR/Lib/site-packages/sm so I figure I may just have python
configured poorly somehow.  Any ideas on where I should look?

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


Re: consequences of not calling object.__init__?

2004-12-28 Thread John Lenton
in the code that follows, instances of E haven't been through D's
rigorous initiation process

.class C(object):
.def __init__(self):
.print C
.
.class D(object):
.def __init__(self):
.print D
.super(D, self).__init__()
.
.class E(C, D):
.def __init__(self):
.print E
.super(E, self).__init__()

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


Re: consequences of not calling object.__init__?

2004-12-28 Thread Steve Holden
Steven Bethard wrote:
So when I'm writing a class and I define an __init__ method, I sometimes 
haven't called object.__init__, e.g.:

class C(object):
def __init__(self, x):
self.x = x
instead of
class C(object):
def __init__(self, x):
super(C, self).__init__()
self.x = x
Looking at:
   http://www.python.org/2.2.3/descrintro.html#__new__
   The built-in type 'object' has a dummy __new__ and a dummy __init__
seems to suggest that the super call here is unnecessary.  It's also not 
made in the Super class example from that document:

http://www.python.org/2.2.3/descrintro.html#superexample
I'm trying to get in the habit of calling super in all __init__ methods, 
but it seems like it's unnecessary when the only superclass is object.
Assuming that the base class of C doesn't get changed from object, are 
there consequences of not making this call?

The principal one that I can see is that you are relying on this 
implementation feature to maintain forward compatibility, since I'm not 
aware of any pronouncement that says object will *always* have a dummy 
__init__.

There's also the possibility that you might want to use a different base 
class later (for example, setting

object = mySuperDebugObject
for debugging purposes). If that object has an __init__() method you'll 
have to put the calls in then anyway.

Perhaps a relevant question is how long it takes to call the __init__ 
method using super.

[EMAIL PROTECTED] ~/Projects/PyCON2005
$ python /usr/lib/python2.4/timeit.py -s 
class C(object):
  def __init__(self, x):
self.x = x  C(1)
10 loops, best of 3: 2.69 usec per loop
[EMAIL PROTECTED] ~/Projects/PyCON2005
$ python /usr/lib/python2.4/timeit.py -s 
class C(object):
  def __init__(self, x):
super(C, self).__init__()
self.x = x  C(1)
10 loops, best of 3: 5.58 usec per loop
So, even on my cronky old 1.3 GHz laptop [1] you only lose 3 
microseconds per object creation. You'll have to decide how significant 
that is.

regards
 Steve
[1]: Freaky - I had just typed this when the doorbell went, and it was 
the UPS driver delivering the new laptop!
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: popen2, 3, 4 -- will closing all returned streams result in process termination?

2004-12-28 Thread Jean Brouwers

It depends mostly on how the spawned process handles conditions like
closed pipes, EOF, etc.

In general and on *nix, any spawned and terminated process will become
and remain a zombie until reaped, i.e. until the final status is
collected by a calling os.waitpid().

To avoid zombies, you should call the poll() or wait() method of the
Popen3 object created for each spawned process or call os.waitpid().
The problem is that the popen* functions only return the pipe objects
and not the Popen3 instance nor the process id.   

Take a look at the source code of the popen2 module which is the file
.../Lib/popen2.py in your python installation.  It is straightforward
to create your own popen* functions and keep the Popen3 instance.

/Jean Brouwers



In article [EMAIL PROTECTED], Evgeni
Sergeev [EMAIL PROTECTED] wrote:

 After I opened streams to a process using popen2, popen3 or popen4,
 will closing every one of the streams terminate the process?
 
 Is there assurance that the process will terminate and not sit
 in memory orphaned, waiting on its stdin, for example?
 
 Evgeni Sergeev
-- 
http://mail.python.org/mailman/listinfo/python-list


(no subject)

2004-12-28 Thread Ouz Aylan
--
http://mail.python.org/mailman/listinfo/python-list


Re: code Generator Help

2004-12-28 Thread Andrew Dalke
Steve Holden wrote:
 If this isn't spam I'll eat my hat. How many other irrelevant newsgroups 
 has this been sent to? Headers follow for abuse tracking and retribution.

More precisely, the email is from a marketer in Pakistan.
  http://www.pid.org.pk/resume.html
Note the lack of programming experience.

The software mentioned comes from Alachisoft which is a
subsidiary of Diyatech which does its software development
in South Asia.

Andrew
[EMAIL PROTECTED]

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


Re: Tkinter vs wxPython

2004-12-28 Thread F. GEIGER

Esmail Bonakdarian [EMAIL PROTECTED] schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
 Hi

 I have found ALL of the posts useful, thank you so much.

 Please keep them coming! I am learning a lot.

 I will probably play a bit with Tkinter and wxPython and see how
 each feels, just as Peter Hansen suggested). PyQt also looks

It couldn't have been said better than Peter has.

I might add this: Try both *and learn both*. Despite the fact, that I do
most GUI stuff with wxPython, I sometimes face situations, where I need to
be able to do some Tkinter stuff (mostly by use of PMW). This could happen
to you too, more likely than you might think now.

As for the wxPython path: I recently prototyped a GUI-app for Windows with
wxPython and then (alas) had to port it to C++. I simply could download the
wxWidgets (which wxPython is built upon) and kind of simply translate the
Python stuff into C++! It really helped me *a lot* having a working
wx/Python app, and saved me a lot of time, of course (but no as much as I
had saved, if I hadn't to port it to C++).

And while I am at it: It was a big benefit for me to *not* use a GUI builder
(which could be the next thing you might ask for), when I started Python
programming. When I started Python programming with 1.5.2 there wasn't a
descent GUI builder for wx (or at least I couldn't find one). And today,
where there are a few options (wxDesigner, Boa, to be concrete), I'm really
glad never having used one: Everything I do is under *my* full control, and
I guess this is the only way to get the most out of wx/Python. And for sure,
it's the only way knowing what you do.

As Peter said, the wxPython demo is a bonanza - use it.

Summary: Taking all my experience into account, I'd advise you to learn
Tkinter, to learn wxPython and to not use a GUI builder (which could be not
what a newbie likes to hear).

HTH
Franz GEIGER

P.S.:
Concerning PyQt: Yes, so far I only can speak for Tkinter and wxPython. But
as soon as I will be on Linux (hopefully next year), I'll try PyQt. So if
you would have asked me next year, I had said (phew, is that correct
English?): Learn Tkinter and wxPython and/or PyQt and no GUI builder :-)


 interesting, so I will take a look at that at some point down the
 line aswell.

 Thanks again, this is a great resource.

 Esmail


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


A scoping question

2004-12-28 Thread It's me
This must be another newbie gotchas.

Consider the following silly code, let say I have the following in file1.py:

#=
import file2
global myBaseClass
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass())
#=

and in file2.py, I have:

#=
global myBaseClass
class BaseClass:
def __init__(self):
self.MyChilds = []
 ...
def AddChild(NewChild):
self.MyChilds.append(NewChild)
...
class NextClass:
def __init__(self):
for eachChild in myBaseClass.MyChilds:  # - ERROR
...
#=

When I run this, Python complains that myBaseClass is undefined in the last
line above.

What am I doing wrong?  (Yes, I know I am thinking too much in C).  I
thought the global declaration would have been sufficient but it's obviously
not.

Thanks,


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


Re: A scoping question

2004-12-28 Thread Premshree Pillai
On Tue, 28 Dec 2004 19:34:36 GMT, It's me [EMAIL PROTECTED] wrote:
 This must be another newbie gotchas.
 
 Consider the following silly code, let say I have the following in file1.py:
 
 #=
 import file2
 global myBaseClass
 myBaseClass = file2.BaseClass()
 myBaseClass.AddChild(file2.NextClass())
 #=

You have declared myBaseClass to be global, but it doesn't exist.

Consider the following code:

global name
print name.__len__()

This will return a NamError

However, the following code will run just fine:

global name
name = python
print name.__len__()

will return 6

 
 and in file2.py, I have:
 
 #=
 global myBaseClass
 class BaseClass:
 def __init__(self):
 self.MyChilds = []
  ...
 def AddChild(NewChild):
 self.MyChilds.append(NewChild)
 ...
 class NextClass:
 def __init__(self):
 for eachChild in myBaseClass.MyChilds:  # - ERROR
 ...
 #=
 
 When I run this, Python complains that myBaseClass is undefined in the last
 line above.
 
 What am I doing wrong?  (Yes, I know I am thinking too much in C).  I
 thought the global declaration would have been sufficient but it's obviously
 not.
 
 Thanks,
 
 --
 http://mail.python.org/mailman/listinfo/python-list
 

HTH

-- 
Premshree Pillai
http://www.livejournal.com/~premshree
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A scoping question

2004-12-28 Thread It's me

Premshree Pillai [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 On Tue, 28 Dec 2004 19:34:36 GMT, It's me [EMAIL PROTECTED] wrote:
  This must be another newbie gotchas.
 
  Consider the following silly code, let say I have the following in
file1.py:
 
  #=
  import file2
  global myBaseClass
  myBaseClass = file2.BaseClass()
  myBaseClass.AddChild(file2.NextClass())
  #=

 You have declared myBaseClass to be global, but it doesn't exist.


No, myBaseClass exists in file1.py.   The question is how can I tell
file2.py that the global variable is in file1 (without doing a silly
file1.myBaseClass

Since I am invoking file2 from file1, I would have thought that global
variables in file1 exists automatically(too much C thinking, I know)


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


Re: Repainting

2004-12-28 Thread M.E.Farmer

LutherRevisited wrote:
 I have an application that uses a WxListCtrl to hold data that is
updated
 extremely fast.  When I run my application the listctrl updates so
fast that it
 practically disappears.  Is there a way I can have it update with the
user
 seeing it update rapidly without the dissapearing?  Right now I have
used the
 freeze and thaw methods to get rid of that disappearing listctrl
problem, only
 now you have to wait for it to run it's course to see the output.  It
really
 isn't critical, I just think it would be a cool visual if the user
could see it
 rapidly updating, I'm beginning to think that because of how rapidly
it updates
 that isn't possible, but if it is I appreciate any help.  And you
guys would be
 so proud of me, I actually downloaded the Wx docs and found freeze
and thaw all
 on my own under wxwindows memberslol.  That's a quick note out to
all that
 have been patient with me while helping me learn wxpython.
Glad to see you downloaded the docs!
Ok since you made some effort I will try again to help you.
just do a search for wxYield.

This is straight off the web.
'''
::wxYield

Bool wxYield(void)

Yields control to pending messages in the windowing system (has no
effect under XView or Motif). This can be useful, for example, when a
time-consuming process writes to a text window. Without an occasional
yield, the text window will not be updated properly, and (since Windows
multitasking is cooperative) other processes will not respond.

Caution should be exercised, however, since yielding may allow the user
to perform actions which are not compatible with the current task.
Disabling menu items or whole menus during processing can avoid
unwanted reentrance of code.
'''
Just sprinkle your listctrl update loop with wx.Yield().
I am not sure if this will help you but has fixed update problems for
me before.
By the way when you have problems with wxPython you may get more
responses from  the wxPython list. Comp.lang.python is good for general
python, but wxPython list is specific to the wx framework.
hth,
M.E.Farmer

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


Re: A scoping question

2004-12-28 Thread Premshree Pillai
On Tue, 28 Dec 2004 19:59:01 GMT, It's me [EMAIL PROTECTED] wrote:
 
 Premshree Pillai [EMAIL PROTECTED] wrote in message
 news:[EMAIL PROTECTED]
  On Tue, 28 Dec 2004 19:34:36 GMT, It's me [EMAIL PROTECTED] wrote:
   This must be another newbie gotchas.
  
   Consider the following silly code, let say I have the following in
 file1.py:
  
   #=
   import file2
   global myBaseClass
   myBaseClass = file2.BaseClass()
   myBaseClass.AddChild(file2.NextClass())
   #=
 
  You have declared myBaseClass to be global, but it doesn't exist.
 
 
 No, myBaseClass exists in file1.py.   The question is how can I tell

Umm, from the sample code (for file2.py) that you provided, I don't
see myBaseClass. You've only declared it to be global in file2.py, but
it does not exist -- does not exist in the sense that it has no type
associated with it, which in turn means meaning you cannot apply
methods to it.

 file2.py that the global variable is in file1 (without doing a silly
 file1.myBaseClass
 
 Since I am invoking file2 from file1, I would have thought that global
 variables in file1 exists automatically(too much C thinking, I know)
 
 
 --
 http://mail.python.org/mailman/listinfo/python-list
 


-- 
Premshree Pillai
http://www.livejournal.com/~premshree
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A scoping question

2004-12-28 Thread Steven Bethard
It's me wrote:
This must be another newbie gotchas.
Consider the following silly code, let say I have the following in file1.py:
#=
import file2
global myBaseClass
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass())
#=
and in file2.py, I have:
#=
global myBaseClass
class BaseClass:
def __init__(self):
self.MyChilds = []
 ...
def AddChild(NewChild):
self.MyChilds.append(NewChild)
...
class NextClass:
def __init__(self):
for eachChild in myBaseClass.MyChilds:  # - ERROR
...
#=
When I run this, Python complains that myBaseClass is undefined in the last
line above.
What am I doing wrong?  (Yes, I know I am thinking too much in C).  I
thought the global declaration would have been sufficient but it's obviously
not.
I think you're confused about what the global keword does.  Declaring a 
name as global makes that name global *to the module*:

http://docs.python.org/ref/global.html
http://docs.python.org/lib/built-in-funcs.html#l2h-32
What you probably want instead is:
 file1.py 
import file2
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass())
--
 file2.py 
class BaseClass:
def __init__(self):
self.MyChilds = []
def AddChild(self, NewChild):
self.MyChilds.append(NewChild)
class NextClass:
def __init__(self):
from file1 import myBaseClass  # IMPORT
for eachChild in myBaseClass.MyChilds:
pass
--
Note that I import myBaseClass in __init__.  If I imported it at the top 
of the module, then file1 would import file2 which would then import 
file1 and you'd have a circular dependency.

As it is, your code is very tightly coupled.  Why don't you put all this 
code into a single module?

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


Re: A scoping question

2004-12-28 Thread Steven Bethard
It's me wrote:
This must be another newbie gotchas.
Consider the following silly code
[snip tightly coupled code]
A few options that also might work better than such tightly coupled modules:
 file1.py 
import file2
myBaseClass = file2.BaseClass()
class NextClass:
def __init__(self):
for eachChild in myBaseClass.MyChilds:
pass
myBaseClass.AddChild(file2.NextClass())
--
 file2.py 
class BaseClass:
def __init__(self):
self.MyChilds = []
def AddChild(self, NewChild):
self.MyChilds.append(NewChild)
--
or
 file1.py 
import file2
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass(myBaseClass))
--
 file2.py 
class BaseClass:
def __init__(self):
self.MyChilds = []
def AddChild(self, NewChild):
self.MyChilds.append(NewChild)
class NextClass:
def __init__(self, myBaseClass):
for eachChild in myBaseClass.MyChilds:
pass
--
--
http://mail.python.org/mailman/listinfo/python-list


Re: pygame + py2exe = bad exe. why?

2004-12-28 Thread M.E.Farmer
Hello Erik,
Have you ever seen pygame2exe.py?
It is a py2exe script for pygame.
I found this on my hard drive from last year.
I have never created an exe from pygame using this script , so it might
be useless ;)
Do a search might be updated by now.can not remember where I got it
from ( maybe pygame website? )


py#make standalone, needs at least pygame-1.5.3 and py2exe-0.3.1
pyfrom distutils.core import setup
pyimport sys, os, pygame, shutil
pyimport py2exe
py
py#setup the project variables here.
py#i can't claim these will cover all the cases
py#you need, but they seem to work for all my
py#projects, just change as neeeded.
py
py
pyscript = aliens.py#name of starting .PY
pyicon_file =   #ICO file for the .EXE (not working
well)
pyoptimize = 2#0, 1, or 2; like -O and -OO
pydos_console = 1 #set to 0 for no dos shell when run
pyextra_data = ['data', 'readme.txt'] #extra files/dirs copied to game
pyextra_modules = ['pygame.locals']   #extra python modules not auto
found
py
py#use the default pygame icon, if none given
pyif not icon_file:
pypath = os.path.split(pygame.__file__)[0]
pyicon_file = '' + os.path.join(path, 'pygame.ico') + ''
py#unfortunately, this cool icon stuff doesn't work in current py2exe
:(
py#icon_file = ''
py
py
py#create the proper commandline args
pyargs = ['py2exe', '--force', '-O'+`optimize`]
pyargs.append(dos_console and '--console' or '--windows')
pyif icon_file:
pyargs.append('--icon')
pyargs.append(icon_file)
pyargs.append('--force-imports')
pyargs.append(','.join(extra_modules))
py#args.append(','.join(pygame_modules + extra_modules))
pysys.argv[1:] = args + sys.argv[1:]
py
pyproject_name = os.path.splitext(os.path.split(script)[1])[0]
py
py
py#this will create the executable and all dependencies
pysetup(name=project_name, scripts=[script])
py
py#also need to hand copy the extra files here
pydef installfile(name):
pydst = os.path.join('dist', project_name)
pyprint 'copying', name, '-', dst
pyif os.path.isdir(name):
pydst = os.path.join(dst, name)
pyif os.path.isdir(dst):
pyshutil.rmtree(dst)
pyshutil.copytree(name, dst)
pyelif os.path.isfile(name):
pyshutil.copy(name, dst)
pyelse:
pyprint 'Warning, %s not found' % name
py
py
py
py
pypygamedir = os.path.split(pygame.base.__file__)[0]
pyinstallfile(os.path.join(pygamedir,
pygame.font.get_default_font()))
pyinstallfile(os.path.join(pygamedir, 'pygame_icon.bmp'))
pyfor data in extra_data:
pyinstallfile(data)

This is probably a complete mess by the time it reaches you.
I started every line with py so just unwrap the lines that didn't make
it.
Hth,
M.E.Farmer

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


Re: Best GUI for small-scale accounting app?

2004-12-28 Thread Ed Leafe
On Dec 28, 2004, at 1:16 PM, Paul Rubin wrote:
Well, those are commercial developers who are afraid of the GPL.
	No, they were several members of the Python community. I disagreed 
with their interpretation of the GPL, but the fact remains that it was 
a major stumbling block to getting others involved.

I don't see how you lose with the GPL, unless you count missing out on
the exciting opportunity to be an unpaid employee of someone else's
corporation, without even getting back improvements made to your code.
	The downside is gaining critical mass for the project. Having several 
visible Python folks refuse to even look at what we were doing was not 
helping things at all. And I think it the chances of someone else using 
my code without payment or anything is a pretty small risk. We still 
own copyright, which means that while they can use it, they can't claim 
it's theirs.

I'm not sure what sizers are
OIC - then this is not going to be very fruitful.
Ehhh, sounds a little too much like javabeans :).
	No, it sounds like every other development environment for creating 
database applications. I looked a long time for something like this in 
Python before undertaking the writing of it myself.

 ___/
/
   __/
  /
 /
 Ed Leafe
 http://leafe.com/
 http://dabodev.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: HELP Non-Blocking reads from sys.stdin in Windows.

2004-12-28 Thread Miki Tebeka
Hello Barr,

 I am in real need of a way to perform non blocking reads from sys.stdin on
 windows. I have looked every where for an answer but but with no luck. I
 beleive there there must be a way of doing this, can some one  please help
 asap.
Warning: The below code wasn't tested at all...

---
from Queue import Queue, Empty
from sys import stdin
from threading import Thread

# Reading from empty stdin error
class EmptyError(Exception): pass 

# Input queue
_queue = Queue()

def produce():
'''Read one char at a time from stdin and place in _queue'''
try:
while 1:
c = stdin.read(1) # Read one char
if not c: # EOF
_queue.put(EOFError, 1)
break
_queue.put(c, 1)
except EOFError, e:
_queue.put(EOFError)

# Start the thread
t = Thread(target=produce)
t.setDaemon(1) # Don't inhibit interperter exit
t.start() # Start thread

def get():
'''Get one item from queue.

Might raise EmptyError if queue is empty or EOFError of end of input
'''
try:
val = _queue.get(0)
if val is EOFError:
raise EOFError
return val
except Empty:
raise EmptyError

def is_empty():
'''Tell if no input is ready'''
return _queue.empty()

---

HTH.
--

Miki Tebeka [EMAIL PROTECTED]
http://tebeka.bizhat.com
The only difference between children and adults is the price of the toys
-- 
http://mail.python.org/mailman/listinfo/python-list


naming conventions (WAS: A scoping question)

2004-12-28 Thread Steven Bethard
It's me wrote:
#=
import file2
global myBaseClass
myBaseClass = file2.BaseClass()
myBaseClass.AddChild(file2.NextClass())
#=
[snip]
#=
global myBaseClass
class BaseClass:
def __init__(self):
self.MyChilds = []
 ...
def AddChild(NewChild):
self.MyChilds.append(NewChild)
...
class NextClass:
def __init__(self):
for eachChild in myBaseClass.MyChilds:  # - ERROR
...
#=
Also worth mentioning if you're just starting with Python.  Python has 
some official naming conventions:

http://www.python.org/peps/pep-0008.html
These are just recommendations of course, but if you have the option 
(e.g. you're not constrained by style enforced by your employer), and 
you'd like your code to look more like standard Python modules, you 
might consider using these suggestions.  This would make your code look 
something like:

#=
import file2
global my_base_class
my_base_class = file2.BaseClass()
my_base_class.add_child(file2.NextClass())
#=
#=
global my_base_class
class BaseClass:
def __init__(self):
self.my_childs = []
 ...
def add_child(new_child):
self.my_childs.append(new_child)
...
class NextClass:
def __init__(self):
for each_child in my_base_class.my_childs:  # - ERROR
...
#=
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter vs wxPython

2004-12-28 Thread Jarek Zgoda
Cameron Laird wrote:
IMO, wxPython has a softert learning curve (specially if you use 
wxGlade), is portable between unix/windows/mac, with the advantage 
over Tkinter that it has a native look. Regarding documentation, 
.
While people seem to mean a range of different things when they
write, Tkinter doesn't look 'native', most of them are being
addressed in revisions currently underway.  In fact, new look-
and-feel are available in early releases for those interested in
experimentation.
Well, while on Windows native look exists, on X11 native has other 
meaning. On my wife's desktop it's KDE that is native, GNUStep is native 
on mine and I strongly object calling GTK native, as one can read on 
SWT/Eclipse website. There's no universally native look on X11. Some 
toolkits look better, but this is a matter of personal taste, for 
software developer clean, stable API and suitable widgets are of much 
higher value.

--
Jarek Zgoda
http://jpa.berlios.de/ | http://www.zgodowie.org/
--
http://mail.python.org/mailman/listinfo/python-list


install questions

2004-12-28 Thread A Chan
Hi, All,

I'm new in Python. I just install ActivePython 2.4 on
my PC and also install SOAPpy-0.11.6.zip,
soapy-0.1.win32.exe. When I run the following script,
I got no module named SOAPpy. Am I missing any
modules? Thanks


Angela

error message:

Traceback (most recent call last):
  File
C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py,
line 310, in RunScript
exec codeObject in __main__.__dict__
  File C:\test1.py, line 1, in ?
import SOAPpy
ImportError: No module named SOAPpy

=
Python script:

import SOAPpy

WSDL_URI =
http://www.xmethods.net/sd/2001/TemperatureService.wsdl;
service = SOAPpy.WSDL.Proxy(WSDL_URI)

# if you are behind a proxy server, you need to set
this
service.soapproxy.http_proxy = 'PROXY_HOST:PROXY_PORT'

# set config so that we dump the SOAP envelopes
# (sometimes you will be thrilled to see the SOAP
envelopes)
service.soapproxy.config.dumpSOAPOut = 1
service.soapproxy.config.dumpSOAPIn = 1

temp = service.getTemp('90210') # get temperature in
Beverly Hills
print 'The temperature in Beverly Hills is',temp,'F'
===





__ 
Do you Yahoo!? 
Yahoo! Mail - You care about security. So do we. 
http://promotions.yahoo.com/new_mail
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: install questions

2004-12-28 Thread Premshree Pillai
Umm, the file is called soap.py, so when you import you'll have to do a:

import soap


On Tue, 28 Dec 2004 13:09:48 -0800 (PST), A Chan [EMAIL PROTECTED] wrote:
 Hi, All,
 
 I'm new in Python. I just install ActivePython 2.4 on
 my PC and also install SOAPpy-0.11.6.zip,
 soapy-0.1.win32.exe. When I run the following script,
 I got no module named SOAPpy. Am I missing any
 modules? Thanks
 
 Angela
 
 error message:
 
 Traceback (most recent call last):
   File
 C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py,
 line 310, in RunScript
 exec codeObject in __main__.__dict__
   File C:\test1.py, line 1, in ?
 import SOAPpy
 ImportError: No module named SOAPpy
 
 =
 Python script:
 
 import SOAPpy
 
 WSDL_URI =
 http://www.xmethods.net/sd/2001/TemperatureService.wsdl;
 service = SOAPpy.WSDL.Proxy(WSDL_URI)
 
 # if you are behind a proxy server, you need to set
 this
 service.soapproxy.http_proxy = 'PROXY_HOST:PROXY_PORT'
 
 # set config so that we dump the SOAP envelopes
 # (sometimes you will be thrilled to see the SOAP
 envelopes)
 service.soapproxy.config.dumpSOAPOut = 1
 service.soapproxy.config.dumpSOAPIn = 1
 
 temp = service.getTemp('90210') # get temperature in
 Beverly Hills
 print 'The temperature in Beverly Hills is',temp,'F'
 ===
 
 
 __
 Do you Yahoo!?
 Yahoo! Mail - You care about security. So do we.
 http://promotions.yahoo.com/new_mail
 --
 http://mail.python.org/mailman/listinfo/python-list
 


-- 
Premshree Pillai
http://www.livejournal.com/~premshree
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reference behavior through C (was: Lambda going out of fashion)

2004-12-28 Thread Craig Ringer
On Wed, 2004-12-29 at 02:08, Cameron Laird wrote:
 In article [EMAIL PROTECTED],
 Craig Ringer  [EMAIL PROTECTED] wrote:
   .
   .
   .
   IMO the reference behaviour of functions in the C API could be
 clearer. [snip]  .
   .
   .
 This is a sensitive area for me, too.  I'd welcome insight
 on how to think about this.  If Pythonia were a better place
 in this regard, how would it be?  Reference documents that
 more transparently define reference behavior?

I think the current documentation does a fairly good job of that when
describing how to treat the return values of the various functions, but
a much poorer one when covering their arguments.

 A convention for API names that reveals reference characteristics?

That is what I'd lean towards personally... but of course there's
duplication and compatibility to be considered.

--
Craig Ringer

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


RE: built-in 'property'

2004-12-28 Thread Bob . Cowdery
Title: RE: built-in 'property'





Thanks to everyone that has helped on this. What I am trying to do is create a capability based api that I can build to order. This is as far as I get at the moment.

Each of the first three classes represents some function I can do to a radio, there would be many of these in practice. The next class is the API. I figure I have to include all the possible radio function classes in this as I can't figure out how to make the classes I include per instance. When I create the API object I pass in a capability array as in the last class. I use these classes as follows.

 import capability as c
 import radioapi as r
 caps = c.Capability()
 cap = caps.getCaps('SDR1000')
 cap
['mode', 'freq', 'blanker']
 api = r.API(cap)
 r.caps
['mode', 'freq', 'blanker']
 api.mode
Retrieving mode var mode
'lsb'
 api.freq
Retrieving freq var freq
7.0801
 api.blanker
Retrieving blanker var blanker
1
 hasattr(api, 'monitor')
0


This is the behaviour I want, each class responds if it is in the capability array. The user can test attributes with hasattr(klass, 'att') to see if it is supported. I can create another instance with a different radio and it will respond accordingly. The problem of course is that in class API, caps is global so as soon as I create another instance the first starts responding to the new capability. If I try to make caps per instance I get into all sorts of trouble with recursion. Does anyone have an idea how to fix this or is it just impossible to make this work.

Regards
Bob
 
class Mode(object):


 def __init__(self, initval=None, name='var'):
 self.val = initval
 self.name = name


 def __get__(self, obj, objtype):
 print 'Retrieving mode', self.name
 return self.val


 def __set__(self, obj, val):
 print 'Updating mode' , self.name
 self.val = val
import capability


class Freq(object):


 def __init__(self, initval=None, name='var'):
 self.val = initval
 self.name = name


 def __get__(self, obj, objtype):
 print 'Retrieving freq', self.name
 return self.val


 def __set__(self, obj, val):
 print 'Updating freq' , self.name
 self.val = val
 
class Blanker(object):


 def __init__(self, initval=None, name='var'):
 self.val = initval
 self.name = name


 def __get__(self, obj, objtype):
 print 'Retrieving blanker', self.name
 return self.val


 def __set__(self, obj, val):
 print 'Updating blanker' , self.name
 self.val = val 


class API(object):
 
 # create all possible radio classes
 mode=Mode('lsb', 'var mode')
 freq=Freq(7.080, 'var freq')
 blanker=Blanker(True, 'var blanker')
 global caps
 caps = []
 
 def __init__(self, pcaps):
 global caps
 caps = pcaps 


 def __getattribute__(self, key):
 global caps
 if (key in caps) or (key == 'caps'):
 obj = object.__getattribute__(self, key)
 if hasattr(obj, __get__):
 return obj.__get__()
 return obj
 else:
 raise AttributeError, unreadable attribute


class Capability(object):
 
 m_cap = {
 'SDR1000': ['mode','freq','blanker'],
 'MyRig': ['mode','freq'],
 'YourRig': ['mode', 'blanker']
 }
 
 def getCaps(self, radio):
 return self.m_cap[radio]



*** Confidentiality Notice *** 
Proprietary/ConfidentialInformation belonging to CGI Group Inc. and its 
affiliatesmay be contained in this message. If you are not a 
recipientindicated or intended in this message (or responsible 
fordelivery of this message to such person), or you think forany reason 
that this message may have been addressed to youin error, you may not use or 
copy or deliver this messageto anyone else. In such case, you should 
destroy thismessage and are asked to notify the sender by reply 
email.

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

Re: Mutable objects which define __hash__ (was Re: Why are tuples immutable?)

2004-12-28 Thread Bengt Richter
On Sun, 26 Dec 2004 12:17:42 +1000, Nick Coghlan [EMAIL PROTECTED] wrote:

Bengt Richter wrote:
 I take it you are referring to regular python dictionaries,

Correct. So I'll skip over the sections talking about alternate lookup 
strategies in my reply.
Cool.

Anyway, what are the consequences of a type which has a 'variable hash'?

The only real bad consequence is that the internal state of a dictionary can 
break if someone alters the hash of one of its keys. The restriction to 
'constant hashes' is aimed squarely at eliminating this class of programming 
errors. It doesn't actually provide any performance gain.
 
 Why not? It means you only have to compute the hash for any given object 
 once,
 and you can cache the hash value. That could be a biggie if you had megabyte 
 trees
 of nested tuples as keys and reused them frequently for lookup.

Allowing mutation doesn't mean abandoning your caching - it just means you 
need 
a way to tell the dict to update it's key cache (i.e. rehash())
There's more than one way a key gets hashed: once when the key:value association
is entered into the dict state. (It pays to save the hash value in the dict 
along with references
to the key and value objects for several reasons, which I'll get to [1]).

A second time a key may be hashed is when it is used as a lookup key. This can 
be a reference to
the identical key object first used, or it can be a new object. A new object 
has to be hashed in order
to have a hash value to use in finding candidate keys to compare to. If _this_ 
object
is used as a key again, it must be hashed again -- unless it is an object that 
caches its own
hash and invalidates it when mutated so it can rehash itself if its __hash__ 
method is subsequently
called.

Thus re-use of a different lookup key than the original provides an opportunity 
for a performance
gain in the lookup if the key object caches it hash value for return by 
__hash__.
That's what I meant by why not? in response to your assertion that the 
constant hash restriction
doesn't (ok, I took that as a can't ;-) provide any performance gain.

[1] IME a hash is only necessary to optimize operation of a dict. The primary 
purpose is to limit
the number of comparisons necessary to determine whether a key exists in the 
dict, and to find the
matching one. First the hash value is converted to a bucket selection. This 
will involve some
function of the full hash value, reducing it to a value that can access 
buckets. This function can
potentially change as the dict grows. Once the bucket is selected, a number of 
keys may be found there.
Since thejob is to find equality, the hash value can serve again, using all its 
bits, to select a subset
of the keys in the bucket that _may_ be equivalent. This is an optimization to 
avoid comparing
key objects with differing hashes -- which is fine for immutable keys, which 
can't be the same
if their hashes differ. IOW, immutable key candidates may be rejected 
immediately if their hash values
aren't equal to the lookup key's hash value.

The other side of this coin is that keys whose hash values _are_ equal to the 
lookup key's hash value
must all be compared in some order (probably whatever order is convenient in 
working through a bucket)
until an equal key is found, or not.

This means that if we give all mutable keys the same hash value, they will all 
be in the same bucket,
and that bucket will be searched in some order for an equal key, and the first 
one found to be equal
will be what I called the effective unique key. With a constant hash value -- 
e.g., zero -- there
is no reason to re-hash: the hashes haven't changed ;-) There may be a reason 
to eliminate shadowed keys
with duplicate equal values, but it's not necessary for consistent operation.

Based on this, I made a wrapper object for mutable keys, which returns a 
constant zero as the hash value,
and provides a __cmp__ of the wrapped object for the dict's key equality 
testing. This means if W is the
wrapper class, you can use W(mutable) as a key in an ordinary dict, and they 
all go to the same bucket
as 0 and 0.0 and whatever else hashes to 0.

I decided to modify my dict subclass to wrap unhashable key objects 
automatically, with very similar effect
to the original, except eliminating the parallel lists for the mutable keys and 
their values. The only thing
is that I knew the order of list.index searching, but I don't know the order of 
bucket 0 searching, so
shadowing and elimination of duplicate keys by re-instantiation will probably 
eliminate different duplicates
sometimes.


 I think, for one thing, it would be more efficient to notice that some keys 
 were guaranteed not
 to need rehashing... um, maybe by paritioning the key set into immutables 
 and mutables ;-)

True, since otherwise rehash() would have to check every key, even the 
immutable 
ones. However, that only affects the time required for a rehash(), rather than 
general dictionary operation.
Given that you 

Problems installing MySQLdb on Windows [newbie]

2004-12-28 Thread Alex Meier
hi, all!

this is my first contact with python, I installed python 2.4 (on Win2k) 
and unzipped the MySQLdb package MySQL-Python 1.0.0 for win32 into 
Lib/site-packages. 

However, when I try to import the MySQLdb package, I am faced with the 
error message DLL load failed, in more detail:

 import MySQLdb

Traceback (most recent call last):
  File pyshell#9, line 1, in -toplevel-
import MySQLdb
  File C:\Programme\Python24\lib\site-packages\MySQLdb\__init__.py, 
line 27, in -toplevel-
import _mysql
ImportError: DLL load failed: Das angegebene Modul wurde nicht gefunden.

The directory structure is (only the relevant parts):

C:\Programme\Python24
 |
 +-- Lib
  |
  +-- site-packages
|
+-- _mysql.pyd
+-- _mysql_exceptions.py
+-- CompatMysqldb.py
+-- MySQLdb
  |
  +-- __init__.py
  +-- connections.py
  +-- ...

One thing strikes me: in sys.path, the path to site-packages contains 
the dir lib (lowercase!) whereas in the file system it would be 
written Lib (mixed case). Could this pose a problem?

This is the path:

 sys.path
['C:\\Programme\\Python24\\Lib\\idlelib', 'C:\\WINNT\\system32
\\python24.zip', 'C:\\Programme\\Python24', 'C:\\Programme\\Python24
\\DLLs', 'C:\\Programme\\Python24\\lib', 'C:\\Programme\\Python24\\lib
\\plat-win', 'C:\\Programme\\Python24\\lib\\lib-tk', 'C:\\Programme
\\Python24\\lib\\site-packages']

Any hints for me?

TIA
Alex

-- 
remove underscore+nospam if you want to mail me
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: argument type

2004-12-28 Thread Roy Smith
It's me [EMAIL PROTECTED] wrote:
 How can I tell from within a function whether a particular argument is a
 sigular type, or a complex type?
 ...
 In C++, you would do it with function overloading.  If arg1 is always simple
 type, I wouldn't care what it is.  But what if I *do* need to know whether
 arg1 is a list or not?

I have a vague feeling you're trying to write C++ in Python, and that 
usually doesn't work well.  In general, C++ (and Java) is all about 
types of things, while Python is more about capabilities of things.

What do you mean by a simple type as opposed to a complex type?  I 
suspect by complex type you really mean tuple or list.  If that's 
the case, you can certainly do something like:

def myFunc (arg):
   if isinstance (arg, tuple) or isinstance (arg, list):
  blah, blah, blah

But before you do that, you might want to think if this is really what 
you want to do.  What, exactly, is it that you're trying to do that 
requires you to know what type of object an argument is?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: objects as mutable dictionary keys

2004-12-28 Thread John Roth
I think that's a good summary. The condensed
version is that the results of both __hash__() and
__cmp__() have to remain stable for dicts to work
as one would expect. __cmp__ doesn't do that
for lists, and it isn't defined by default for user
objects.
John Roth
Peter Maas [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
Peter Maas schrieb:
There was a huge and sometimes heated debate about tuples, lists and
dictionaries recently, and the mainstream opinion was that dictionary
keys must not be mutable, so lists are not allowed as dictionary keys.
Warning, long posting (~ 100 lines)
The existence of lists and tuples and the impossibility to use
lists as dictionary keys is a constant source of irritation for
Python newcomers. Recent threads in c.l.py have revealed that
even programmers like me using Python for some years now often don't
have a clear picture. To put an end to this misery I tried to learn
from the recent discussions and to explain to myself what's going on.
My problem was that I didn't know exactly how a dictionary and
a dictionary lookup works:
A dictionary maps key values to data values. Sketch of a dictionary
lookup(value = dict[key]):
def lookup(dict, key):
'''dictionary lookup is done in three steps:
   1. A hash value of the key is computed using a hash function.
  Hash functions map a large set L to a (usually) smaller
  set S.
  A hash function must satisfy:
  (*) for all e1, e2 in L: h(e1) != h(e2) = e1 != e2
  A hash function should satisfy as well as possible:
  for all e1, e2 in L: h(e1) == h(e2) = e1 == e2
  Violation of the latter condition means a hash collision,
  i.e. two or more elements of L have the same hash value.
  This should be highly unlikely for good hash functions.
  If not, hash lookup becomes as slow as sequential lookup.
   2. The hash value addresses a location in dict.data which is
  supposed to be an array of bins. A bin contains a collision
  list of (key,value) pairs.
   3. The collision list addressed by the hash value is searched
  sequentially until a pair is found with pair[0] == key. The
  return value of the lookup is then pair[1]. Equality (==) is
  defined by the function cmp(). The return value for equality is
  0, for inequality some other value.
'''
h = hash(key)  # step 1
cl = dict.data[h]  # step 2
for pair in cl:# step 3
if cmp(key, pair[0]) == 0:
return pair[1]
else:
raise KeyError, Key %s not found. % key
Thus a data type must be a valid input for hash() and cmp() to be usable
as a dictionary key. hash() and cmp() must satisfy the condition (*) in
lookup.__doc__ for this data type.
Is a list a suitable candidate for a dictionary key? hash(list) = id(list)
and cmp(list1, list2) comparing id(list1) with id(list2) would satisfy
condition (*). But this definition completely ignores list contents,
causing big surprises for programmers:
- Different lists with the same content would be mapped to different
  dictionary values.
- Dictionary lookup with list literals would be impossible.
To avoid these surprises dictionary lookup would have to use list contents
instead of list id. Consider the (hypothetical, not working) code:
 d = dict()
 li = [1,2,3]
 d[li] = 123
 d[[1,2,3]]
123
Now assume li is changed (e.g. li[2] = 4). There are two options to handle 
this,
let the dictionary ignore changes

 d[li]
KeyError: [1,2,4] not found in dictionary. (even worse: a previously 
existing
[1,2,4] map is returned).

or let the dictionary follow changes
 d[[1,2,3]]
MovedError: Please address future lookups to [1,2,4] :)
Both are pretty unsatisfactory. Conclusion: dictionary lookup with
mutable types like lists is a source of unpleasant surprises for the
programmer and therefore impossible in Python. This is the point where
tuples come in. They have nearly the same interface as lists but cannot
be changed once they have been created thereby avoiding the problems
discussed for lists. Thus tuples can be used as dictionary keys.
What about instances of user defined classes?
User defined classes can be anything the programmer likes but yet their
instances are usable as dictionary keys because there is a default:
hash(object) = id(object) and cmp(object1, object2) compares id(object1)
with id(object2). The same setting that has been discussed above for lists
and has been found unsatisfactory. What is different here?
1. It is a default setting which can be adapted to each class by defining/
   overriding the methods __hash__ and __cmp__.
2. For objects identity is more important than for lists.
That's it.
Please correct me if I'm wrong. If not, a poor programmer's soul has
found peace eventually :)
--
---
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel 

Re: Problems installing MySQLdb on Windows [newbie]

2004-12-28 Thread Steve Holden
Alex Meier wrote:
hi, all!
this is my first contact with python, I installed python 2.4 (on Win2k) 
and unzipped the MySQLdb package MySQL-Python 1.0.0 for win32 into 
Lib/site-packages. 

However, when I try to import the MySQLdb package, I am faced with the 
error message DLL load failed, in more detail:


import MySQLdb

Traceback (most recent call last):
  File pyshell#9, line 1, in -toplevel-
import MySQLdb
  File C:\Programme\Python24\lib\site-packages\MySQLdb\__init__.py, 
line 27, in -toplevel-
import _mysql
ImportError: DLL load failed: Das angegebene Modul wurde nicht gefunden.

The directory structure is (only the relevant parts):
C:\Programme\Python24
 |
 +-- Lib
  |
  +-- site-packages
|
+-- _mysql.pyd
+-- _mysql_exceptions.py
+-- CompatMysqldb.py
+-- MySQLdb
  |
  +-- __init__.py
  +-- connections.py
  +-- ...
One thing strikes me: in sys.path, the path to site-packages contains 
the dir lib (lowercase!) whereas in the file system it would be 
written Lib (mixed case). Could this pose a problem?

No, Windows file lookups are not case-sensitive.

This is the path:

sys.path
['C:\\Programme\\Python24\\Lib\\idlelib', 'C:\\WINNT\\system32
\\python24.zip', 'C:\\Programme\\Python24', 'C:\\Programme\\Python24
\\DLLs', 'C:\\Programme\\Python24\\lib', 'C:\\Programme\\Python24\\lib
\\plat-win', 'C:\\Programme\\Python24\\lib\\lib-tk', 'C:\\Programme
\\Python24\\lib\\site-packages']
Any hints for me?
TIA
Alex
I'm not sure that the Win32 installer is up to date for 2.4. I recently 
mailed Andy Dustman with a copy of the up to date installer I built, but 
I never had any acknowledgment and it doesn't appear to have found its 
way on to SourceForge yet.

I'd suggest you use a binary installer. Remove everything that your 
current install attempt dropped under site-packages, and download and run

http://pydish.holdenweb.com/pwp/MySQL-python.exe-1.0.0.win32-py2.4.exe
That's a ready-to-go no-compilation-required installer for Windows 
Python 2.4, and will get you going straight away.

regards
 Steve
--
Steve Holden   http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC  +1 703 861 4237  +1 800 494 3119
--
http://mail.python.org/mailman/listinfo/python-list


Re: argument type

2004-12-28 Thread Doug Holton
It's me wrote:
The argument I wish to pass is either one string, or a list of strings, or a
tuple of strings.
For instance, I have:
def abc(arg1, arg2, arg3)
Let say that I expect arg1 and arg3 to be a number, and arg2 can be either
one string, or a bunch of strings and I need to do something on each of the
strings passed down.  

def seq(x):
if hasattr(x,__iter__):
return x
else:
return (x,)

def abc (arg1, arg2, arg3):
for item in seq(arg2):
print item

abc(1,test1,2)
abc(1,[test1,test2],2)
abc(1,2,3)
abc(1,[2,3,4],5)
abc(1,(2,3,4),5)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best GUI for small-scale accounting app?

2004-12-28 Thread JanC
Ed Leafe schreef:

 I think the field of GUI frameworks / tools for Python is fragmented
 because it's fragmented outside of Python too...
 
  I think that the reason things are fragmented in this field is that 
 none of the tools are simple enough to learn.

Even on Windows, where several well-known and/or easy to use Rapid GUI  
Database Development Tools exist (Delphi, VB, Access, Visual FoxPro, 
FileMaker, ...), the framework field is fragmented: Microsoft's Win32, MFC 
 WTL, Borland's VCL  CLX, wxWidgets, System.Windows.Forms, several Java 
frameworks, ...

But even then, if DaBo ever becomes as easy to use as Delphi/VB for this 
type of applications, while remaining cross-platform, that might easily 
double the number of Python developers.  ;-)


-- 
JanC

Be strict when sending and tolerant when receiving.
RFC 1958 - Architectural Principles of the Internet - section 3.9
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problems installing MySQLdb on Windows [newbie]

2004-12-28 Thread John Machin

Alex Meier wrote:
 hi, all!

 this is my first contact with python, I installed python 2.4 (on
Win2k)
 and unzipped the MySQLdb package MySQL-Python 1.0.0 for win32 into
 Lib/site-packages.

 However, when I try to import the MySQLdb package, I am faced with
the
 error message DLL load failed, in more detail:


(1) RTFHomePage (FIRST SENTENCE):
MySQL versions 3.22, 3.23 and 4.0; and Python versions 1.5.2-2.3 are
supported. 

Background: A .pyd has to be linked against a specific PythonXY.dll;
see point (4) below.

(2) A package which doesn't provide an installer but merely invites you
to unzip everything into .../lib/site-packages is a bit dodgy. If you
had have followed the instructions blindly, you would have ended up
with a directory called mysql-python-1.0.0.win32-py2.3 [, look,
2.3] as a child of site-packages.

(3) Lib versus lib is not the problem; if you examine your
traceback, you will see that it found Lib even though lib was
specified. Windows file names are not case-sensitive. However there can
be Python-imposed problems which can be overcome (in the remote event
that you meet these problems) by using the PYTHONCASEOK environment
veriable.

(4) Why you are getting the DLL not found message is beyond me, given
your description of what you've done. Perhaps the picture is being
obscured by your using pyshell. What you should have got is something
like this [I've extracted _mysql.pyd into my junk directory]:

C:\junkpython
Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on
win32
Type help, copyright, credits or license for more information.
 import _mysql
Traceback (most recent call last):
File stdin, line 1, in ?
ImportError: Module use of python23.dll conflicts with this version of
Python.


(5) But the _mysql.pyd appears to be a bit suspect anyway:

C:\junk\python23\python
Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)]
on win32
Type help, copyright, credits or license for more information.
 import _mysql
Traceback (most recent call last):
File stdin, line 1, in ?
ImportError: _mysql: init failed


(6) I suggest that you contact the package maintainer.

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


Re: emulating python shell

2004-12-28 Thread Fernando Perez
Uwe Mayer wrote:

 Hi,
 
 in an application I want to provide direct access to the python interpreter
 of the running program.
 I use rawinput() and exec() to read an input string and a self-made function
 to check wether the inputed block is closed and then execute it.
 
 When running python interactively the result of the previous statement is
 assigned to the variable _ and commands like dir() just output their
 results to stdout.
 However, executions of the sort:
 
 exec(_ = +command)
 
 don't work.
 
 Any ideas how to mimick python -i 's behaviour?

You can look at the code.py module in the python standard lib.  It implements a
pure-python interactive interpreter from scratch, so there's no need for you
to reinvent that particular wheel.  Since it's in the standard lib, you can
rely on it for deployment to external sites.

plug
If you want something more sophisticated, and ready-made for this kind of
embedding, look at ipython: http://ipython.scipy.org.  IPython is itself based
on code.InteractiveConsole, but at this point it has overridden almost all of
the  methods in the base class.

Embedding it is as easy as:

from IPython.Shell import IPShellEmbed 
ipshell = IPShellEmbed() 
ipshell() # this call anywhere in your program will start IPython 

You can have multiple embedded instances, and they can be initialized to use
anythingb

You can find further details about embedding ipython here:
http://ipython.scipy.org/doc/manual/node9.html

/plug

HTH,

f

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


ImportError and jythonc

2004-12-28 Thread Henri Sivonen
I have a Jython script that uses Java classes and runs fine using 
jython. It also compiles using jythonc. However, when I try to run the 
compiled program with the same CLASSPATH, I get an ImportError upon 
first Java import.

How can I fix this?

-- 
Henri Sivonen
[EMAIL PROTECTED]
http://iki.fi/hsivonen/
-- 
http://mail.python.org/mailman/listinfo/python-list


Convert all images to JPEG

2004-12-28 Thread Thomas
Hi,

I got a bunch of different images of different types ( bmp, gif, png,
tiff etc ) and I want to convert them all to JPEGs using PIL. Is this
possible? When I try I get all sorts of errors, doing something like :

im = Image.open(srcImage) # might be png, gif etc, for instance
test1.png
im.thumbnail(size, Image.ANTIALIAS) # size is 640x480
im.save(targetName, JPEG) # targetname is test1.jpg

produces an exception. Any clues?

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


Re: Problems installing MySQLdb on Windows [newbie]

2004-12-28 Thread Alex Meier
In article [EMAIL PROTECTED], [EMAIL PROTECTED] says...
 http://pydish.holdenweb.com/pwp/MySQL-python.exe-1.0.0.win32-py2.4.exe

 That's a ready-to-go no-compilation-required installer for Windows 
 Python 2.4, and will get you going straight away.

Thanx a lot, Steve! This worked without a hitch.

Alex


-- 
remove underscore+nospam if you want to mail me
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list addition methods compared.

2004-12-28 Thread Ishwor
On Mon, 27 Dec 2004 18:49:14 +0100, François Granger
[EMAIL PROTECTED] wrote:
 Le 27/12/04 1:03, « Ishwor » [EMAIL PROTECTED] a écrit :
 
  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??
 
 On a iBook G4 à 1.2 Ghz loaded with tons of other softwares running.
 
 fgranger:/develop/python scripts fgranger$ python listspeed.py
 @@@
 Method 1 done in (average finish time(out of 3)) - 5.6365475655
 Method 2 done in (average finish time(out of 3)) - 0.0562076569
 Method 3 done in (average finish time(out of 3)) - 0.0455052853
 @@@
 fgranger:/develop/python scripts fgranger$ python listspeed.py
 @@@
 Method 1 done in (average finish time(out of 3)) - 6.1534483433
 Method 2 done in (average finish time(out of 3)) - 0.0637686253
 Method 3 done in (average finish time(out of 3)) - 0.0500767231
 @@@
 fgranger:/develop/python scripts fgranger$ python listspeed.py
 @@@
 Method 1 done in (average finish time(out of 3)) - 5.5850391388
 Method 2 done in (average finish time(out of 3)) - 0.0594174862
 Method 3 done in (average finish time(out of 3)) - 0.0549054146
 @@@
 
Thank you. ;-) method 3 ( l += [x] which maps to l.extend([x]) )
indeed seems fastest. well anyway i'll be using timeit module from now
onwards as Steve pointed out. Thank you.

[snip]
-- 
On a cold day please heat your laptop using
while 1: pass  ;-)
cheers,
Ishwor Gurung
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problems installing MySQLdb on Windows [newbie]

2004-12-28 Thread Alex Meier
[EMAIL PROTECTED] says...
 (1) RTFHomePage (FIRST SENTENCE):
 MySQL versions 3.22, 3.23 and 4.0; and Python versions 1.5.2-2.3 are
 supported. 

I have to admit I took a chance because the error message led me to 
thinking it was a simple path problem or the like, not a version 
problem.

Anyway, I got the whole thing up and running using the binary installer 
Steve has pointed me to. So my interest in finding out what really had 
happened has decreased somewhat - to say the least.

Nevertheless, thank you for your extensive answer,
Alex

-- 
remove underscore+nospam if you want to mail me
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Q: Scheduling in scipy.cow

2004-12-28 Thread Fernando Perez
Scott David Daniels wrote:

 Mathias wrote:
 Dear NG,
 
 can somebody tell me how the work packages are scheduled to the workers?
  From the code it seems to me like a a static distribution, ie each
 worker gets the same amount of work, not taking into account if a faster
 worker already finished all work packages.
 
 Thanks,
Mathias
 
 PS: Is there a better NG for scipy related questions, espescially
 scipy.cow?
 
 I don't know the general newsgroup name, but:
  gmane.comp.python.scientific.user
 or  gmane.comp.python.scientific.devel
 
 on news.gmane.org are the places I watch for scipy stuff.

These are the gmane interfaces to the scipy user/dev lists, which can be found
here in regular mailing list form:

http://www.scipy.org/mailinglists/

Cheers,

f

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


Re: Convert all images to JPEG

2004-12-28 Thread Leif K-Brooks
Thomas wrote:
im = Image.open(srcImage) # might be png, gif etc, for instance
test1.png
im.thumbnail(size, Image.ANTIALIAS) # size is 640x480
im.save(targetName, JPEG) # targetname is test1.jpg
produces an exception. Any clues?
The problem is that test1.png is a paletted image, and JPEGs can only 
hold true-color images. Try changing the last line to:

im.convert('RGB').save(targetName, 'JPEG')
--
http://mail.python.org/mailman/listinfo/python-list


Re: More elegant way to cwd?

2004-12-28 Thread Kamilche
For library modules there are already other and more elegant means.
-Peter
Well, I want to make a script execute without error regardless of where 
the current working directory is, and without having to make the user 
modify their PYTHONPATH variable or install something in site-packages.

Is there a way to let the user just 'drag the folder' anywhere on their 
hard drive, and have it work, without having to modify any special 
system variables?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter vs wxPython

2004-12-28 Thread Michael McGarry
Definitely look at PyQt. It was the GUI framework I chose when going 
through the same process 3 weeks ago. I have to disagree with F.Geiger 
(sorry, F.Geiger), I think a GUI builder is a necessity. It saves you a 
lot of time. The alternative is to keep changing your code until your 
GUI looks as you want. With a GUI builder you draw what you want and 
have the tool generate the Python class for the GUI. It also sets up 
event handlers for you too.

Visual elements are best designed visually!!!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best GUI for small-scale accounting app?

2004-12-28 Thread Ed Leafe
On Dec 28, 2004, at 5:52 PM, JanC wrote:
But even then, if DaBo ever becomes as easy to use as Delphi/VB for 
this
type of applications, while remaining cross-platform, that might easily
double the number of Python developers.  ;-)
	Well, there are at least a half-million Visual FoxPro developers who 
have been hung out to dry by Microsoft, most of whom would love to 
leave the land of proprietary closed solutions for a bit of fresh air. 
That's where Paul and I came from, and that was our initial motivation 
for deciding to develop Dabo - there wasn't a Python tool out there 
that could even begin to approach what we were used to with VFP. If we 
could get Dabo to the point where someone familiar with VFP or even VB 
could become productive in a short time, well, I'm certain that there 
will be lots of new blood in these parts. Our work is being followed 
very closely by those communities.

 ___/
/
   __/
  /
 /
 Ed Leafe
 http://leafe.com/
 http://dabodev.com/
--
http://mail.python.org/mailman/listinfo/python-list


getattr() woes

2004-12-28 Thread Thomas Rast
Hello

I've found out about a fundamental problem of attribute lookup, the
hard way.

asyncore.py uses the following code:

class dispatcher:
# ...
def __getattr__(self, attr):
return getattr(self.socket, attr)

Now suppose that I'm asking for some attribute not provided by
dispatcher: The lookup mechanism will apparently try to find it
directly and fail, generating an AttributeError; next it will call
__getattr__ to find the attribute.  So far, no problems.

But I used a property much like this:

 import asyncore
 class Peer(asyncore.dispatcher):
... def _get_foo(self):
... # caused by a bug, several stack levels deeper
... raise AttributeError('hidden!')
... foo = property(_get_foo)
...

and as the error message suggests, the original AttributeError is
hidden by the lookup mechanism:

 Peer().foo
Traceback (most recent call last):
  File stdin, line 1, in ?
  File /usr/lib/python2.4/asyncore.py, line 366, in __getattr__
return getattr(self.socket, attr)
AttributeError: 'NoneType' object has no attribute 'foo'

Is there anything that can be done about this?  If there are no better
solutions, perhaps the documentation for property() could point out
this pitfall?

- Thomas

-- 
If you want to reply by mail, substitute my first and last name for
'foo' and 'bar', respectively, and remove '.invalid'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best GUI for small-scale accounting app?

2004-12-28 Thread Ed Leafe
On Dec 28, 2004, at 9:04 PM, Luke Skywalker wrote:
Interesting discussion. I haven't looked at Dabo yet, but the issues
that must be solved before Python is a valid alternative to
proprietary solutions like Delphi or VB are:
- speed where it matters (ie. no 20s load time)
	Load what? The app, or the data? Users don't care how long the app 
takes to start up, since they usually run it all day long. Data 
response is a whole 'nother matter, and Dabo is extremely fast in that 
regard. After all, a data set is nothing more than lists of lists, and 
Python is wicked fast with list handling.

- good RAD (IDE and GUI designer, on par with Delphi or VB)
	Still in its infancy in Dabo. Would be nice to have a team working on 
it, cos there's only so much a single developer who also has a life can 
do.

- high-quality, varied widgets
	One of the main reason we picked wxPython as our initial toolkit. 
Nearly everything we could want is in there, and they look good on all 
platforms.

- good DB connectors
	That's not something we control. Dabo is designed to use existing 
dbapi-compliant connectors, such as MySQLdb. We currently support 
MySQL, PostgreSQL, and Firebird. If anyone has a need to link to 
another db, the script to do it is pretty well abstracted.

- reasonable footprint (ie. no 20MB program just for a small
appplication; have mercy on users stuck with P3 and dial-up)
	
	Don't know where we'll come in in this regard. Most database apps 
require some sort of runtime engine, and we'll be no different.

- ease of deployment and maintenance (ie. how easy is it for an
application to launch some updated that will fetch updates from the
web)
	That seems to me more in the domain of apps created with Dabo, not 
Dabo itself. Python already has everything you need to do this, but you 
need to create the appropriate scripts for your server and your app.

If Dabo can do all this, it could be a great solution to all those
	Of course, we're still pretty early in development; we have 0.3 
scheduled to be released in the first week of January. But we do have 
our sights set pretty high.

 ___/
/
   __/
  /
 /
 Ed Leafe
 http://leafe.com/
 http://dabodev.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: More elegant way to cwd?

2004-12-28 Thread Peter Hansen
Kamilche wrote:
For library modules there are already other and more elegant means.
Well, I want to make a script execute without error regardless of where 
the current working directory is, and without having to make the user 
modify their PYTHONPATH variable or install something in site-packages.
If you are talking about just a script, then this of course
works out of the box without doing anything special.  You just
run the script and it works.
If, on the other hand, the script requires access to certain
shared *other* modules, then no, if you don't tell the script
where to find those other modules, and they are not in the same
folder as the script itself, then you can't do this.  You do
have to tell the Python where to find things... I'm unclear
what your situation is, that you have shared modules that you
want to use in various other scripts, and yet you have some
strange restriction preventing you from telling Python where
those are to be found except with custom code written in each
script that will use the modules.
Even if that really describes your (very bizarre, IMHO) situation,
the least you could do is write the aforementioned code in a
nice subroutine that you just cut and paste into each module,
then call elegantly.  It's code reuse, even if it's the most
rudimentary sort of reuse.
Is there a way to let the user just 'drag the folder' anywhere on their 
hard drive, and have it work, without having to modify any special 
system variables?
Not sure exactly what you are looking for.  I certain have folders
of Python scripts that I can just drag here or there and have them
work.  When they need to use common library files, however, I take
a moment to set that up ahead of time, using .pth files if I can't
or won't install them in site-packages.
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyUnitPerf

2004-12-28 Thread Roy Smith
Grig [EMAIL PROTECTED] wrote:
 Problem with porting patterns/api's from java straight to python is
 that most of the outcome feels unpythonic. I'll not go about my own
 feelings python vs. java here now, but I just want to point out that
 there's already a rather large core of hard-python users who refuse to
 use pyUnit because of this,

I'm curious what people find un-pythonic about PyUnit?  I've used it, 
and while some parts of it seem a little over-complex to me, I don't see 
anything about it which is inherently un-pythonic.  Is this just a case 
of Not Invented Here?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Other notes

2004-12-28 Thread Doug Holton
[EMAIL PROTECTED] wrote:
for i in 1..12: pass
for c in a..z: pass

 @infix
 def interval(x, y): return range(x, y+1) # 2 parameters needed
 assert 5 interval 9 == interval(5,9)

 10) There can be something in the middle between the def statement and
 the lambda.
These will likely not appear in CPython standard, but Livelogix runs on 
top of the CPython VM and supports .. sequences and custom infix 
operators: http://logix.livelogix.com/tutorial/5-Standard-Logix.html

11) This is just a wild idea for an alternative syntax to specify a
global variable inside a function. From:
def foo(x):
global y
y = y + 2
(the last two lines are indented)
To:
def foo(x): global.y = global.y + 2
Beside the global.y, maybe it can exist a syntax like upper.y or
caller.y that means the name y in the upper context. upper.upper.y etc.
This will also likely never appear in Python.  I like your idea though. 
 I implemented the same exact thing a couple months ago.  One 
difference though, you only need to type out the full global.y if you 
want to differentiate it from a local variable with the same name.


15) NetLogo is a kind of logo derived from StarLogo, implemented in
Java.
Show that this language is only partially a toy, and it can be useful
to understand and learn nonlinear dynamics of many systems.
If you want to do something like Netlogo but using Python instead of 
Logo, see:  http://repast.sourceforge.net/
You can script repast in jython or you can script repast.net.

Also, you might request the NetLogo and StarLogo developers to support 
Jython (in addition to Logo) scripting in their next version (which is 
already in development and supports 3D).
--
http://mail.python.org/mailman/listinfo/python-list


Re: consequences of not calling object.__init__?

2004-12-28 Thread Jorge Luiz Godoy Filho
Peter Hansen, Quarta 29 Dezembro 2004 01:04, wrote:

 Maybe there's no such pronouncement, but unless there is a
 clear statement somewhere (and I believe I've missed it, if
 there is) that reads one should *always* call __init__ on the
 superclass even if one is just subclassing object and not
 dealing with multiple inheritance situations, then I would
 submit that the majority of Python code written using new-style
 classes would be broken should what you suggest above ever
 actually happen...  starting with much of the code in the
 standard library (based on a quick glance at those modules
 whose contents match the re pattern class .*(object): .

Things are kind weird at this point, since there are too many things to
think about and to make a decision on what should be done and what is
recommended to be done...

Quoting from http://www.python.org/peps/pep-0008.html:


(...)
Designing for inheritance
(...)
  Also decide whether your attributes should be private or not.
  The difference between private and non-public is that the former
  will never be useful for a derived class, while the latter might
  be.  Yes, you should design your classes with inheritence in
  mind!
(...)


So, I don't really know which is correct: to always call the constructor of
the parent class or just do that when it is needed by design... 

I think that based on the above quotation from PEP-0008 code in the standard
library should be calling the parent class constructor.  But then, I'm one
of the people who never do that :-)

-- 
Godoy. [EMAIL PROTECTED]

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


Re: pyUnitPerf

2004-12-28 Thread Mike Thompson
Roy Smith wrote:
Grig [EMAIL PROTECTED] wrote:
Problem with porting patterns/api's from java straight to python is
that most of the outcome feels unpythonic. I'll not go about my own
feelings python vs. java here now, but I just want to point out that
there's already a rather large core of hard-python users who refuse to
use pyUnit because of this,

I'm curious what people find un-pythonic about PyUnit?  I've used it, 
and while some parts of it seem a little over-complex to me, I don't see 
anything about it which is inherently un-pythonic.  Is this just a case 
of Not Invented Here?
I've seen 'py.test' proposed as as a more pythonic unit test framework. 
So its design may provide you with some clues.  It can be found at:

http://codespeak.net/py/current/doc/test.html#starting-point-py-test-command-line-tool
As far as I can see, the defining feature of py.test is the simplicity 
of the API.  Its impressively absent.

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


Re: getattr() woes

2004-12-28 Thread Aahz
In article [EMAIL PROTECTED],
Thomas Rast  [EMAIL PROTECTED] wrote:

I've found out about a fundamental problem of attribute lookup, the
hard way.

Maybe.

asyncore.py uses the following code:

class dispatcher:
# ...
def __getattr__(self, attr):
return getattr(self.socket, attr)

Now suppose that I'm asking for some attribute not provided by
dispatcher: The lookup mechanism will apparently try to find it
directly and fail, generating an AttributeError; next it will call
__getattr__ to find the attribute.  So far, no problems.

But I used a property much like this:

 import asyncore
 class Peer(asyncore.dispatcher):
... def _get_foo(self):
... # caused by a bug, several stack levels deeper
... raise AttributeError('hidden!')
... foo = property(_get_foo)
...

You're not supposed to use properties with classic classes.
-- 
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: Other notes

2004-12-28 Thread Andrew Dalke
bearophileHUGS:
[on Python's O(n) list insertion/deletion) at any place other than tail
 (My hypothesis: to keep list implementation a bit simpler, to avoid
 wasting memory for the head buffer, and to keep them a little faster,
 avoiding the use of the skip index S).

Add its relative infrequent need.

 2) I usually prefer explicit verbose syntax, instead of cryptic symbols
 (like decorator syntax), but I like the infix Pascal syntax .. to
 specify a closed interval (a tuple?) of integers or letters
 
 assert 1..9 == tuple(range(1,10))
 for i in 1..12: pass
 for c in a..z: pass

It's been proposed several times.  I thought there was a PEP
but I can't find it.  One problem with it; what does

  for x in 1 .. a:

do?  (BTW, it needs to be 1 .. 12 not 1..12 because 1. will be
interpreted as the floating point value 1.0.)

What does
  a = MyClass()
  b = AnotherClass()
  for x in a .. b:
print x

do?  That is, what's the generic protocol?  In Pascal it
works because you also specify the type and Pascal has
an incr while Python doesn't.

 3) I think it can be useful a way to define infix functions, like this
 imaginary decorator syntax:
 
 @infix
 def interval(x, y): return range(x, y+1) # 2 parameters needed
 
 This may allow:
 assert 5 interval 9 == interval(5,9)

Maybe you could give an example of when you need this in
real life?

What does

  1 + 2 * 3 interval 9 / 3 - 7

do?  That is, what's the precedence?  Does this only work
for binary or is there a way to allow unary or other
n-ary (including 0-ary?) functions?


 4) The printf-style formatting is powerful, but I still think it's
 quite complex for usual purposes, and I usually have to look its syntax
 in the docs. I think the Pascal syntax is nice and simpler to remember
 (especially for someone with a little Pascal/Delphi experience ^_^),

But to someone with C experience or any language which derives
its formatting string from C, Python's is easier to understand than
your Pascal one.

A Python view is that there should be only one obvious way to do
a task.  Supporting both C and Pascal style format strings breaks
that.  Then again, having both the old % and the new PEP 292 string
templates means there's already two different ways to do string
formatting.

 For example this Delphi program:
  ...
 const a = -12345.67890;
  ...
 writeln(a:4:20);
  ...
 Gives:
  ...
 -12345.6789
Python says that's 

 %.20f % -12345.67890
'-12345.678979453457'

I don't think Pascal is IEEE enough.

note also that the Pascal-style formatting strings are less
capable than Python's, though few people use features like

 % 2.3f % -12.34
'-12.340'
 % 2.3f % 12.34
' 12.340'


 5) From the docs about round:
  ...
 But to avoid a bias toward rounding up there is another way do this:

There are even more ways than that.  See
  http://www.python.org/peps/pep-0327.html#rounding-algorithms

The solution chosen was not to change 'round' but to provide
a new data type -- Decimal.  This is in Python 2.4.

 6) map( function, list, ...) applies function to every item of list and
 return a list of the results. If list is a nested data structure, map
 applies function to just the upper level objects.
 In Mathematica there is another parameter to specify the level of the
 apply.
  ..
 I think this semantic can be extended:

A real-life example would also be helpful here.

What does
  map(len, Blah, level = 200)
return?

In general, most people prefer to not use map and instead
use list comprehensions and (with 2.4) generator comprehensions.


 level=0 means that the map is performed up to the leaves (0 means
 infinitum, this isn't nice, but it can be useful because I think Python
 doesn't contain a built-in Infinite).

You need to learn more about the Pythonic way of thinking
of things.  The usual solution for this is to have level = None.

 7) Maybe it can be useful to extended the reload(module) semantic:
 reload(module [, recurse=False])
 If recurse=True it reloads the module and recursively all the modules
 that it imports.

It isn't that simple.  Reloading modules isn't sufficient.
Consider

import spam
a = spam.Eggs()
reload(spam)
print isinstance(a, spam.Eggs)

This will print False because a contains a reference to
the old Eggs which contains a reference to the old spam module.

As I recall, Twisted has some super-reload code that may be
what you want.  See
  http://twistedmatrix.com/documents/current/api/twisted.python.rebuild.html

 8) Why reload is a function and import is a statement? (So why isn't
 reload a statement too, or both functions?)

import uses the underlying __import__ function.

Consider using the __import__ function directly

math = __import__(math)

The double use of the name math is annoying and error prone.

It's more complicated with module hierarchies.

 xml = __import__(xml.sax.handler)
 xml.sax.handler
module 'xml.sax.handler' from '/sw/lib/python2.3/xml/sax/handler.pyc'
 xml.sax.saxutils
Traceback (most recent call last):
  File 

Re: Other notes

2004-12-28 Thread Paul Rubin
Andrew Dalke [EMAIL PROTECTED] writes:
 What does
   a = MyClass()
   b = AnotherClass()
   for x in a .. b:
 print x
 
 do?  That is, what's the generic protocol?  

.. just becomes an operator like + or whatever, which you can define
in your class definition:

class MyClass:
   def __dotdot__(self, other):
  return xrange(self.whatsit(), other.whatsit())

The .. operation is required to return an iterator.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Other notes

2004-12-28 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
4) The printf-style formatting is powerful, but I still think it's
quite complex for usual purposes, and I usually have to look its syntax
in the docs. I think the Pascal syntax is nice and simpler to remember
(especially for someone with a little Pascal/Delphi experience ^_^), it
uses two : to format the floating point numbers (the second :number
is optional). For example this Delphi program:
{$APPTYPE CONSOLE}
const a = -12345.67890;
begin
writeln(a);
writeln(a:2:0);
writeln(a:4:2);
writeln(a:4:20);
writeln(a:12:2);
end.
Gives:
-1.2345678900E+0004
-12346
-12345.68
-12345.6789
-12345.68
(The last line starts with 3 spaces)
Even after looking at your example, I have no idea what the two numbers 
on each side of the :'s do.  The last number appears to be the number of 
decimal places to round to, but I don't know what the first number does.

Since I can't figure it out intuitively (even with examples), I don't 
think this syntax is any less inscrutable than '%width.decimalsf'. 
My suspicion is that you're just biased by your previous use of Pascal. 
 (Note that I never used Pascal or enough C to use string formatting 
before I used Python, so I'm less biased than others may be in this 
situation.)

6) map( function, list, ...) applies function to every item of list and
return a list of the results. If list is a nested data structure, map
applies function to just the upper level objects.
In Mathematica there is another parameter to specify the level of the
apply.
So:
map(str, [[1,[2]], 3])
==
['[1, [2]]', '3']
With a hypothetical level (default level = 1, it gives the normal
Python map):
map(str, [[1,[2]], 3], level=1)
==
['[1, [2]]', '3']
map(str, [[1,[2]], 3], level=2)
==
['1', '[2]', '3']
I think this semantic can be extended:
level=0 means that the map is performed up to the leaves (0 means
infinitum, this isn't nice, but it can be useful because I think Python
doesn't contain a built-in Infinite).
level=-1 means that the map is performed to the level just before the
leaves.
Level=-n means that the map is performed n levels before the leaves.
This packs two things into map -- the true mapping behavior (applying a 
function to a list) and the flattening of a list.  Why don't you lobby 
for a builtin flatten instead?  (Also, Google for flatten in the 
python-list -- you should find a recent thread about it.)

10) There can be something in the middle between the def statement and
the lambda. For example it can be called fun (or it can be called
def still). With it maybe both def and lambdas aren't necessary
anymore. Examples:
cube = fun x:
return x**3
(the last line is indented)
sorted(data, fun x,y: return x-y)
(Probably now it's almost impossible to modify this in the language.)
Google the python-list for 'anonymous function' or 'anyonymous def' and 
you'll find a ton of discussion about this kind of thing.  I'll note 
only that your first example gains nothing over

def cube(x):
return x**3
and that your second example gains nothing over
sorted(data, lambda x, y: return x-y)
or
sorted(data, operator.sub)

11) This is just a wild idea for an alternative syntax to specify a
global variable inside a function. From:
def foo(x):
global y
y = y + 2
(the last two lines are indented)
To:
def foo(x): global.y = global.y + 2
Well, you can do:
def foo(x):
globals()['y'] = globals()['y'] + 2
Not exactly the same syntax, but pretty close.

13) In Mathematica language the = has the same meaning of Python, but
:= is different:
lhs := rhs assigns rhs to be the delayed value of lhs. rhs is
maintained in an unevaluated form. When lhs appears, it is replaced by
rhs, evaluated afresh each time.
I don't know if this can be useful...
You can almost get this behavior with lambdas, e.g.:
   x = lambda: delayed_expression()
then you can get a new instance of the expression by simply doing:
   new_instance = x()
I know this isn't exactly what you're asking for, but this is one 
current possibility that does something similar.  You might also look at:

http://www.python.org/peps/pep-0312.html
which suggests a simpler syntax for this kind of usage.
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Using python to deploy software

2004-12-28 Thread secun
Has anyone used python to deploy (non-python) software on a Windows
network?

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


Re: Other notes

2004-12-28 Thread Steven Bethard
Andrew Dalke wrote:
I must say it's getting pretty annoying to say things like
when would this be useful? and have you read the documentation?
for your statements.
I'll second that.  Please, Bearophile, do us the courtesy of checking
(1) Google groups archive of the mailing list:
http://groups-beta.google.com/group/comp.lang.python
and
(2) The Python Enhancement Proposals:
http://www.python.org/peps/
before posting another such set of questions.  While most of the people 
on this list are nice enough to answer your questions anyway, the 
answers are already out there for at least half of your questions, if 
you would do us the courtesy of checking first.

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


Re: getattr() woes

2004-12-28 Thread David M. Cooke
[EMAIL PROTECTED] (Aahz) writes:

 In article [EMAIL PROTECTED],
 Thomas Rast  [EMAIL PROTECTED] wrote:

class dispatcher:
# ...
def __getattr__(self, attr):
return getattr(self.socket, attr)

 import asyncore
 class Peer(asyncore.dispatcher):
... def _get_foo(self):
... # caused by a bug, several stack levels deeper
... raise AttributeError('hidden!')
... foo = property(_get_foo)
...

 You're not supposed to use properties with classic classes.

Even if dispatcher was a new-style class, you still get the same
behaviour (or misbehaviour) -- Peer().foo still raises AttributeError
with the wrong message.

A simple workaround is to put a try ... except AttributeError block in
his _get_foo(), which would re-raise with a different error that
wouldn't be caught by getattr. You could even write a property
replacement for that:

 class HiddenAttributeError(Exception):
... pass
 def robustprop(fget):
... def wrapped_fget(self):
... try:
... return fget(self)
... except AttributeError, e:
... raise HiddenAttributeError(*e.args)
... return property(fget=wrapped_fget)

Ideally, I think the better way is if getattr, when raising
AttributeError, somehow reused the old traceback (which would point
out the original problem). I don't know how to do that, though.

-- 
||\/|
/--\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca
-- 
http://mail.python.org/mailman/listinfo/python-list


Why tuples use parentheses ()'s instead of something else like 's?

2004-12-28 Thread [EMAIL PROTECTED]
Tuples are defined with regards to parentheses ()'s as everyone knows.

This causes confusion for 1 item tuples since (5) can be interpreted
as a tuple OR as the number 5 in a mathematical expression
such as x = (5) * (4+6).

Wouldn't it have been better to define tuples with 's or {}'s or
something else to avoid this confusion??

Perhaps ()'s are a good idea for some other reason I don't know?

Please enlighten me as I really want to know.
Chris

P.S. I love Python!

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


Re: Using python to deploy software

2004-12-28 Thread Anand
I haven't but one of my friends have used Pyro (Python Remote Objects)
to do so.

You basically need to write a custom Pyro server and run it on a
central machine. Your pyro clients can be installed on the machines
where the software need to be installed.

For more details and similar ideas refer the project page of pyro at
http://pyro.sourceforge.net/projects.html .

-Anand

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


Re: Why tuples use parentheses ()'s instead of something else like 's?

2004-12-28 Thread Hans Nowak
[EMAIL PROTECTED] wrote:
Tuples are defined with regards to parentheses ()'s as everyone knows.
This causes confusion for 1 item tuples since (5) can be interpreted
as a tuple OR as the number 5 in a mathematical expression
such as x = (5) * (4+6).
No, (5) is always the number 5.  To make a one-element tuple, use (5,).
Wouldn't it have been better to define tuples with 's or {}'s or
something else to avoid this confusion??
Perhaps ()'s are a good idea for some other reason I don't know?
Actually, for non-empty tuples, the parentheses aren't really necessary, 
unless code is ambiguous.

 x = 1, 2, 3
 x
(1, 2, 3)
 y = 5,
 y
(5,)
but:
 print 8, 9  # not a tuple
8 9
 print (8, 9)
(8, 9)
HTH,
--
Hans Nowak
http://zephyrfalcon.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why tuples use parentheses ()'s instead of something else like 's?

2004-12-28 Thread Leif K-Brooks
[EMAIL PROTECTED] wrote:
Wouldn't it have been better to define tuples with 's or {}'s or
something else to avoid this confusion??
The way I see it, tuples are just a way of having a function return 
multiple values at once. When you think of them that way, you don't even 
need parenthesis:

def foo():
if we_found_stuff:
return 200, 'long and boring result'
else:
return 404, 'nothing found'
status_code, body = foo()
If foo() only needed to return one value, it would do so in the normal 
way, and you wouldn't need to worry about 1-tuples.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why tuples use parentheses ()'s instead of something else like 's?

2004-12-28 Thread Marius Bernklev
* [EMAIL PROTECTED]

 Perhaps ()'s are a good idea for some other reason I don't know?

One-element tuples are written as (4,).



-- 
Marius Bernklev

URL: http://www.ping.uio.no/~mariube/ 

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


Re: Python on Linux

2004-12-28 Thread Tim Roberts
Austin [EMAIL PROTECTED] wrote:

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?

You don't want to uninstall the old version.  Red Hat installs packages
that are needed for its configuration scripts.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza  Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Other notes

2004-12-28 Thread Andrew Dalke
Paul Rubin wrote:
 .. just becomes an operator like + or whatever, which you can define
 in your class definition:
 
 class MyClass:
def __dotdot__(self, other):
   return xrange(self.whatsit(), other.whatsit())
 
 The .. operation is required to return an iterator.

Ahh, I see.

This should be put into a PEP.  Some obvious questions:
  - .. or ... ?  The latter is already available for
  use in slices

  - If ... should the name be __ellipsis__?  If ..
  should the name be __range___?

  - Should range(x, y) first attempt x.__range__(y)?

  - Can it be used outside of a for statement?  Ie, does
   x = a ... b
return a generic iterator?  Almost certainly as that
fits in nicely with the existing 'for' syntax.

  - What's the precedence?  Given
  x = a .. b .. c
  x = 1 + 2 .. 5 * 3
  x = 1 ** 5 .. 4 ** 2
 etc., what is meant?  Most likely .. should have the
 lowest precedence, evaluated left to right.

  - is there an __rdotdot__?

  - any way to specify use the normal beginning?  Like
 for x in .. 5:  # same as 0 .. 5
  -or (the oft rejected)-
 for x in 5:

  - any way to specify ad infinitum?  Like
  for x in 0 .. Infinity:
-or-
  for x in 0 ... :

  - does for x in 10 .. 0 the same as xrange(10,0) (what
 you propose) or xrange(10, 0, -1)?

  - do strings work for len(s)  1?  Eg, A000 .. A999?

  - What do you think of (assuming the use of ...)
  for x in 0.100:?

  - What's the advantage of .. over, say a function or
method?  That is, why does the new binary operator
prove so useful?  In one of my gedanken experiments
I considered getting the 10th through 20th prime
  for x in primes(10) .. primes(20):
but that seems clumsier than
  for x in primes_between(10, 20):
in part because it requires primes(10) to have some
meaning.  I suppose
  for x in primes(10) .. 20:
could also work though that should in my mind generate
primes up to the number 20 and not the 20th prime.
Note that primes(10) cannot return the 10th prime as
the value 29.

Andrew
[EMAIL PROTECTED]

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


  1   2   >