T3 on GAE

2008-12-08 Thread Massimo Di Pierro


 http://web2py.appspot.com/t3/default/wiki/main(there is a  
video tutorial)


T3 version 0.2 is out. Now you can develop for GAE on GAE and it  
could not get any easier.


T3 is a development platform (built on web2py) that works like a WIKI  
and it lets you embed python code and components in wiki pages.  
Components include CRUD forms, attachments, reviews, comments, google  
checkout buttons, charts, all web2py helpers, functions and  
validators, and any user defined function.


T3 lets you create models, procedures, and edit stylesheet using the  
web interface. Everything is stored in the database. Nothing on  
filesystem.


The entire platform runs everywhere python runs, including GAE.

Massimo

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

   Support the Python Software Foundation:
   http://www.python.org/psf/donations.html


[ANN] Leipzig Python User Group - Meeting, December 9, 2008, 08:00pm

2008-12-08 Thread Mike Müller

=== Leipzig Python User Group ===

We will meet on Tuesday, December 9 at 8:00 pm at the training
center of Python Academy in Leipzig, Germany
( http://www.python-academy.com/center/find.html ).

The topic is Generators in Python as unix-like pipelines.

Food and soft drinks are provided. Please send a short
confirmation mail to [EMAIL PROTECTED], so we can prepare
appropriately.

Everybody who uses Python, plans to do so or is interested in
learning more about the language is encouraged to participate.

While the meeting language will be mainly German, we will provide
English translation if needed.

Current information about the meetings are at
http://www.python-academy.com/user-group .

Mike



== Leipzig Python User Group ===

Wir treffen uns am Dienstag, 09.12.2008 um 20:00 Uhr
im Schulungszentrum der Python Academy in Leipzig
( http://www.python-academy.de/Schulungszentrum/anfahrt.html ).

Unser Thema ist Generatoren in Python als unixartige Pipelines.

Für das leibliche Wohl wird gesorgt. Eine Anmeldung unter
[EMAIL PROTECTED] wäre nett, damit wir genug Essen
besorgen können.

Willkommen ist jeder, der Interesse an Python hat, die Sprache
bereits nutzt oder nutzen möchte.

Aktuelle Informationen zu den Treffen sind unter
http://www.python-academy.de/User-Group zu finden.

Viele Grüße
Mike









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

   Support the Python Software Foundation:
   http://www.python.org/psf/donations.html


ANN: PyBindGen 0.10 released

2008-12-08 Thread Gustavo Carneiro
PyBindGen is a Python module that is geared to generating C/C++ code that
binds a C/C++ library for Python. It does so without extensive use of either
C++ templates or C pre-processor macros. It has modular handling of C/C++
types, and can be easily extended with Python plugins. The generated code is
almost as clean as what a human programmer would write.

It can be downloaded from:

http://code.google.com/p/pybindgen/

Bug reports should be filed here:

https://bugs.launchpad.net/pybindgen


=== pybindgen 0.10 ===

- New null_ok, default_value options for pointer-to-class parameters;

- Thread safety fixes;

- Map C++ operator() into Python's tp_call (__call__);

- Initial support for std containers (except mapping containers);

- Generate __copy__ methods for classes with copy constructor;

- Add 'wrapper registry' optional feature (off by default): allows
  C++ instances returned by pointer to be consistently wrapped
  always by the same Python wrapper, so that the 'is' operator can
  be used for identity testing;

- New C type expression parser, is_const not longer needed for
  parameter types, just put const in the type string as
  appropriate;

- Sort the declarations returned by (py)gccxml.  If generating
  python script files from gccxml scanning, now the output file
  becomes more stable and less prone to move declarations up and
  down with different people scanning and the output file is under
  version control;

- Map binary comparison operators ( = == = ) from C++ to Python;

- Map some binary numeric operators (+ - * /) from C++ to Python;

- Allow installation of pybindgen even if no C/C++ compiler is detected;

- Fix compatibility with older Python versions (tested with 2.3, 2.4,
and 2.5)

-- 
Gustavo J. A. M. Carneiro
INESC Porto, Telecommunications and Multimedia Unit
The universe is always one step beyond logic. -- Frank Herbert
--
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


SQLObject 0.9.9

2008-12-08 Thread Oleg Broytmann
Hello!

I'm pleased to announce version 0.9.10, a minor bugfix release of 0.9 branch
of SQLObject.


What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite,
Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB).


Where is SQLObject
==

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://cheeseshop.python.org/pypi/SQLObject/0.9.9

News and changes:
http://sqlobject.org/News.html


What's New
==

News since 0.9.8


* Backported from the trunk: under MySQL use the connection's dbEncoding
  instead of ascii, when converting a unicode value from python to database
  for a StringCol.

* Fixed createSQL constrains generation under MySQL when the table's name
  includes the database's name (contains a dot).

For a more complete list, please see the news:
http://sqlobject.org/News.html

Oleg.
-- 
 Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED]
   Programmers don't die, they just GOSUB without RETURN.
--
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


SQLObject 0.10.4

2008-12-08 Thread Oleg Broytmann
Hello!

I'm pleased to announce version 0.10.4, a minor bugfix release of 0.10 branch
of SQLObject.


What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite,
Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB).


Where is SQLObject
==

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://cheeseshop.python.org/pypi/SQLObject/0.10.4

News and changes:
http://sqlobject.org/News.html


What's New
==

News since 0.10.3
-

* Fixed createSQL constrains generation under MySQL when the table's name
  includes the database's name (contains a dot).

For a more complete list, please see the news:
http://sqlobject.org/News.html

Oleg.
-- 
 Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED]
   Programmers don't die, they just GOSUB without RETURN.
--
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


dBase III files and Visual Foxpro 6 files

2008-12-08 Thread Ethan Furman

Greetings All!

I nearly have support complete for dBase III dbf/dbt files -- just 
wrapping up support for dates.  The null value has been a hindrance for 
awhile but I nearly have that solved as well.


For any who know of a cool dbf module already in existence for dBase III 
and Visual Foxpro -- where were you six months ago when I was searching? 
 ;)  Seriously, though, this has been a great learning experience for me.


As I said -- dbf/dbt files are 99% ready.  idx files -- no support:  for 
my purposes I just don't need them.  I've found no problem in loading 
tables up to 300,000 records with 50 fields per record, and re-ordering 
them on the fly in memory.


However, after putting much effort into this code, and wanting it to be 
useful to others in the community, are there others who work with dbf 
files that would need idx/cdx support?  Or tables so large they won't 
fit comfortably into memory?


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


Re: Rich Comparisons Gotcha

2008-12-08 Thread James Stroud

Robert Kern wrote:

James Stroud wrote:
I think it skips straight to __eq__ if the element is not the first in 
the list.


No, it doesn't skip straight to __eq__(). y is 1 returns False, so 
(y==1) is checked. When y is a numpy array, this returns an array of 
bools. list.__contains__() tries to convert this array to a bool and 
ndarray.__nonzero__() raises the exception.


list.__contains__() checks is then __eq__() for each element before 
moving on to the next element. It does not try is for all elements, 
then try __eq__() for all elements.


Ok. Thanks for the explanation.


  That no one acknowledges this makes me feel like a conspiracy
  is afoot.

I don't know what you think I'm not acknowledging.


Sorry. That was a failed attempt at humor.

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


gzip.GzipFile (was Re: Don't you just love writing this sort of thing :))

2008-12-08 Thread Jorgen Grahn
On Sat, 06 Dec 2008 10:01:10 +, Arnaud Delobelle [EMAIL PROTECTED] wrote:

...
 Why use (open, gzp.GzipFile)[Entry.endswith(.gz)] when we have had
 contitional expressions for a few years now?  Instead, you can write

 (gzip.GzipFile if entry.endswidth(.gz) else open).

 I think it will be faster (as it doesn't require the construction of a
 tuple and then the retrieval of one of its elements) and clearer.

Even clearer would be if gzip.Gzipfile could (optionally) read
non-gzipped files and file-like objects, like the gzip Unix commands
zcat -f, zgrep and so on.

Also, making a decision based on the .gz part of the name isn't
always correct -- you miss files named foo.Z and similar.

/Jorgen

-- 
  // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu
\X/ snipabacken.se  R'lyeh wgah'nagl fhtagn!
--
http://mail.python.org/mailman/listinfo/python-list


Re: EBCDIC -- ASCII

2008-12-08 Thread martinjamesevans
On Dec 5, 2:13 pm, Michael Ströder [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  On Dec 4, 4:45 pm, Michael Ströder [EMAIL PROTECTED] wrote:
  [EMAIL PROTECTED] wrote:
  I'm having a problem trying to use the codecs package to aid me in
  converting some bytes from EBCDIC into ASCII.
  Which EBCDIC variant?

  sEBCDIC = unicode(sSource, 'cp500', 'ignore')
  Are you sure CP500 is the EBCDIC variant for the language you want?

 http://www.ietf.org/rfc/rfc1345.txtlistsit as:

     charset IBM500
     rem source: IBM NLS RM Vol2 SE09-8002-01, March 1990
     alias CP500
     alias ebcdic-cp-be
     alias ebcdic-cp-ch

  Obviously I could just knock up a 255 character lookup table and do it
  myself, I was just trying to be a little more Pythonic and use that
  built in table.
  It's pythonic to implement a Unicode codec for unknown character tables.
  I've put these two on my web site:

 http://www.stroeder.com/pylib/encodings/ebcdicatde.pyhttp://www.stroe...ebcdicatde)

  Thanks for the tables, ebcdicatde.py does look more suitable.

  My problem appears to be that my source is a byte string. In a
  nutshell I need \x81\x82\x83\xf1\xf2\xf3 to become abc123 in a
  byte string.

 Python 2.5.2 (r252:60911, Aug  1 2008, 00:43:38)
   import ebcdicatde
   \x81\x82\x83\xf1\xf2\xf3.decode('ebcdic-at-de').encode('ascii')
 'abc123'
  

 Ciao, Michael.- Hide quoted text -

 - Show quoted text -


Many thanks for all your posts!
Just what I needed.
--
http://mail.python.org/mailman/listinfo/python-list


Re: var or inout parm?

2008-12-08 Thread Bruno Desthuilliers

Colin J. Williams a écrit :

[EMAIL PROTECTED] wrote:

How can I make a var parm, where the called function can modify
the value of the parameter in the caller?

def f(x):
x = x + 1

n = 1
f(n)
# n should now be 2

Many TIA!!
Mark




Why not run it and see?

Your function returns None.

The function in effect takes a copy of n.


Nope, it takes the object bound to global name 'n'.

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


Re: Don't you just love writing this sort of thing :)

2008-12-08 Thread Gabriel Genellina

En Sun, 07 Dec 2008 05:34:39 -0200, Lawrence D'Oliveiro
[EMAIL PROTECTED] escribió:


In message [EMAIL PROTECTED], Arnaud Delobelle wrote:


  * you give the impression of being arrogant;


Oddly enough, I wasn't the one who started by criticizing other people's
code. I have no ego about my code; I gladly accept criticisms. But  
perhaps
some other people are not so thick-skinned and do not like getting as  
they

give...


May I ask then *why* did you chose to post your code fragment? Did I miss
something?

--
Gabriel Genellina

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


Re: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL?

2008-12-08 Thread alex23
On Dec 8, 2:26 pm, illume [EMAIL PROTECTED] wrote:
 pygame is simpler to learn, since it doesn't require you to know how
 to create classes or functions.

I'm not sure if I'd be quick to tout that as an advantage... :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get a beep, OS independent ?

2008-12-08 Thread Gabriel Genellina

En Sun, 07 Dec 2008 23:34:17 -0200, Joe Strout [EMAIL PROTECTED] escribió:


On Dec 7, 2008, at 4:43 PM, Steven D'Aprano wrote:


Of course, if you're volunteering to write such a standard system beep
for Python, I for one would be grateful.


I am.  But where should I put it?  Assuming we don't want to wait for  
the (understandably) lengthy and contentious process required to add  
something to the Python system libraries, where would be the next best  
place for this sort of simple OS abstraction layer?


The cookbook? http://www.activestate.com/ASPN/Python/Cookbook/
If you can make it run on several different architectures you could upload
a patch as a feature request to http://bugs.python.org/

--
Gabriel Genellina

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


Re: ftp retrlines with re...

2008-12-08 Thread Gabriel Genellina

En Fri, 05 Dec 2008 12:51:58 -0200, [EMAIL PROTECTED]
[EMAIL PROTECTED] escribió:


Ive been working on an application quite some time now and i wanted to
include something to let the user load a new version. i therefore
tried to include this here:


Too much code, unclear question... please post again, shortening code to  
the minimum necesary to show the problem. And tell us *what* is the  
problem, what did you expect to happen, what actually happened...


--
Gabriel Genellina

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


Re: mod_python and files directory

2008-12-08 Thread Gabriel Genellina

En Sat, 06 Dec 2008 09:26:40 -0200, mete [EMAIL PROTECTED] escribió:

but i want to take it somewhere else...i want to it work some other path  
in

other system.


os.path.dirname(os.path.abspath(__file__))
returns the directory where the current file resides. Execute it early in
your code.

--
Gabriel Genellina

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


Re: var or inout parm?

2008-12-08 Thread Chris Rebert
On Mon, Dec 8, 2008 at 12:26 AM, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
 Colin J. Williams a écrit :

 [EMAIL PROTECTED] wrote:

 How can I make a var parm, where the called function can modify
 the value of the parameter in the caller?

 def f(x):
x = x + 1

 n = 1
 f(n)
 # n should now be 2

 Many TIA!!
 Mark



 Why not run it and see?

 Your function returns None.

 The function in effect takes a copy of n.

 Nope, it takes the object bound to global name 'n'.

See Also: the earlier heated debate thread over what evaluation
strategy Python uses (Survey says!: call-by-object).

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com


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

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


Re: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL?

2008-12-08 Thread James Mills
On Mon, Dec 8, 2008 at 6:31 PM, alex23 [EMAIL PROTECTED] wrote:
 On Dec 8, 2:26 pm, illume [EMAIL PROTECTED] wrote:
 pygame is simpler to learn, since it doesn't require you to know how
 to create classes or functions.

 I'm not sure if I'd be quick to tout that as an advantage... :)

Neither would i. Classes and Objects
and good OOP practises can benefit
a pygame game just as well as any
other Python app. What's more using
and learning Python's OO semantics
and syntax is really really easy :)

--JamesMills

-- 
--
-- Problems are solved by method
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get a beep, OS independent ?

2008-12-08 Thread Duncan Booth
Joe Strout [EMAIL PROTECTED] wrote:

 But invoking the standard system beep is such a basic function that it  
 ought to be easier than this.  I'm pretty sure it's a single OS call  
 on all platforms.  On OS X, for example, it's
 
void NSBeep(void);
 
 declared in NSGraphics.h.  I'm sure it's something similarly simple on  
 other platforms.

I think what you're missing is a definition for 'the standard system'. If 
I'm logged in to one of my servers in a large datacentre then I don't what 
that system to beep as that would be pretty useless. I want the system I'm 
logged in with to do the beeping.

For some systems and some types of login (e.g. Microsoft's Remote Desktop) 
then remoting the sound output isn't a problem, but I might just be logged 
in with SSH and in that case the only option available is to send some 
escape sequence to the user's terminal. Traditionally generation of escape 
sequences for a user's terminal is something done by the application, not a 
function of the operating system.

I think that's why you'll find there will be a variety of ways to generate 
beeps, squeaks and squawks if you are using a gui (only as with all other 
gui functions there is no common ground between different systems), but 
nothing beyond '\a' for terminals.

-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL?

2008-12-08 Thread illume
On Dec 8, 7:31 pm, alex23 [EMAIL PROTECTED] wrote:
 On Dec 8, 2:26 pm, illume [EMAIL PROTECTED] wrote:

  pygame is simpler to learn, since it doesn't require you to know how
  to create classes or functions.

 I'm not sure if I'd be quick to tout that as an advantage... :)

Hi,

It's easier to teach only requiring *using* classes, and functions
than *creating* them.  This is important if it's being used to teach
programming - as you don't need to teach people two fairly large
concepts before you can do anything.

People are motivated by seeing results.  So it can be good to let
people do things without requiring much learning.  Anyone teaching
object oriented program will tell you that it's a hard concept to
present to people.  So if you can avoid teaching parts of OO, and a
bunch of other concepts at the same time, it's easier for people to
handle.

It's quite nice to be able to handle events without requiring
callbacks.  Everyone hates callbacks, but lots of people use them for
event systems.  However callbacks aren't needed at all for event
programming.  Instead you can get an event as an object and then
process it.

Callbacks for events made more sense in languages like smalltalk where
events and method calls were closely aligned concepts(method calls are
messages in smalltalk).  However in languages where you don't have
such a close conceptual alignment(such as python), making events
objects instead of method calls is much easier to understand.

Also python has very slow function calls, so avoiding using callbacks
is also faster.

Imagine using callbacks for files?  So you would have to subclass
file, and make a read_data method.  Then your class will call your
read data method when some data arrives.  Kind of annoying, and not
needed.

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


Re: gzip.GzipFile (was Re: Don't you just love writing this sort of thing :))

2008-12-08 Thread Bruno Desthuilliers

Jorgen Grahn a écrit :
(snip)


Also, making a decision based on the .gz part of the name isn't
always correct -- you miss files named foo.Z and similar.


.tgz anyone ?


/Jorgen


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


Re: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL?

2008-12-08 Thread alex23
On Dec 8, 7:18 pm, illume [EMAIL PROTECTED] wrote:
 It's easier to teach only requiring *using* classes, and functions
 than *creating* them.  This is important if it's being used to teach
 programming - as you don't need to teach people two fairly large
 concepts before you can do anything.

I'm just kind of aghast at the idea of teaching anyone how to
program games by using large, imperative chunks of code. I don't see
functions as being a fairly large concept at all, and utterly vital
to being able to write anything but the most basic 'hello world'
example code.

 Also python has very slow function calls, so avoiding using callbacks
 is also faster.

Wouldn't it be better to teach people the basics of coding -before-
setting out to optimise their code?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python now coming from Perl

2008-12-08 Thread Nick Craig-Wood
Bertilo Wennergren [EMAIL PROTECTED] wrote:
  I'm planning to start learning Python now, using Python 3000.
  I have no previous Python skills, but I now Perl pretty well.
  I'm also well experienced with JavaScript.
 
  Any pointers and tips how I should go about getting into
  Python?

Read Dive Into Python while following along with your keyboard.

( http://www.diveintopython.org/ free online or paper edition from
your favourite bookseller )

My favourite mistake when I made the transition was calling methods
without parentheses.  In perl it is common to call methods without
parentheses - in python this does absolutely nothing!  pychecker does
warn about it though.

  perl   - $object-method
  python - object.method()

-- 
Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: infering the number of args a function takes at runtime

2008-12-08 Thread sniffer
On Dec 8, 9:39 am, sniffer [EMAIL PROTECTED] wrote:
 hi all,
 i am a python newbie, in a project currently doing i need to find out
 the number of arguments that a function takes at runtime.? Is this
 possible ,if so how do i do this,i ve looked through the python
 documentation but couldnt find anything.any help will be great

 TIA

Thanks guys , i think this should work for me.btw as enquired i am
working o a mvc thingie where in need to call functions in a
controller,and pass the arguments as recieved from the end user so i
need to make sure that the number of arguments passed from the front
end are correct or not in the context of the function being called
--
http://mail.python.org/mailman/listinfo/python-list


Re: ftp retrlines with re...

2008-12-08 Thread Peter Otten
[EMAIL PROTECTED] wrote:

 filelist=server.retrlines('LIST')

This does not do what you think it does.

 help(ftplib.FTP.retrlines)

gives


Help on method retrlines in module ftplib:

retrlines(self, cmd, callback=None) unbound ftplib.FTP method
Retrieve data in line mode.
The argument is a RETR or LIST command.
The callback function (2nd argument) is called for each line,
with trailing CRLF stripped.  This creates a new port for you.
print_line() is the default callback.


I. e. you would need something like

lines = []
server.retrlines(LIST, lines.append)

to store the method's output in a variable instead of printing it to stdout.
But try

files = server.nlist()

instead which gives you a list of filenames. 

Peter

PS: Remember to take Gabriel's advice to heart for your next question.
--
http://mail.python.org/mailman/listinfo/python-list


Determining whether a variable is less/greater than a range.

2008-12-08 Thread [EMAIL PROTECTED]
Hi. I'm having another go at learning Python so I'll probably be
asking a few basic questions. Here is the first one.

a = list(range(10, 21)

b = 9

c = 21

How can I find out if b and c have values less or more than the values
in list a?

Thanks.


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


built-in functions as class attributes

2008-12-08 Thread Mark Dickinson
Here's a curiosity:  after

def my_hex(x):
return hex(x)

one might expect hex and my_hex to be interchangeable
in most situations.  But (with both Python 2.x and 3.x)
I get:

 def my_hex(x): return hex(x)
...
 class T(object): f = hex
...
 class T2(object): f = my_hex
...
 T().f(12345)
'0x3039'
 T2().f(12345)
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: my_hex() takes exactly 1 argument (2 given)
[36412 refs]

Anyone know what the precise rules that lead to this
behaviour are, or where they're documented?

Surprised'ly yours,

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


Re: Guido's new method definition idea

2008-12-08 Thread Lie Ryan
On Sun, 07 Dec 2008 18:27:21 +0100, Andreas Waldenburger wrote:

 On Sat, 6 Dec 2008 23:21:04 -0800 (PST) Lie [EMAIL PROTECTED] wrote:
 
 I think we have to test this on newbies. [snip]
 
 Now that's talking like a programmer!
 
 Ideas on how such a survey could be conducted? Anyone?
 
 
 If this dead horse is revived because of that reason, then I'd go with
 changing the error message to something that is less confusing to
 newbies[1].
 + googol
 
 
 I remember being tripped with the (thinking that python miscounted the
 number of argument) when I was new. This has the advantage of backward
 compatibility and no syntax change, just less misleading error message.
 
 [1] anything could work, but I like this one: (c is an instance of
 class C)
 if the code is: c.foo(...), Error: TypeError: c.foo() takes exactly 3
 argument
 while if the code is: C.foo(...), Error: C.foo() takes exactly 4
 arguments
 You can implement c.foo as a curried C.foo function, catch C.foo's
 TypeError exception then reraise it as c.foo exception.
 I'm not sure that I'd find that less confusing. Because a c.foo() *does*
 take four arguments, not three. It's just that the first one is implicit
 (Right?).

It's not implicit, we explicitly pass c (the object instance), although 
not in the argument list. So c.foo takes 3 arguments while C.foo takes 4 
arguments. 

In other words:
from functools import partial
c = C() - c.attr = partial(C.attr, c)

Note the error message I gave:
TypeError: c.foo() takes exactly 3 arguments
TypeError: C.foo() takes exactly 4 arguments

There are two differences there, not only one claims to accept three and 
the other 4 arguments, but also the capitalization of c/C. Here is a 
clearer example:

inst = cls()
TypeError: inst.foo() takes exactly 3 arguments
TypeError: cls.foo() takes exactly 4 arguments

for comparison, python's current (2.5) error message is:
TypeError: foo() takes exactly 4 arguments

in addition, with this proposal we'll know how foo is being called.

The following is a quick and dirty implementation of such error message.
Note: There are still some unresolved problems though:
1. instance.[func name] is hardcoded, as I don't know how to get the 
instance's name from the instance creation itself
2. Class Invoking from class gives TypeError: foo()... instead of 
TypeError: Class.foo()...
3. most definitely not to be used on real application

from types import MethodType
import re
errmess = re.compile(r'(.*?) (.*?) (\d*) (arguments?) \((\d*) given\)')
def usenewexc(obj):
def wrap(f):
def wrap_(*args, **kargs):
try:
print args, kargs
return f(*args, **kargs)
except TypeError, e:
re_mess = errmess.match(e.message)
fname = re_mess.group(1)
interm = re_mess.group(2) if re_mess.group(3) != '1' else 
'takes'
reqargs = int(re_mess.group(3)) - 1 if re_mess.group(3) !
= '1' else 'no'
argue_s = re_mess.group(4) if re_mess.group(3) != '1' 
else 'arguments'
givenargs = int(re_mess.group(5)) - 1
raise TypeError('%s.%s %s %s %s (%s given)' % 
('instance', fname, interm, reqargs, argue_s, givenargs))   
return wrap_
for attrname in dir(obj):
attr = obj.__getattribute__(attrname)
if type(attr) == MethodType:
obj.__setattr__(attrname, wrap(attr))
return obj

class A(object):
def foo(self):
print ''
pass
a = usenewexc(A())
A.foo(a, 2)


 How about:
 
 TypeError: c.foo() takes exactly 3 arguments in addition to the
 implicit instance reference.
 
 or
 
 TypeError: c.foo() takes exactly 4 arguments (5 given, including the
 implicit instance reference)
 
 ... or something less kludgy in that general direction. This would
 explain exactly what is wrong.
 
 /W
 
 --
 My real email address is constructed by swapping the domain with the
 recipient (local part).


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


Re: Determining whether a variable is less/greater than a range.

2008-12-08 Thread [EMAIL PROTECTED]
On Dec 8, 11:12 am, Tim Chase [EMAIL PROTECTED] wrote:
  a = list(range(10, 21))

  b = 9

  c = 21

  How can I find out if b and c have values less or more than the values
  in list a?

 Sounds like a good use for 2.5's addition of the any() and all()
 functions -- you don't mention whether you want your variable
 compared against *any* of the list items or *all* of the list
 items.  You also don't mention whether you want the comparison
 results, or just a single scalar.  Lastly, you omit the details
 of what happens if your target value (d below) falls within the
 range.  One of the following should do it for you:

     a = range(10,21)
     b = 9
     c = 21
     d = 15
     any(b  x for x in a)
    True
     all(b  x for x in a)
    True
     any(c  x for x in a)
    False
     any(d  x for x in a)
    True
     all(d  x for x in a)
    False
     any(c  x for x in a)
    True
     all(c  x for x in a)
    True
     any(d  x for x in a)
    True
     all(d  x for x in a)
    False

 If you just want the comparisons:

    y1 = [bx for x in a]
    y2 = [cx for x in a]
    y3 = [dx for x in a]
    z1 = [(bx, bx) for x in a]
    z2 = [(cx, cx) for x in a]
    z3 = [(dx, dx) for x in a]

 -tkc

Hi Tim. I'm just learning Python at the moment. All I was really
wanting was a True or False value which min and max give.

a = list(range(10, 21))

b = 9

c = 21

if b  min(a)
if c  max(a)

The any() and all() functions look useful so thanks for the tips.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mathematica 7 compares to other languages

2008-12-08 Thread Jon Harrop
Xah Lee wrote:
 The result and speed up of my code can be verified by anyone who has
 Mathematica.

You changed the scene that is being rendered = your speedup is bogus!

Trace the scene I originally gave and you will see that your program is no
faster than mine was.

-- 
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
http://www.ffconsultancy.com/?u
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to get a beep, OS independent ?

2008-12-08 Thread malkarouri
On 6 Dec, 23:40, Stef Mientki [EMAIL PROTECTED] wrote:
 hello,

 I want to give a small beep,

Just to add to the options here. Where ncurses work you can use:

python -c 'from curses import *;wrapper(lambda s:beep())'

To try it just enter the whole line above in the command line..

Regards,

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


Re: Mathematica 7 compares to other languages

2008-12-08 Thread Jon Harrop
Xah Lee wrote:
 For those interested in this Mathematica problem, i've now cleaned up
 the essay with additional comments here:
 
 • A Mathematica Optimization Problem
   http://xahlee.org/UnixResource_dir/writ/Mathematica_optimization.html

In that article you say:

 Further, if Intersect is made to take a flat sequence of argument as
 in “Intersect[o_, d_, lambda_, n_, c_, r_, s_]”, then pattern matching can
 be avoided by making it into a pure function “Function”. And when it is
 a “Function”, then Intersect or part of it may be compiled with Compile.
 When the code is compiled, the speed should be a order of magnitude
 faster. 

That is incorrect. Mathematica's Compile function cannot handle recursive
functions like Intersect. For example:

In[1]:= Compile[{n_, _Integer}, If[# == 0, 1, #0[[# n - 1]] #1] [n]]

During evaluation of In[1]:= Compile::fun: Compilation of
(If[#1==0,1,#0[[#1 n-1]] #1])[Compile`FunctionVariable$435] cannot
proceed. It is not possible to compile pure functions with arguments
that represent the function itself. 

-- 
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
http://www.ffconsultancy.com/?u
--
http://mail.python.org/mailman/listinfo/python-list


Re: A question about reference in Python.

2008-12-08 Thread James Mills
In case the OP is interested here is a more complete
implementation (others are welcome to comment):

http://codepad.org/drIhqb7Z

Enjoy :)

cheers
James

-- 
--
-- Problems are solved by method
--
http://mail.python.org/mailman/listinfo/python-list


Re: pytz and timezone specialists

2008-12-08 Thread manatlan
On 5 déc, 20:46, Ned Deily [EMAIL PROTECTED] wrote:
 In article
 [EMAIL PROTECTED],



  manatlan [EMAIL PROTECTED] wrote:
  Here is a really simple code :
  ---
  from datetime import datetime
  frompytzimport timezone

  tz=timezone(Europe/Paris)

  d=datetime(2008,12,12,19,00,00,tzinfo=tz)
  print d.isoformat()

  d=datetime.now(tz)
  print d.isoformat()
  ---
  when I run it, it displays (according current time ;-):

  2008-12-12T19:00:00+00:09
  2008-12-05T19:15:38.135467+01:00

  The Europe/Paris timezone is GMT+1 ... the second date seems to be
  right (+01:00 at the end)

  But why the first date ends with +00:09 ?!? it should be +01:00 ...
  no ?!
  Where's the bug ?!? (sure : it's me ;-) ... but i don't understand
  this simple thing)
  tz = timezone(Europe/Paris)
  d = tz.localize(datetime(2008,12,12,19,00,00))
  print d.isoformat()

 2008-12-12T19:00:00+01:00

 http://pytz.sourceforge.net/

 This library only supports two ways of building a localized time. The
 first is to use the .localize() method provided by thepytzlibrary.
 This is used to localize a naive datetime (datetime with no timezone
 information).  ... Unfortunately using the tzinfo argument of the
 standard datetime constructors ''does not work'' withpytzfor many
 timezones.

 --
  Ned Deily,
 [EMAIL PROTECTED]

now, I use :
d=datetime.now(tz).replace(2008,12,12,19,00,00)

and it works like expected ...

btw, thanks for your answer
--
http://mail.python.org/mailman/listinfo/python-list


Re: Public imports

2008-12-08 Thread Bruno Desthuilliers

Márcio Faustino a écrit :

Hi,

Does Python support public imports instead of the default private?


Python has no notion of public or private !-)


Something like D's public import (see http://www.digitalmars.com/d/
2.0/module.html)


Python imports don't work as D imports (as far as I can tell from the 
above link). The Python import statement binds imported name - whether 
the module object itself[1] or the explicitely[2] or implicitely[3] 
specified names from the module object - into the importing module's 
namespace.


[1] import some_module
[2] from some_module import some_name
[3] from some_module import *


IOW, if module_b imports module_a and module_c import module_a, module_a 
will be accessible in module_c as module_b.module_a. If module_b import 
name_x from module_a and module_c imports module_b, name_x will be 
accessible in module_c as module_b.name_x. Etc, etc


HTH



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


Re: Guido's new method definition idea

2008-12-08 Thread Bruno Desthuilliers

Philip Slate a écrit :

On Dec 7, 1:13 pm, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:


and friendlier to newbies.

I'd rather say more acceptable to java-brainwashed developpers.


And I'd rather say you're trolling, 


Almost, indeed. But not as much as you !-)
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie - merging xls files using xldt and xlwt

2008-12-08 Thread J Sutar
Hi,

I have been provided with the program below. Which sets out to merge
singlesheet excel files into one multisheet excel workbook.

Though it manages to merge multiple files into one workbook many of the
formats are not preserved. For example, what was originally 22.92% is
converted to 0.2292...

I was hoping if somebody could please help me understand how this can be
fixed. Ideally I would like to create a program which merges files whilst
keeping all formats (if at all possible).

###

Merge all xls files in a given directory into one multisheet xls file.
The sheets get the orginal file name, without the extension.
File names should not exceed 29 characters

import xlrd, xlwt
import glob, os.path
def merge_xls (in_dir, out_file=K:/Stats Jobs 2003/St0883 (CITB -
J33882)/3. Results/Excel/merged_output.xls):

xls_files   = glob.glob(in_dir + *.xls)
sheet_names = [os.path.basename(v)[:-4] for v in xls_files]
sheet_excl  = [os.path.basename(v)[:-4] for v in xls_files if
len(os.path.basename(v)[:-4])  29]
merged_book = xlwt.Workbook()

if in_dir[-1:] != /: in_dir = in_dir + /
xls_files.sort()
if xls_files:
for k, xls_file in enumerate(xls_files):
print --- Processing file %s % (xls_file)
if len (sheet_names[k]) = 29:
book = xlrd.open_workbook(xls_file)
if book.nsheets == 1:
ws= merged_book.add_sheet(sheet_names[k])
sheet = book.sheet_by_index(0)
for rx in range(sheet.nrows):
for cx in range(sheet.ncols):
ws.write(rx, cx, sheet.cell_value(rx, cx))
elif book.nsheets in range(2, 100):
for sheetx in range(book.nsheets):
sheet0n = sheet_names[k]+str(sheetx+1).zfill(2)
ws  = merged_book.add_sheet(sheet0n)
sheet   = book.sheet_by_index(sheetx)
for rx in range(sheet.nrows):
for cx in range(sheet.ncols):
ws.write(rx, cx, sheet.cell_value(rx, cx))
else:
print ERROR *** File %s has %s sheets (maximum is 99)
% (xls_file, book.nsheets)
raise
else:
print WARNING *** File name too long: %s.xls (maximum is
29 chars)  % (sheet_names[k])
print WARNING *** File %s.xls was skipped. %
(sheet_names[k])
merged_book.save(out_file)
print
print --- Merged xls file written to %s using the following source
files:  % (out_file)
for k, v in enumerate(sheet_names):
if len(v) = 29:
print \t, str(k+1).zfill(3), %s.xls % (v)
print
if sheet_excl:
print -- The following files were skipped because the file
name exceeds 29 characters: 
for k, v in enumerate(sheet_excl):
print \t, str(k+1).zfill(3), v
else:
print NOTE *** No xls files in %s. Nothing to do. % (in_dir)
merge_xls(in_dir=C:/temp/test merge xls/)
###


Many thanks in advance.

Jigs


2008/11/3 J Sutar [EMAIL PROTECTED]

 Mr Roskam,

 We have interacted before on the SPSS listserve, you have helped me out
 fair few times!

 I need a helping hand again, do you have the final solution to this
 problem, mergin xls from a given directory?

 Also where do I download the relevant modules from?

 Cheers
 Jigs

 2008/10/15 Albert-jan Roskam [EMAIL PROTECTED]

 Hi John,

 Thanks! Using a higher xlrd version did the trick! Regarding your other
 remarks:
 -yep, input files with multiple sheets don't work yet. I kinda repressed
 that ;-) Spss outputs only single-sheet xls files, but I agree it's nicer if
 the programs works in other cases too.
 -and no, I don't intend to use data fields. Wouldn't it be easier to
 convert those to string values if I ever came across them?

 Thanks again!
 Albert-Jan


 --- On Wed, 10/15/08, John Machin [EMAIL PROTECTED] wrote:

  From: John Machin [EMAIL PROTECTED]
  Subject: Re: newbie - merging xls files using xldt and xlwt
  To: python-list@python.org
  Date: Wednesday, October 15, 2008, 3:14 PM
   On Oct 15, 9:16 pm, Albert-jan Roskam
  [EMAIL PROTECTED] wrote:
   Hi,
  
   I wrote the program below to merge all xls files in a
  given directory into one multisheet xls file. It uses xlwt
  and xlrd. The xls files I use for input are generated by
  Spss. When I open and re-save the files in Excel, the
  program works, but when I use the xls files as they were
  created by Spss, the program returns an error message (see
  below). Some details: Python 2.4, xlwt version 0.7.0, xlrd
  version 0.5.2, Win NT.
  
   Any ideas?
 
  The version of xlrd that you are using is an antique. Go to
  http://pypi.python.org/pypi/xlrd and get the latest
  version. If that
  doesn't work, 

Re: Determining whether a variable is less/greater than a range.

2008-12-08 Thread [EMAIL PROTECTED]
Wow. Thanks Eric and Peter. Very helpful indeed.

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


Python and audio frequency analysis

2008-12-08 Thread manatlan
I'd like to make a kind of spectrum analyzer ...
Which should display bars according bands of frequencies ... in real
time...

Is anybody know an audio processing lib in python for that ?


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


Re: Determining whether a variable is less/greater than a range.

2008-12-08 Thread Tim Chase

a = list(range(10, 21))

b = 9

c = 21

How can I find out if b and c have values less or more than the values
in list a?


Sounds like a good use for 2.5's addition of the any() and all() 
functions -- you don't mention whether you want your variable 
compared against *any* of the list items or *all* of the list 
items.  You also don't mention whether you want the comparison 
results, or just a single scalar.  Lastly, you omit the details 
of what happens if your target value (d below) falls within the 
range.  One of the following should do it for you:


   a = range(10,21)
   b = 9
   c = 21
   d = 15
   any(b  x for x in a)
  True
   all(b  x for x in a)
  True
   any(c  x for x in a)
  False
   any(d  x for x in a)
  True
   all(d  x for x in a)
  False
   any(c  x for x in a)
  True
   all(c  x for x in a)
  True
   any(d  x for x in a)
  True
   all(d  x for x in a)
  False

If you just want the comparisons:

  y1 = [bx for x in a]
  y2 = [cx for x in a]
  y3 = [dx for x in a]
  z1 = [(bx, bx) for x in a]
  z2 = [(cx, cx) for x in a]
  z3 = [(dx, dx) for x in a]

-tkc






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


Re: Shutdown Mac OSX computer using python

2008-12-08 Thread Wolfgang Draxinger
Håkan Hagenrud wrote:

 Hello, i'm a python noob!
 
 But I would like to shutdown a 10.5.x mac computer using python
 (2.5.1)
 
 this is my code:
 #!/usr/bin/python
 import SystemEvents
 down = SystemEvents.Power_Suite.Power_Suite_Events()
 down.shut_down()
 
 the last call needs an additional argument, I cant find any
 documentation about this. Anybody knows?
 
 Thank you!

Why so complicated? MacOS X is a Unix at it's base, so you can
use Unix commands.

#!/usr/bin/python
import os
os.system(shutdown -h now)

Must be run as root, won't work otherwise. You can however add to
sudoers (man visudo) shutdown as NOPASSWD program for the users
that want to execute the script and use sudo shutdown ...
instead of just shutdown ...

Wolfgang Draxinger
-- 
E-Mail address works, Jabber: [EMAIL PROTECTED], ICQ: 134682867

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


Beginner trying to understand functions.

2008-12-08 Thread simonh
In my attempt to learn Python I'm writing a small (useless) program to
help me understand the various concepts. I'm going to add to this as I
learn to serve as a single place to see how something works,
hopefully. Here is the first approach:



name = input('Please enter your name: ')
print('Hello', name)

while True:
try:
age = int(input('Please enter your age: '))
break
except ValueError:
print('That was not a valid number. Please try again.')

permitted = list(range(18, 31))

if age in permitted:
print('Come on in!')
elif age  min(permitted):
print('Sorry, too young.')
elif age  max(permitted):
print('Sorry, too old.')

input('Press any key to exit.')



That works fine. Then I've tried to use functions instead. The first
two work fine, the third fails:



def getName():
name = input('Please enter your name: ')
print('Hello', name)

def getAge():
while True:
try:
age = int(input('Please enter your age: '))
break
except ValueError:
print('That was not a valid number. Please try again.')

def checkAge():
permitted = list(range(18, 31))
if age in permitted:
print('Come on in!')
elif age  min(permitted):
print('Sorry, too young.')
elif age  max(permitted):
print('Sorry, too old.')

getName()
getAge()
checkAge()

I get this error message: NameError: global name 'age' is not
defined.

I'm stuck, can someone help? Thanks.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL?

2008-12-08 Thread Pierre-Alain Dorange
illume [EMAIL PROTECTED] wrote:

 pygame is also much more portable, has more people using it, has more
 developers, and a stable API.  Code you wrote 5 years ago will most
 likely still work.  Code you wrote for older versions of pyglet will
 not work without changes.

I'm a new python and pygame user (i came from C/C++), very easy to learn
and you got results very fast.

I've done a low investigation before choosing pygame over pyglet.
I choose pygame because i only need 2D and also because it seems there
is more documentations, samples, books and developers for pygame.

pygame is really easy to learn and seems fast to me and easy to extend
(derivate class), support image, sound, etc... And can be bundled with
py2app (Mac) : important to distribute the project.
I just run a bug whn using background music, py2app fail ti create the
bundle...

On my iMac intel, i run my small arcade game (a spaceinvader like)
between 800-1400 fps using dirtyrect.
I can also run without modification on Windows and Unbuntu using WMWare
on the same machine.

-- 
Pierre-Alain Dorange
http://microwar.sourceforge.net/

Ce message est sous licence Creative Commons by-nc-sa-2.0
http://creativecommons.org/licenses/by-nc-sa/2.0/fr/
--
http://mail.python.org/mailman/listinfo/python-list


Re: getting error...... Traceback (most recent call last): File stdin, line 1, in module File C:\Python25\Lib\site-packages\xlrd\__init__.py, line 370, in open_workbook biff_version = bk.getb

2008-12-08 Thread John Machin
On Dec 8, 6:48 pm, Gabriel Genellina [EMAIL PROTECTED] wrote:
 En Fri, 05 Dec 2008 02:31:01 -0200, pk sahoo [EMAIL PROTECTED]  
 escribió:



  hallo everybody,
  when i am running the following command

  import xlrd
  book=xlrd.open_workbook(C:\\a.xls)

  i am getting the following error..

  *Traceback (most recent call last):
    File stdin, line 1, in module
    File C:\Python25\Lib\site-packages\xlrd\__init__.py, line 370, in
  open_workb
  ook
      biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
    File C:\Python25\Lib\site-packages\xlrd\__init__.py, line 1323, in
  getbof
      raise XLRDError('Expected BOF record; found 0x%04x' % opcode)
  xlrd.biffh.XLRDError: Expected BOF record; found 0x3f3c*

 Looks like your a.xls file is not an Excel file (one of the formats  
 supported by xlrd).
 As 0x3f3c corresponds to the characters '?' you probably have an XML file.

This can be verified easily by opening the file with a simple-minded
text editor (e.g. Notepad) ... if the first two lines are

?xml version=1.0?
?mso-application progid=Excel.Sheet?

then it's an Excel 2003 XML Spreadsheet that's been manually(?)
renamed from .xml to .xls.

The current xlrd release supports only the binary (BIFF) format .xls
files created by Excel 3.0 to Excel 2003. The next release (due out
Real Soon Now) will support Excel 2.1 and 2.0 formats [don't ask].
Very soon after that will come support for Excel 2007 .xlsx which is a
bunch of XML files inside a ZIP file. Support for Excel 2003
SpreadsheetML is way down the to-do list.

If the OP wants to be able to read the file with xlrd:
(1) Open it with Excel 200[37] and save as a .xls file
or (2) rename it to .xml, start OpenOffice.org Calc, click on File,
click on Open, click on Files of type, choose Microsoft Excel 2003
XML (*.xml) from the (long, unsorted) drop-down list, ..., and save
as etc etc. Gnumeric is not an option.

HTH,
John



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


Re: Mathematica 7 compares to other languages

2008-12-08 Thread Jon Harrop
[EMAIL PROTECTED] wrote:
 Well, its past 'tonight' and 6 hours to go till past 'tomorrow'.
 Where the hell is it Zah Zah?

Note that this program takes several days to compute in Mathematica (even
though it takes under four seconds in other languages) so don't expect to
see a genuinely optimized version any time soon... ;-)

-- 
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
http://www.ffconsultancy.com/?u
--
http://mail.python.org/mailman/listinfo/python-list


Re: built-in functions as class attributes

2008-12-08 Thread Peter Otten
Mark Dickinson wrote:

 Here's a curiosity:  after
 
 def my_hex(x):
 return hex(x)
 
 one might expect hex and my_hex to be interchangeable
 in most situations.  But (with both Python 2.x and 3.x)
 I get:
 
 def my_hex(x): return hex(x)
 ...
 class T(object): f = hex
 ...
 class T2(object): f = my_hex
 ...
 T().f(12345)
 '0x3039'
 T2().f(12345)
 Traceback (most recent call last):
   File stdin, line 1, in module
 TypeError: my_hex() takes exactly 1 argument (2 given)
 [36412 refs]
 
 Anyone know what the precise rules that lead to this
 behaviour are, or where they're documented?

To work properly as a method a callable needs a __get__() method
implementing the binding mechanism. Functions written in C generally don't
have that.

 class A(object):
... def __call__(self, *args):
... print called with, args
...
 class B(object):
... a = A()
...
 B().a()
called with ()

Now let's turn A into a descriptor:

 def __get__(self, inst, cls=None):
... print inst, cls
... if inst is not None:
... def bound(*args):
... self(inst, *args)
... return bound
... return self
...
 A.__get__ = __get__
 B().a()
__main__.B object at 0x2ae49971b890 class '__main__.B'
called with (__main__.B object at 0x2ae49971b890,)

I don't know if there is something official, I google for

http://users.rcn.com/python/download/Descriptor.htm

or descrintro every time I need a refresher.

Peter

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


Shutdown Mac OSX computer using python

2008-12-08 Thread Håkan Hagenrud

Hello, i'm a python noob!

But I would like to shutdown a 10.5.x mac computer using python (2.5.1)

this is my code:
#!/usr/bin/python
import SystemEvents
down = SystemEvents.Power_Suite.Power_Suite_Events()
down.shut_down()

the last call needs an additional argument, I cant find any  
documentation about this. Anybody knows?


Thank you!

Håkan Hagenrud
--
http://mail.python.org/mailman/listinfo/python-list


Re: Strengths and weaknesses of Pygame vs. pyglet vs. PyOpenGL?

2008-12-08 Thread illume
On Dec 8, 8:59 pm, alex23 [EMAIL PROTECTED] wrote:
 On Dec 8, 7:18 pm, illume [EMAIL PROTECTED] wrote:

  It's easier to teach only requiring *using* classes, and functions
  than *creating* them.  This is important if it's being used to teach
  programming - as you don't need to teach people two fairly large
  concepts before you can do anything.

 I'm just kind of aghast at the idea of teaching anyone how to
 program games by using large, imperative chunks of code. I don't see
 functions as being a fairly large concept at all, and utterly vital
 to being able to write anything but the most basic 'hello world'
 example code.


Yes, teaching hello world without requiring the creation classes is a
*good thing*.  Imagine having to create classes to make a hello world
program? You'd have a typical java hello world program.  This means
you need to explain the concept of OO before they can do hello world.

It's about teaching concepts separately, rather than requiring them to
be taught all at once.  If you don't need to use something, then why
bother using it?  Just for purity?  Python has a long history of not
making everything classes.

So I see requiring the creation of classes to do 'hello world' as
being un-pythonic and overly complex.  I also see it getting in the
way of seeing results, which is important when intially learning
programming.



  Also python has very slow function calls, so avoiding using callbacks
  is also faster.

 Wouldn't it be better to teach people the basics of coding -before-
 setting out to optimise their code?

I was explaing the advantages of avoiding callbacks, and avoiding
requiring the creation of classes.  I think it's simpler, and faster
to avoid callbacks.  I was not saying that it's better to optimize
peoples code before teaching people the basics of programming.


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


Public imports

2008-12-08 Thread Márcio Faustino
Hi,

Does Python support public imports instead of the default private?
Something like D's public import (see http://www.digitalmars.com/d/
2.0/module.html) or even Perl's export_to_level.

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


Re: Determining whether a variable is less/greater than a range.

2008-12-08 Thread [EMAIL PROTECTED]
Found it. min and max functions. I thought that this would be
implemented as a list method:

a.min
a.max

I can see that the built in functions make sense.

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


Re: built-in functions as class attributes

2008-12-08 Thread Mark Dickinson
On Dec 8, 11:23 am, Peter Otten [EMAIL PROTECTED] wrote:
 I don't know if there is something official, I google for

 http://users.rcn.com/python/download/Descriptor.htm

 or descrintro every time I need a refresher.

Thank you!  I'd read this before, but apparently I'd
either not taken it in first time round, or entirely
forgotten it.

Anything written by Raymond has got to be pretty
darn close to 'official'.  :)

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


Re: Determining whether a variable is less/greater than a range.

2008-12-08 Thread Peter Otten
[EMAIL PROTECTED] wrote:

 Hi. I'm having another go at learning Python so I'll probably be
 asking a few basic questions. Here is the first one.
 
 a = list(range(10, 21)
 
 b = 9
 
 c = 21
 
 How can I find out if b and c have values less or more than the values
 in list a?

 a = range(10, 21)
 b = 9
 c = 21

Are there any items in a that are less than b or greater than c?

 any(xb or xc for x in a)
False

No. Are there any items in a that are greater than b?

 any(xb for x in a)
True

Yes.

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


Re: Beginner trying to understand functions.

2008-12-08 Thread James Mills
On Mon, Dec 8, 2008 at 11:32 PM, simonh [EMAIL PROTECTED] wrote:
 That works fine. Then I've tried to use functions instead. The first
 two work fine, the third fails:

[ ... snip ... ]

Try this:

def getName():
   name = input('Please enter your name: ')
   print('Hello', name)
   return name

def getAge():
   while True:
  try:
 return int(input('Please enter your age: '))
  except ValueError:
 print('That was not a valid number. Please try again.')

def checkAge(age):
  permitted = list(range(18, 31))
  if age in permitted:
 print('Come on in!')
 return True
  elif age  min(permitted):
 print('Sorry, too young.')
 elif age  max(permitted):
 print('Sorry, too old.')

  return False

name = getName()
age = getAge()
if checkAge(age):
   # Do something
else:
   # Do something else


cheers
James

PS: Read the Tutorial :)

-- 
--
-- Problems are solved by method
--
http://mail.python.org/mailman/listinfo/python-list


Re: infering the number of args a function takes at runtime

2008-12-08 Thread Lie Ryan
On Mon, 08 Dec 2008 02:40:03 -0800, sniffer wrote:

 On Dec 8, 9:39 am, sniffer [EMAIL PROTECTED] wrote:
 hi all,
 i am a python newbie, in a project currently doing i need to find out
 the number of arguments that a function takes at runtime.? Is this
 possible ,if so how do i do this,i ve looked through the python
 documentation but couldnt find anything.any help will be great

 TIA
 
 Thanks guys , i think this should work for me.btw as enquired i am
 working o a mvc thingie where in need to call functions in a
 controller,and pass the arguments as recieved from the end user so i
 need to make sure that the number of arguments passed from the front end
 are correct or not in the context of the function being called

In python, usually you'll just pass the them all and maybe catch errors.

def callback(*args, **kargs):
try:
return func(*args, **kargs)
except TypeError:
print('An error happened')

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


Re: Beginner trying to understand functions.

2008-12-08 Thread Pierre-Alain Dorange
simonh [EMAIL PROTECTED] wrote:

 def getName():
 name = input('Please enter your name: ')
 print('Hello', name)
 
 def getAge():
 while True:
 try:
 age = int(input('Please enter your age: '))
 break
 except ValueError:
 print('That was not a valid number. Please try again.')
 
 def checkAge():
 permitted = list(range(18, 31))
 if age in permitted:
 print('Come on in!')
 elif age  min(permitted):
 print('Sorry, too young.')
 elif age  max(permitted):
 print('Sorry, too old.')
 
 getName()
 getAge()
 checkAge()
 
 I get this error message: NameError: global name 'age' is not
 defined.

Indeed age was not a global... So :

1/ make it a global (just define age=0 before getAge()

2/ or return a value from getAge() and pass this avlue to checkAge.

I recommand the second option, less globals is always better.

def getAge():
while True:
try:
age = int(input('Please enter your age: '))
return age

except ValueError:
print('That was not a valid number. Please try again.')

def checkAge(age,min=18,max=31):
if age in list(range(min, max)):
print('Come on in!')
elif age  min:
print('Sorry, too young.')
elif age  max:
print('Sorry, too old.')

getName()
a=getAge()
checkAge(a)

For my part, i wouldn't loop getAge(à this way : i dislike infinite
loop.
I prefer to return None when ther is an error and check for None in the
main program

def getAge():
try:
age = int(input('Please enter your age: '))
return age

except ValueError:
print('That was not a valid number. Please try again.')
return None

getName()
a=getAge()
if a!=None:
checkAge(a)

of i you want to loop in getAge() :

def getAge():
age=-1
while age0:
try:
age = int(input('Please enter your age: '))

except ValueError:
print('That was not a valid number. Please try again.')

return age

I'm a beginner with python, perhaps it was not pythonic, but i'm sure
someone will tell is it's not.

-- 
Pierre-Alain Dorangehttp://microwar.sourceforge.net/

Ce message est sous licence Creative Commons by-nc-sa-2.0
http://creativecommons.org/licenses/by-nc-sa/2.0/fr/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Determining whether a variable is less/greater than a range.

2008-12-08 Thread eric
On Dec 8, 11:44 am, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 Hi. I'm having another go at learning Python so I'll probably be
 asking a few basic questions. Here is the first one.

 a = list(range(10, 21)

 b = 9

 c = 21

 How can I find out if b and c have values less or more than the values
 in list a?

 Thanks.


what about:
a = list(range(10, 21))


def compare(value, list):
m,M = min(list), max(list)
return value=m, value=M

b = 9
c = 21

print compare(b,a)
print compare(c,a)

for i in range (8, 25):
print i, compare(i, a)



(False, True)
(True, False)
8 (False, True)
9 (False, True)
10 (True, True)
11 (True, True)
12 (True, True)
13 (True, True)
14 (True, True)
15 (True, True)
16 (True, True)
17 (True, True)
18 (True, True)
19 (True, True)
20 (True, True)
21 (True, False)
22 (True, False)
23 (True, False)
24 (True, False)


it helps?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and audio frequency analysis

2008-12-08 Thread Pierre-Alain Dorange
manatlan [EMAIL PROTECTED] wrote:

 I'd like to make a kind of spectrum analyzer ...
 Which should display bars according bands of frequencies ... in real
 time...
 
 Is anybody know an audio processing lib in python for that ?

For the display module you can use pygame, pyglet or pyOpenGL, there are
fast.

For the audio analysis i thought the module must be written in C or
something very fast, because python, due to it's nature, would probably
not compute spectrum as fast as real time : 44100 samples per seconds is
a lot of work...



-- 
Pierre-Alain Dorangehttp://microwar.sourceforge.net/

Ce message est sous licence Creative Commons by-nc-sa-2.0
http://creativecommons.org/licenses/by-nc-sa/2.0/fr/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner trying to understand functions.

2008-12-08 Thread Peter Otten
simonh wrote:

 In my attempt to learn Python I'm writing a small (useless) program to
 help me understand the various concepts. I'm going to add to this as I
 learn to serve as a single place to see how something works,
 hopefully. Here is the first approach:

 That works fine. Then I've tried to use functions instead. The first
 two work fine, the third fails:

 def getName():
 name = input('Please enter your name: ')
 print('Hello', name)
 
 def getAge():
 while True:
 try:
 age = int(input('Please enter your age: '))
 break
 except ValueError:
 print('That was not a valid number. Please try again.')
 
 def checkAge():
 permitted = list(range(18, 31))
 if age in permitted:
 print('Come on in!')
 elif age  min(permitted):
 print('Sorry, too young.')
 elif age  max(permitted):
 print('Sorry, too old.')
 
 getName()
 getAge()
 checkAge()
 
 I get this error message: NameError: global name 'age' is not
 defined.
 
 I'm stuck, can someone help? Thanks.


Generally, when you calculate something within a function you tell it the
caller by returning it:

 def get_age():
... return 74
...
 get_age()
74
 age = get_age()
 age
74

And if you want a function to act upon a value you pass it explicitly:

 def check_age(age):
... if 18 = age = 30:
... print(Come in)
... else:
... print(Sorry, you can't come in)
...
 check_age(10)
Sorry, you can't come in
 check_age(20)
Come in

To check the age determined by the get_age() function you do:

 age = get_age()
 check_age(age)
Sorry, you can't come in

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


Beginner trying to understand functions.

2008-12-08 Thread acerimusdux

simonh write:

In my attempt to learn Python I'm writing a small (useless) program to
help me understand the various concepts. I'm going to add to this as I
learn to serve as a single place to see how something works,
hopefully. Here is the first approach:



name = input('Please enter your name: ')
print('Hello', name)

while True:
try:
age = int(input('Please enter your age: '))
break
except ValueError:
print('That was not a valid number. Please try again.')

permitted = list(range(18, 31))

if age in permitted:
print('Come on in!')
elif age  min(permitted):
print('Sorry, too young.')
elif age  max(permitted):
print('Sorry, too old.')

input('Press any key to exit.')



That works fine. Then I've tried to use functions instead. The first
two work fine, the third fails:



def getName():
name = input('Please enter your name: ')
print('Hello', name)

def getAge():
while True:
try:
age = int(input('Please enter your age: '))
break
except ValueError:
print('That was not a valid number. Please try again.')

def checkAge():
permitted = list(range(18, 31))
if age in permitted:
print('Come on in!')
elif age  min(permitted):
print('Sorry, too young.')
elif age  max(permitted):
print('Sorry, too old.')

getName()
getAge()
checkAge()

I get this error message: NameError: global name 'age' is not
defined.

I'm stuck, can someone help? Thanks.
  


You are running into Python's scoping rules. Variables in Python are not 
global by default, they are local to their scope. Each function has it's 
own scope (but blocks like if: and while: don't.) So your variable age 
only exists in
getage(). It doesn't exist in checkage().  You could simply add a 
global age statement to getAge() before you first use the age 
variable, and that will likely work.


Or, rather than declare it global, you might want to have getage() 
return a value, and then pass it to checkage () as a function parameter. 
Add a return age statement to getage() before break. Then, for your def:


def checkage(age):

And then when calling:

A=getAge()
checkAge(A)





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


Re: Guido's new method definition idea

2008-12-08 Thread Almar Klein
I like the transparancy and clearity of python, and the explicit self
fits beautifully. Allowing a second way of defining your methods
would only confuse newbies more I would think.

I was a newby only half a year ago (or maybe I still am). The
explicit self seems weird the very first time you see it, but very
soon you see the beauty of it. The error message may be confusing
sometimes, but as Guido says, I guess it's better to fix the
error message rather than changing the language.

-1 for me!

As for the $ stuff, it makes things less transparant and yes, it's looks
rather ugly.

-1 on this one as well.


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


Re: gzip.GzipFile (was Re: Don't you just love writing this sort of thing :))

2008-12-08 Thread MRAB

Jorgen Grahn wrote:

On Sat, 06 Dec 2008 10:01:10 +, Arnaud Delobelle [EMAIL PROTECTED] wrote:

...

Why use (open, gzp.GzipFile)[Entry.endswith(.gz)] when we have had
contitional expressions for a few years now?  Instead, you can write

(gzip.GzipFile if entry.endswidth(.gz) else open).

I think it will be faster (as it doesn't require the construction of a
tuple and then the retrieval of one of its elements) and clearer.


Even clearer would be if gzip.Gzipfile could (optionally) read
non-gzipped files and file-like objects, like the gzip Unix commands
zcat -f, zgrep and so on.

Also, making a decision based on the .gz part of the name isn't
always correct -- you miss files named foo.Z and similar.

gzip is for reading gzipped files. IMHO it would be better to have a 
de-archive module which uses the gzip, tarfile, etc, modules as necessary.

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


Re: Rich Comparisons Gotcha

2008-12-08 Thread Rasmus Fogh
Rober Kern wrote:
James Stroud wrote:
 Steven D'Aprano wrote:
 On Sun, 07 Dec 2008 13:57:54 -0800, James Stroud wrote:

 Rasmus Fogh wrote:

 ll1 = [y,1]
 y in ll1
 True
 ll2 = [1,y]
 y in ll2
 Traceback (most recent call last):
   File stdin, line 1, in module
 ValueError: The truth value of an array with more than one element
is
 ambiguous. Use a.any() or a.all()
 I think you could be safe calling this a bug with numpy.

 Only in the sense that there are special cases where the array
 elements are all true, or all false, and numpy *could* safely return a
 bool. But special cases are not special enough to break the rules.
 Better for the numpy caller to write this:

 a.all() # or any()

 instead of:

 try:
 bool(a)
 except ValueError:
 a.all()

 as they would need to do if numpy sometimes returned a bool and
 sometimes raised an exception.

 I'm missing how a.all() solves the problem Rasmus describes, namely
that
 the order of a python *list* affects the results of containment tests
by
 numpy.array. E.g. y in ll1 and y in ll2 evaluate to different
 results in his example. It still seems like a bug in numpy to me, even
 if too much other stuff is broken if you fix it (in which case it
 apparently becomes an issue).

 It's an issue, if anything, not a bug. There is no consistent
 implementation of
 bool(some_array) that works in all cases. numpy's predecessor Numeric
 used to
 implement this as returning True if at least one element was non-zero.
 This
 works well for bool(x!=y) (which is equivalent to (x!=y).any()) but does
 not
 work well for bool(x==y) (which should be (x==y).all()), but many people
 got
 confused and thought that bool(x==y) worked. When we made numpy, we
 decided to
 explicitly not allow bool(some_array) so that people will not write
 buggy code like this again.

You are so right, Robert:

 The deficiency is in the feature of rich comparisons, not numpy's
 implementation of it. __eq__() is allowed to return non-booleans;
 however, there are some parts of Python's implementation like
 list.__contains__() that still expect the return value of __eq__() to be
 meaningfully cast to a boolean.

One might argue if this is a deficiency in rich comparisons or a rather a
bug in list, set and dict. Certainly numpy is following the rules. In fact
numpy should be applauded for throwing an error rather than returning a
misleading value.

For my personal problem I could indeed wrap all objects in a wrapper with
whatever 'correct' behaviour I want (thanks, TJR). It does seem a bit
much, though, just to get code like this to work as intended:
  alist.append(x)
  print ('x is present: ', x in alist)

So, I would much prefer a language change. I am not competent to even
propose one properly, but I'll try.

First, to clear the air:
Rich comparisons, the ability to overload '==', and the constraints (or
lack of them) on __eq__ must stay unchanged. There are reasons for their
current behaviour - ieee754 is particularly convincing - and anyway they
are not going to change. No point in trying.

There remains the problem is that __eq__ is used inside python
'collections' (list, set, dict etc.), and that the kind of overloading
used (quite legitimately) in numpy etc. breaks the collection behaviour.
It seems that proper behaviour of the collections requires an equality
test that satisfies:
1) x equal x
2) x equal y = y equal x
3) x equal y and y equal z = x equal z
4) (x equal y) is a boolean
5) (x equal y) is defined (and will not throw an error) for all x,y
6) x unequal y == not(x equal y) (by definition)

Note to TJR: 5) does not mean that Python should magically shield me from
errors. All I am asking is that programmers design their equal() function
to avoid raising errors, and that errors raised from equal() clearly
count as bugs.

I cannot imagine getting the collections to work in a simple and intuitive
manner without an equality test that satisfies 1)-6). Maybe somebody else
can. Instead I would propose adding an __equal__ special method for the
purpose.

It looks like the current collections use the folowing, at least in part

def oldCollectionTest(x,y):
  if x is y:
return True
  else:
return (x == y)

I would propose adding a new __equal__ method that satisfies 2) - 6)
above.

We could then define

def newCollectionTest(x,y):
  if x is y:
# this takes care of satisfying 1)
return True
  elif hasattr(x, '__equal__'):
return x.__equal__(y)
  elif hasattr(y, '__equal__'):
return y.__equal__(x)
  else:
return False

The implementations for list, set and dict would then behave according to
newCollectionTest. We would also want an equal() built-in with the same
behaviour.

In plain words, the default behaviour would be identity semantics. Objects
that wanted value semantics could implement an __equal__ function with the
correct behaviour. Wherever possible __equal__ would be the same as
__eq__.  This function may deviate from 'proper' behaviour in some cases.
All I claim 

Re: dBase III files and Visual Foxpro 6 files

2008-12-08 Thread sniffer
On Dec 8, 12:53 pm, Ethan Furman [EMAIL PROTECTED] wrote:
 Greetings All!

 I nearly have support complete for dBase III dbf/dbt files -- just
 wrapping up support for dates.  The null value has been a hindrance for
 awhile but I nearly have that solved as well.

 For any who know of a cool dbf module already in existence for dBase III
 and Visual Foxpro -- where were you six months ago when I was searching?
   ;)  Seriously, though, this has been a great learning experience for me.

 As I said -- dbf/dbt files are 99% ready.  idx files -- no support:  for
 my purposes I just don't need them.  I've found no problem in loading
 tables up to 300,000 records with 50 fields per record, and re-ordering
 them on the fly in memory.

 However, after putting much effort into this code, and wanting it to be
 useful to others in the community, are there others who work with dbf
 files that would need idx/cdx support?  Or tables so large they won't
 fit comfortably into memory?

 ~ethan~

hi ethan,
great to hear that someone has finally written something for
interacting with vfp6 data,when do you plan to release it
--
http://mail.python.org/mailman/listinfo/python-list


Re: Public imports

2008-12-08 Thread bearophileHUGS
Márcio Faustino:
 Does Python support public imports instead of the default private?
 Something like D's public import (see http://www.digitalmars.com/d/
 2.0/module.html) or even Perl's export_to_level.

D type system has several big holes, and I am trying to push Walter to
fix some of those, to make it look a little more sane, like for
example the Python module system.
Public imports are often bad.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and audio frequency analysis

2008-12-08 Thread David Cournapeau
On Mon, Dec 8, 2008 at 10:20 PM, manatlan [EMAIL PROTECTED] wrote:
 I'd like to make a kind of spectrum analyzer ...
 Which should display bars according bands of frequencies ... in real
 time...

 Is anybody know an audio processing lib in python for that ?

Hi,

It is possible to use python for audio processing: I am doing in PhD
in audio signal processing, and I mostly use python for my research:
audio file IO, relatively advanced processing, display. You will need
scientific packages to do the processing: numpy at minimum, to give
you an array class ala matlab, for fast vector operations, and scipy
to give you more tools (filtering, multi-dimensional fft, etc...).

Now, it may not be usable depending on your application: if you know
matlab, and your application is doable in matlab, it is doable in
python + numpy/scipy. You can see an example of real-time spectrogram
with the whole scientific python stack here:

http://code.enthought.com/projects/chaco/gallery.php (last example at
the bottom)

But it may not work out depending on what you mean by real-time: if
you use the term precisely, in its computer-science meaning
(time-bound process), then it will be difficult if not impossible, by
the very nature of python. You need a very precise control of
resources in that context, which python does not give.

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


Re: Beginner trying to understand functions.

2008-12-08 Thread cadmuxe
i think we should use raw_input('Please enter your name: ') instead of
input('Please enter your name: ')

2008/12/8 Peter Otten [EMAIL PROTECTED]

 simonh wrote:

  In my attempt to learn Python I'm writing a small (useless) program to
  help me understand the various concepts. I'm going to add to this as I
  learn to serve as a single place to see how something works,
  hopefully. Here is the first approach:

  That works fine. Then I've tried to use functions instead. The first
  two work fine, the third fails:

  def getName():
  name = input('Please enter your name: ')
  print('Hello', name)
 
  def getAge():
  while True:
  try:
  age = int(input('Please enter your age: '))
  break
  except ValueError:
  print('That was not a valid number. Please try again.')
 
  def checkAge():
  permitted = list(range(18, 31))
  if age in permitted:
  print('Come on in!')
  elif age  min(permitted):
  print('Sorry, too young.')
  elif age  max(permitted):
  print('Sorry, too old.')
 
  getName()
  getAge()
  checkAge()
 
  I get this error message: NameError: global name 'age' is not
  defined.
 
  I'm stuck, can someone help? Thanks.


 Generally, when you calculate something within a function you tell it the
 caller by returning it:

  def get_age():
 ... return 74
 ...
  get_age()
 74
  age = get_age()
  age
 74

 And if you want a function to act upon a value you pass it explicitly:

  def check_age(age):
 ... if 18 = age = 30:
 ... print(Come in)
 ... else:
 ... print(Sorry, you can't come in)
 ...
  check_age(10)
 Sorry, you can't come in
  check_age(20)
 Come in

 To check the age determined by the get_age() function you do:

  age = get_age()
  check_age(age)
 Sorry, you can't come in

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

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


[Python 2.x] Pickling a datetime.tzinfo subclass instance?

2008-12-08 Thread Cong Ma
Hello,

I'm writing a program that pickles an instance of a custom subclass of
datetime.tzinfo. I followed the guides given in the Library Reference (version
2.5.2, chapter 5.1.6), which contain the note:

Special requirement for pickling: A tzinfo subclass must have an __init__
method that can be called with no arguments, else it can be pickled but possibly
not unpickled again. This is a technical requirement that may be relaxed in the
future.

I tried this with an example FixedOffset subclass instance given in the
Example section in the manual. It indeed failed to unpickle. To work around
this, I found two possible solutions:
1. Modify the __init__ method so that it takes optional arguments with default
values;
2. Implement the __getinitargs__ method so that it does the opposite of
__init__: returning a tuple from the instance's internal state that can be used
to re-initialize an instance, retaining the old value.

My questions:
1. Is the technical limitation fixed in version 2.6 or 3.0? I can't check it
for myself now... Python.org seems down and I can't find the docs.
2. To stick with version 2.5, which of the above 2 methods is better? Both seems
 to unpickle to the correct result, but are there subtle side-effects? Or there
are better solutions?

Regards,
Cong.

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


Re: Beginner trying to understand functions.

2008-12-08 Thread James Mills
On Tue, Dec 9, 2008 at 12:24 AM, cadmuxe [EMAIL PROTECTED] wrote:
 i think we should use raw_input('Please enter your name: ') instead of
 input('Please enter your name: ')

Good point :) OP: Please take notes :)

cheers
James

-- 
--
-- Problems are solved by method
--
http://mail.python.org/mailman/listinfo/python-list


Re: Public imports

2008-12-08 Thread bearophileHUGS
 D type system has several big holes,

I meant D module system, of course. Sorry.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner trying to understand functions.

2008-12-08 Thread Benjamin Kaplan
On Mon, Dec 8, 2008 at 9:24 AM, cadmuxe [EMAIL PROTECTED] wrote:

 i think we should use raw_input('Please enter your name: ') instead of
 input('Please enter your name: ')


Print is a function in this code and range returns an iterator (or else
list(range(18,31)) is redundant). I think the OP is using python 3. Guess
we're all going to have to get used to some of the changes, like raw_input
being renamed to input.




 2008/12/8 Peter Otten [EMAIL PROTECTED]

 simonh wrote:

  In my attempt to learn Python I'm writing a small (useless) program to
  help me understand the various concepts. I'm going to add to this as I
  learn to serve as a single place to see how something works,
  hopefully. Here is the first approach:

  That works fine. Then I've tried to use functions instead. The first
  two work fine, the third fails:

  def getName():
  name = input('Please enter your name: ')
  print('Hello', name)
 
  def getAge():
  while True:
  try:
  age = int(input('Please enter your age: '))
  break
  except ValueError:
  print('That was not a valid number. Please try again.')
 
  def checkAge():
  permitted = list(range(18, 31))
  if age in permitted:
  print('Come on in!')
  elif age  min(permitted):
  print('Sorry, too young.')
  elif age  max(permitted):
  print('Sorry, too old.')
 
  getName()
  getAge()
  checkAge()
 
  I get this error message: NameError: global name 'age' is not
  defined.
 
  I'm stuck, can someone help? Thanks.


 Generally, when you calculate something within a function you tell it the
 caller by returning it:

  def get_age():
 ... return 74
 ...
  get_age()
 74
  age = get_age()
  age
 74

 And if you want a function to act upon a value you pass it explicitly:

  def check_age(age):
 ... if 18 = age = 30:
 ... print(Come in)
 ... else:
 ... print(Sorry, you can't come in)
 ...
  check_age(10)
 Sorry, you can't come in
  check_age(20)
 Come in

 To check the age determined by the get_age() function you do:

  age = get_age()
  check_age(age)
 Sorry, you can't come in

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



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


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


datetime and the rich-companison operators

2008-12-08 Thread Ethan Furman

Greetings All!

I am implementing a NullDate class in order to mirror dates and 
datetimes that have no value  (yes, this is for my dbf  module :)


I'm still a bit fuzzy about class methods, hashing, and __new__, but my 
question of the moment is this:  it seems to me that with two dates or 
datetimes, they should either be equal, or one should precede the other, 
and this can be accomplished quite handily with __cmp__... so does 
anyone know why the rich comparisons were used in the datetime module? 
Was it simply a style choice, or is something being handled that __cmp__ 
couldn't cope with?


Thanks in advance!
~ethan~
--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner trying to understand functions.

2008-12-08 Thread Peter Otten
James Mills wrote:

 On Tue, Dec 9, 2008 at 12:24 AM, cadmuxe [EMAIL PROTECTED] wrote:
 i think we should use raw_input('Please enter your name: ') instead of
 input('Please enter your name: ')
 
 Good point :) OP: Please take notes :)

I think the OP is using Python 3.0. What used to cause trouble

Python 2.5.1 (r251:54863, Jul 31 2008, 23:17:43)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type help, copyright, credits or license for more information.
 input()
1/0
Traceback (most recent call last):
  File stdin, line 1, in module
  File string, line 1, in module
ZeroDivisionError: integer division or modulo by zero

is now the way it should be:

Python 3.0 (r30:67503, Dec  4 2008, 11:26:28)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type help, copyright, credits or license for more information.
 raw_input()
Traceback (most recent call last):
  File stdin, line 1, in module
NameError: name 'raw_input' is not defined
 input()
1/0
'1/0'

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


Re: [Py2exe-users] py2exe 0.6.9 released

2008-12-08 Thread Pascal
On Mon, 17 Nov 2008 12:39:36 +, Pascal wrote:

 On Sun, 16 Nov 2008 21:23:59 -0500, Chris Spencer wrote:
 
 After I compile my program with py2exe 0.6.9 with Python 2.6, I'm
 still getting the Application Did Not Initialize Properly error
 dialog whenever I run my code.  What am I doing wrong?
 
 I have exactly the same problem.
 I have tried just anything I could think of to no avail : Copied the 3
 msvc_90.dll to the system32 subdir of Windows, to the directory of my
 application, reinstalled the whole Microsoft Visual C++ 2008
 Redistributable Package, embedded the manifest data into the exe or kept
 it in a .manifest file...
 Could not make it work. Always got the Application Did Not Initialize
 Properly message.
 I'm with Windows XP SP3. I tried all this on 2 different systems and I
 got the same results.


I think I narrowed down a little bit the problem. It's not the common one 
when the msvc_90.dll are not located, though the result is similar.
The problem is when you try to generate at least 2 exe in one setup (with 
2 scripts specified in the windows command of the setup).
This works OK with py2exe 0.6.9 for Python 2.5, but fails with Python 2.6 
(and 2.6.1). None of the generated exe can be started.
When I compare the content of library.zip in both versions, this file 
doesn't contain any .pyc for the scripts you want to generate an exe for 
with Python 2.5, but always contains a .pyc for one of the scripts you 
want to generate an .exe for with Python 2.6. Don't know if it's a clue 
for finding a fix.
I have tested many ways to figure this out but I can't find any solution 
for the moment so I'm sticking with Python 2.5.
--
http://mail.python.org/mailman/listinfo/python-list


Re: dBase III files and Visual Foxpro 6 files

2008-12-08 Thread Ethan Furman

sniffer wrote:

On Dec 8, 12:53 pm, Ethan Furman [EMAIL PROTECTED] wrote:

Greetings All!

I nearly have support complete for dBase III dbf/dbt files -- just
wrapping up support for dates.  The null value has been a hindrance for
awhile but I nearly have that solved as well.

For any who know of a cool dbf module already in existence for dBase III
and Visual Foxpro -- where were you six months ago when I was searching?
  ;)  Seriously, though, this has been a great learning experience for me.

As I said -- dbf/dbt files are 99% ready.  idx files -- no support:  for
my purposes I just don't need them.  I've found no problem in loading
tables up to 300,000 records with 50 fields per record, and re-ordering
them on the fly in memory.

However, after putting much effort into this code, and wanting it to be
useful to others in the community, are there others who work with dbf
files that would need idx/cdx support?  Or tables so large they won't
fit comfortably into memory?

~ethan~


hi ethan,
great to hear that someone has finally written something for
interacting with vfp6 data,when do you plan to release it


Well, let's see...

A couple more days to have the datetime bit worked out (I don't support 
datetimes prior to 1981 in vfp tables),

longer for currency types, and of course, no idx/cdx support at this point.

Tell you what --  I'll trade you a copy of the code as it stands with 
date and datetime working for null values, for an answer of whether you 
need idx/cdx file support.  ;)


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


Re: Beginner trying to understand functions.

2008-12-08 Thread James Mills
On Tue, Dec 9, 2008 at 12:46 AM, Peter Otten [EMAIL PROTECTED] wrote:
 I think the OP is using Python 3.0. What used to cause trouble

Well of course he/she/it is!
I'm too blind to have noticed that! :)

--JamesMills


-- 
--
-- Problems are solved by method
--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner trying to understand functions.

2008-12-08 Thread cadmuxe
On 12月8日, 下午10时53分, James Mills [EMAIL PROTECTED]
wrote:
 On Tue, Dec 9, 2008 at 12:46 AM, Peter Otten [EMAIL PROTECTED] wrote:
  I think the OP is using Python 3.0. What used to cause trouble

 Well of course he/she/it is!
 I'm too blind to have noticed that! :)

 --JamesMills

 --
 --
 -- Problems are solved by method

oh,i think i should go to read the new document of py3k
thanks for all
--
http://mail.python.org/mailman/listinfo/python-list


appending values into array instead of a list

2008-12-08 Thread trias

Hi,
 I have this little script:
import csv
import numpy
signal=[]
ref=[]

for x in csv.reader(open('reffile.csv').readlines()):

ref.append(x)

for x in csv.reader(open('signalfile.csv').readlines()):

signal.append(x)

signalarray=numpy.array(signal, dtype=float)

signaldict={}

signaldict.update(dict(signalarray))

intarray=[0.0 for x in range(301)]

cntarray=[0 for x in range(301)]

for line in ref:

print line

locstr=line[1]

endstr=line[2]

loc=float(locstr)

end=float(endstr)

print loc

print end

i=0

while float(i) = 300.0:

if signaldict.has_key(end+float(i)):

expr=signaldict[end+float(i)]

print expr

intarray[i]+=expr

cntarray[i]+=1

y=i

i+=1

print intarray

print cntarray

fo=file('outfile.txt','w')
s=str(intarray)
fo.write(s)
fo.close()

So on the above I am appending values from signaldict indexed by i for every
object in the ref list. This way I calculate the sum of all values with
similar indexing i value. Would I be able to store the signaldict[i] for
every line individually in a multidimensional array?  

cheers
-- 
View this message in context: 
http://www.nabble.com/appending-values-into-array-instead-of-a-list-tp20896957p20896957.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Best way to run multiple Python processes without overloading CPU or disk i/o

2008-12-08 Thread Philip Semanchuk


On Dec 8, 2008, at 2:48 AM, Gabriel Genellina wrote:


En Wed, 03 Dec 2008 02:29:32 -0200, Philip Semanchuk
[EMAIL PROTECTED] escribió:



On Dec 2, 2008, at 11:21 PM, [EMAIL PROTECTED] wrote:


Is there a cross-platform way to launch multiple Python processes
and monitor CPU usage


os.getloadavg() might be useful. It certainly works on *nix, don't  
know about Windows. The documentation doesn't mention any platform  
limitations.


apart from saying Availability: Unix.? :)


Which just goes to show that Python is improving all the time. That's  
a fix that's present in the 2.6 documentation. I have 2.5 installed,  
and Availability: Unix is not in that doc:

http://www.python.org/doc/2.5/lib/os-path.html#l2h-2791



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


Re: A question about reference in Python.

2008-12-08 Thread Joe Strout

On Dec 7, 2008, at 10:26 PM, Group wrote:

Now, I want to write a Red-Black Tree, and a List structure. In C/C+ 
+, I can
use pointers to refer to  children  notes (or next notes). But, in  
Python, how

can I do it? Except the sequence, I know not any way.


Any variable in Python is a reference, which is roughly analogous to a  
pointer type in C/C++.  For details and examples, see:  http://www.strout.net/info/coding/valref/ 



Best,
- Joe


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


Re: Learning Python now coming from Perl

2008-12-08 Thread Roy Smith
In article [EMAIL PROTECTED],
 Nick Craig-Wood [EMAIL PROTECTED] wrote:
 
 My favourite mistake when I made the transition was calling methods
 without parentheses.  In perl it is common to call methods without
 parentheses - in python this does absolutely nothing!  pychecker does
 warn about it though.
 
   perl   - $object-method
   python - object.method()

On the other hand, leaving out the parens returns the function itself, 
which you can then call later.  I've often used this to create data-driven 
logic.

For example, I'm currently working on some code that marshals objects of 
various types to a wire protocol.  I've got something like:

encoders = {
   SM_INT: write_int,
   SM_SHORT: write_short,
   SM_FLOAT: write_float,
   # and so on
}

class AnyVal:
   def __init__(self, type, value):
  self.type = type
  self.value = value

def write_anyval(any):
   encoders[any.type](any.value)

The fact that functions are objects which can be assigned and stored in 
containers makes this easy to do.
--
http://mail.python.org/mailman/listinfo/python-list


Equivalent of 'wget' for python?

2008-12-08 Thread Robert Dailey
Hi,

I'm looking for a portable way to download ZIP files on the internet
through Python. I don't want to do os.system() to invoke 'wget', since
this isn't portable on Windows. I'm hoping the core python library has
a library for this. Note that I'll be using Python 3.0.

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


Re: Guido's new method definition idea

2008-12-08 Thread Christopher

 I'd like this new way of defining methods, what do you guys think?
 Anyone ready for writing a PEP?

I don't really see any advantage.  IMHO, it is not clearer, it is not
more concise, it makes the definition of class shared variables look
really out of place.  It also makes the new programmer wonder where
the function attaches if you *don't* specify self. I also give it a
-1.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Equivalent of 'wget' for python?

2008-12-08 Thread Diez B. Roggisch
Robert Dailey wrote:

 Hi,
 
 I'm looking for a portable way to download ZIP files on the internet
 through Python. I don't want to do os.system() to invoke 'wget', since
 this isn't portable on Windows. I'm hoping the core python library has
 a library for this. Note that I'll be using Python 3.0.

Module urllib2

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


Re: Equivalent of 'wget' for python?

2008-12-08 Thread Jean-Paul Calderone

On Mon, 08 Dec 2008 17:29:35 +0100, Diez B. Roggisch [EMAIL PROTECTED] 
wrote:

Robert Dailey wrote:


Hi,

I'm looking for a portable way to download ZIP files on the internet
through Python. I don't want to do os.system() to invoke 'wget', since
this isn't portable on Windows. I'm hoping the core python library has
a library for this. Note that I'll be using Python 3.0.


Module urllib2



There isn't such a module in Python 3.0.

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


Re: Equivalent of 'wget' for python?

2008-12-08 Thread r0g
Robert Dailey wrote:
 Hi,
 
 I'm looking for a portable way to download ZIP files on the internet
 through Python. I don't want to do os.system() to invoke 'wget', since
 this isn't portable on Windows. I'm hoping the core python library has
 a library for this. Note that I'll be using Python 3.0.
 
 Thanks.


urllib.urlretrieve(url_of_zip_file, destination_on_local_filesystem).

There's also a third argument you can use to link a progress update
function of your choosing if you need it.


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


Calling C# COM (.NET) from python

2008-12-08 Thread Andrew Falanga
Hi,

I've never programmed in python and only have a small understanding of
what is wrapped up in the terms COM and .NET.  Is there a way of using
python to get a hold of objects written in C# as COM objects using
python?  I'm looking for ways to avoid VBScript (which, after a couple
of weeks, I've determined to be horrid).  That is, is there a way of
getting at COM objects in python that's similar to doing a
CreateObject call in VBScript (http://msdn.microsoft.com/en-us/library/
dcw63t7z.aspx)?

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


Re: Guido's new method definition idea

2008-12-08 Thread anthony . tolle
On Dec 6, 4:15 pm, Carl Banks [EMAIL PROTECTED] wrote:
 On Dec 6, 12:47 am, Patrick Mullen [EMAIL PROTECTED] wrote:

  Could I do something like this:

  def a.add(b): return a+b

  Outside of a class?  Of course then that makes you think you could do
  5.add(6) or something crzy like that.  (I mean, you can do
  (5).__add__(6) but that's something else entirely)

 I'd be inclined to think that this defines an instancemethod on an
 existing object a.  In other word, I'd read the following two lines as
 more or less equivalent.

 def a.add(b): return a+b

 a.add = lambda b: a+b

 Just as the following are equivalent:

 def foo(): return bar

 foo = lambda: bar

 I had been -0 on this, but now I think I'm -1.

This brings up another question, what would one use when referencing
method names inside the class definition?:

class C:
def self.method(arg):
self.value = arg
def self.othermethod(arg):
self.value = arg
# do this?
funcs = (self.method, self.othermethod)
# or this?
funcs = (method, othermethod)

On another related note, I would be interested in seeing this syntax
adopted for a different purpose...

Normally, if I'm defining a nested function that needs to be stored as
an object attribute, I have to use a dummy name, like the following:

class C:
def createfunc(self, arg):
def _dummy(arg):
 return arg + 1
self.func = _dummy

It would be nice to be able to do the following instead:

class C:
def createfunc(self):
def self.func(arg):
return arg + 1

Or, after the class definition is done, to extend it dynamically:

def C.method(self, arg):
self.value = arg

...which would be the equivalent of the following:

def method(self, arg):
self.value = arg
C.method = method

Since functions are first-class objects, it seems perfectly reasonable
to me.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Guido's new method definition idea

2008-12-08 Thread anthony . tolle
On Dec 6, 4:15 pm, Carl Banks [EMAIL PROTECTED] wrote:
 On Dec 6, 12:47 am, Patrick Mullen [EMAIL PROTECTED] wrote:

  Could I do something like this:

  def a.add(b): return a+b

  Outside of a class?  Of course then that makes you think you could do
  5.add(6) or something crzy like that.  (I mean, you can do
  (5).__add__(6) but that's something else entirely)

 I'd be inclined to think that this defines an instancemethod on an
 existing object a.  In other word, I'd read the following two lines as
 more or less equivalent.

 def a.add(b): return a+b

 a.add = lambda b: a+b

 Just as the following are equivalent:

 def foo(): return bar

 foo = lambda: bar

 I had been -0 on this, but now I think I'm -1.

This brings up another question, what would one use when referencing
method names inside the class definition?:

class C:
def self.method(arg):
self.value = arg
def self.othermethod(arg):
self.value = arg
# do this?
funcs = (self.method, self.othermethod)
# or this?
funcs = (method, othermethod)

On another related note, I would be interested in seeing this syntax
adopted for the very purpose Carl hinted at...

Normally, if I'm defining a nested function that needs to be stored as
an object attribute, I have to use a dummy name, like the following:

class C:
def createfunc(self, arg):
def _dummy(arg):
 return arg + 1
self.func = _dummy

It would be nice to be able to do the following instead:

class C:
def createfunc(self):
def self.func(arg):
return arg + 1

Or, after the class definition is done, to extend it dynamically:

def C.method(self, arg):
self.value = arg

...which would be the equivalent of the following:

def method(self, arg):
self.value = arg
C.method = method

Since functions are first-class objects, it seems perfectly reasonable
to me.
--
http://mail.python.org/mailman/listinfo/python-list


SQLObject 0.9.9

2008-12-08 Thread Oleg Broytmann
Hello!

I'm pleased to announce version 0.9.10, a minor bugfix release of 0.9 branch
of SQLObject.


What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite,
Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB).


Where is SQLObject
==

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://cheeseshop.python.org/pypi/SQLObject/0.9.9

News and changes:
http://sqlobject.org/News.html


What's New
==

News since 0.9.8


* Backported from the trunk: under MySQL use the connection's dbEncoding
  instead of ascii, when converting a unicode value from python to database
  for a StringCol.

* Fixed createSQL constrains generation under MySQL when the table's name
  includes the database's name (contains a dot).

For a more complete list, please see the news:
http://sqlobject.org/News.html

Oleg.
-- 
 Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED]
   Programmers don't die, they just GOSUB without RETURN.
--
http://mail.python.org/mailman/listinfo/python-list


SQLObject 0.10.4

2008-12-08 Thread Oleg Broytmann
Hello!

I'm pleased to announce version 0.10.4, a minor bugfix release of 0.10 branch
of SQLObject.


What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite,
Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB).


Where is SQLObject
==

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://cheeseshop.python.org/pypi/SQLObject/0.10.4

News and changes:
http://sqlobject.org/News.html


What's New
==

News since 0.10.3
-

* Fixed createSQL constrains generation under MySQL when the table's name
  includes the database's name (contains a dot).

For a more complete list, please see the news:
http://sqlobject.org/News.html

Oleg.
-- 
 Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED]
   Programmers don't die, they just GOSUB without RETURN.
--
http://mail.python.org/mailman/listinfo/python-list


Python-URL! - weekly Python news and links (Dec 8)

2008-12-08 Thread Gabriel Genellina
QOTW:  To the pure, everything, properly described, is pure ;-) - Bengt
Richter


The final version of Python 3.0 was released last Wednesday, jointly
with 2.6.1 - congratulations!
http://groups.google.com/group/comp.lang.python/t/f92e7e2db667d903/

Implementing lazy properties:
http://groups.google.com/group/comp.lang.python/t/ce1d75c31a6e2df1/

Overriding __special__ methods at the instance level:
http://groups.google.com/group/comp.lang.python/t/3442c5004de0d411/

Strategy to develop libraries both for 2.x and 3.x
http://groups.google.com/group/comp.lang.python/t/ee4f9e645e5f41d0/

Guidelines for designing a project's structure on disk:
http://groups.google.com/group/comp.lang.python/t/e8dd7109df5f61b2/

A detective story: a hard-to-find bug regarding how 3.0 reads
UTF16-encoded files:
http://groups.google.com/group/comp.lang.python/t/ae1bc6660a6b2c5f/

When translated into Python, a Perl example about closures shows
a few differences between 2.5 and 3.0:
http://groups.google.com/group/comp.lang.python/t/5c6734bc5181af6a/

Learning Python for Perl programmers:
http://groups.google.com/group/comp.lang.python/t/d2abcb3e75c5f041/

An alternative syntax for defining methods (moving self out of the
argument list):
http://groups.google.com/group/comp.lang.python/t/5457b8649040f7ea/

as is now a keyword (2.6); that breaks some existing code, and angers
several people:
http://groups.google.com/group/comp.lang.python/t/e9ffe83fcf4b0af0/

3.0 file read/write is slow and not as optimized as 2.x:
http://groups.google.com/group/comp.lang.python/t/6c4d3a2d678c1eba/
http://groups.google.com/group/comp.lang.python/t/9046eee09137c657/



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Papers aims to publish the efforts of Python enthusiats:
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the Planet sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.
http://groups.google.com/group/comp.lang.python.announce/topics

Python411 indexes podcasts ... to help people learn Python ...
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donations/

The Summary of Python Tracker Issues is an automatically generated
report summarizing new bugs, closed ones, and patch submissions. 

http://search.gmane.org/?author=status%40bugs.python.orggroup=gmane.comp.python.develsort=date

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://code.activestate.com/recipes/langs/python/

Many Python conferences around the world are in preparation.
Watch this space for links to them.

Among several Python-oriented RSS/RDF feeds available, see:
http://www.python.org/channews.rdf
For more, see:
http://www.syndic8.com/feedlist.php?ShowMatch=pythonShowStatus=all
The old 

Re: Guido's new method definition idea

2008-12-08 Thread anthony . tolle
On Dec 8, 12:01 pm, [EMAIL PROTECTED] wrote:

 It would be nice to be able to do the following instead:

 class C:
     def createfunc(self):
         def self.func(arg):
             return arg + 1


The above example should have read as follows:

class C:
def createfunc(self, arg):
def self.func(arg):
return arg + 1

-

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


Re: Calling C# COM (.NET) from python

2008-12-08 Thread Ben Kaplan



On Dec 8, 2008, at 11:53 AM, Andrew Falanga [EMAIL PROTECTED] wrote:


Hi,

I've never programmed in python and only have a small understanding of
what is wrapped up in the terms COM and .NET.  Is there a way of using
python to get a hold of objects written in C# as COM objects using
python?  I'm looking for ways to avoid VBScript (which, after a couple
of weeks, I've determined to be horrid).  That is, is there a way of
getting at COM objects in python that's similar to doing a
CreateObject call in VBScript (http://msdn.microsoft.com/en-us/ 
library/

dcw63t7z.aspx)?

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


I would not deal with COM at all. I personally have not used it, but  
there is a version of python called IronPython that's written in C#,  
so it can use .NET and, I think, other C# objects. Other people will  
probably help you more, but you might want to look into that and maybe  
ask this on the python-win list.

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


Re: [Py2exe-users] py2exe 0.6.9 released

2008-12-08 Thread Pascal
On Mon, 08 Dec 2008 14:47:13 +, Pascal wrote:

 On Mon, 17 Nov 2008 12:39:36 +, Pascal wrote:
 
 On Sun, 16 Nov 2008 21:23:59 -0500, Chris Spencer wrote:
 
 After I compile my program with py2exe 0.6.9 with Python 2.6, I'm
 still getting the Application Did Not Initialize Properly error
 dialog whenever I run my code.  What am I doing wrong?
 
 I have exactly the same problem.
 I have tried just anything I could think of to no avail : Copied the 3
 msvc_90.dll to the system32 subdir of Windows, to the directory of my
 application, reinstalled the whole Microsoft Visual C++ 2008
 Redistributable Package, embedded the manifest data into the exe or
 kept it in a .manifest file...
 Could not make it work. Always got the Application Did Not Initialize
 Properly message.
 I'm with Windows XP SP3. I tried all this on 2 different systems and I
 got the same results.
 
 
 I think I narrowed down a little bit the problem. It's not the common
 one when the msvc_90.dll are not located, though the result is similar.
 The problem is when you try to generate at least 2 exe in one setup
 (with 2 scripts specified in the windows command of the setup). This
 works OK with py2exe 0.6.9 for Python 2.5, but fails with Python 2.6
 (and 2.6.1). None of the generated exe can be started. When I compare
 the content of library.zip in both versions, this file doesn't contain
 any .pyc for the scripts you want to generate an exe for with Python
 2.5, but always contains a .pyc for one of the scripts you want to
 generate an .exe for with Python 2.6. Don't know if it's a clue for
 finding a fix.
 I have tested many ways to figure this out but I can't find any solution
 for the moment so I'm sticking with Python 2.5.

Got it !
If you want to generate an exe for a script of your own named abc.py, 
rename it because this will never work with that original name. The 
reason seems to be an abc.pyc file compiled by default by Python 2.6 and 
included in library.zip (abc stands in this case for Abstract Base 
Classes), and using this name for your own script makes nothing work ! 
--
http://mail.python.org/mailman/listinfo/python-list


Re: Calling C# COM (.NET) from python

2008-12-08 Thread Mike Driscoll
On Dec 8, 10:53 am, Andrew Falanga [EMAIL PROTECTED] wrote:
 Hi,

 I've never programmed in python and only have a small understanding of
 what is wrapped up in the terms COM and .NET.  Is there a way of using
 python to get a hold of objects written in C# as COM objects using
 python?  I'm looking for ways to avoid VBScript (which, after a couple
 of weeks, I've determined to be horrid).  That is, is there a way of
 getting at COM objects in python that's similar to doing a
 CreateObject call in VBScript (http://msdn.microsoft.com/en-us/library/
 dcw63t7z.aspx)?

 Thanks,
 Andy

You're probably looking for the PyWin32 package (AKA: Python for
Windows extensions). It's an external package for Python created
mainly by Mark Hammond. You can find it here: 
http://sourceforge.net/projects/pywin32/

It's a loose wrapper to the win32 bindings. It has a win32com module
in it. You can usually take some VB type code and tweak it slightly to
work with Python. There's some docs here:

http://docs.activestate.com/activepython/2.4/pywin32/win32_modules.html

You may also be able to use ctypes. Regardless, the PyWin32 package
has a great mailing list with helpful people that I highly recommend:
http://mail.python.org/mailman/listinfo/python-win32

Other than that, you have the option of using IronPython which can
actually import .NET modules itself. I've messed with it a little, but
I'm not fluent enough in .NET to be able to use a lot of its
capabilities. Regardless, you should read up on it as it offers lots
of interesting capabilities:

http://www.codeplex.com/IronPython

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


Re: Guido's new method definition idea

2008-12-08 Thread Ben Kaplan



On Dec 8, 2008, at 11:59 AM, [EMAIL PROTECTED] wrote:


On Dec 6, 4:15 pm, Carl Banks [EMAIL PROTECTED] wrote:

On Dec 6, 12:47 am, Patrick Mullen [EMAIL PROTECTED] wrote:


Could I do something like this:



def a.add(b): return a+b


Outside of a class?  Of course then that makes you think you could  
do

5.add(6) or something crzy like that.  (I mean, you can do
(5).__add__(6) but that's something else entirely)


I'd be inclined to think that this defines an instancemethod on an
existing object a.  In other word, I'd read the following two lines  
as

more or less equivalent.

def a.add(b): return a+b

a.add = lambda b: a+b

Just as the following are equivalent:

def foo(): return bar

foo = lambda: bar

I had been -0 on this, but now I think I'm -1.


This brings up another question, what would one use when referencing
method names inside the class definition?:

class C:
   def self.method(arg):
   self.value = arg
   def self.othermethod(arg):
   self.value = arg
   # do this?
   funcs = (self.method, self.othermethod)
   # or this?
   funcs = (method, othermethod)

On another related note, I would be interested in seeing this syntax
adopted for a different purpose...

Normally, if I'm defining a nested function that needs to be stored as
an object attribute, I have to use a dummy name, like the following:

class C:
   def createfunc(self, arg):
   def _dummy(arg):
return arg + 1
   self.func = _dummy

It would be nice to be able to do the following instead:

class C:
   def createfunc(self):
   def self.func(arg):
   return arg + 1

Or, after the class definition is done, to extend it dynamically:

def C.method(self, arg):
   self.value = arg

...which would be the equivalent of the following:

def method(self, arg):
   self.value = arg
C.method = method

Since functions are first-class objects, it seems perfectly reasonable
to me.
--
http://mail.python.org/mailman/listinfo/python-list


I agree, this would be much nicer and would not require any special  
cases. I'm not convinced that this is needed, but at least this won't  
confuse newbies as much.

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


Re: Mathematica 7 compares to other languages

2008-12-08 Thread Xah Lee
On Dec 8, 5:10 am, Jon Harrop [EMAIL PROTECTED] wrote:
 Xah Lee wrote:
  For those interested in this Mathematica problem, i've now cleaned up
  the essay with additional comments here:

  • A Mathematica Optimization Problem
   http://xahlee.org/UnixResource_dir/writ/Mathematica_optimization.html

 In that article you say:

  Further, if Intersect is made to take a flat sequence of argument as
  in “Intersect[o_, d_, lambda_, n_, c_, r_, s_]”, then pattern matching can
  be avoided by making it into a pure function “Function”. And when it is
  a “Function”, then Intersect or part of it may be compiled with Compile.
  When the code is compiled, the speed should be a order of magnitude
  faster.

 That is incorrect. Mathematica's Compile function cannot handle recursive
 functions like Intersect.

i didn't claim it can. You can't expect to have a fast or good program
if you code Java style in a functional lang.

Similarly, if you want code to run fast in Mathematica, you don't just
slap in your OCaml code into Mathematica syntax and expect it to work
fast.

If you are a Mathematica expert, you could make it recurse yet have
the speed as other langs. First, by changing your function's form, to
avoid pattern matching, and rewrite your bad recursion. That is what i
claimed in the above paragraph. Read it again to see.

 For example:
 In[1]:= Compile[{n_, _Integer}, If[# == 0, 1, #0[[# n - 1]] #1] [n]]

 During evaluation of In[1]:= Compile::fun: Compilation of
 (If[#1==0,1,#0[[#1 n-1]] #1])[Compile`FunctionVariable$435] cannot
 proceed. It is not possible to compile pure functions with arguments
 that represent the function itself. 

Mathematica's Compile function is intended to speed up numerical
computation. To want Compile to handle recursion in the context of
Mathematica's programing features, is not something possible even in
theoretical sense.

Scheme lisp implementations can compile recursive code, but lisp is a
lower level lang than Mathematica, where perhaps the majority of
Mathematica's builtin functions can equate to 10 or more lines of
lisp, and any of its hundreds math functions equates to entire
libraries of other langs. It is reasonable, but silly, to expect
Mathematica's Compile function to compile any code in Mathematica.

Perhaps in the future version of Mathematica, its Compile function can
handle basic recursive forms.

Also, in this discussion, thanks to Thomas M Hermann's $20 offered to
me for my challenge to you, that i have taken the time to show working
code that demonstrate many problems in your code. Unless you think my
code and replies to you are totally without merit or fairness, but
otherwise you should acknowledge it, in whole or in parts you agree,
in a honest and wholehearted way, instead of pushing on with petty
verbal fights.

  Xah
∑ http://xahlee.org/

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


Re: How to Write to csv file to create bulk address book

2008-12-08 Thread r0g
k.i.n.g. wrote:
 Hi ,
 
 I am new to scripting, I am working on script which would  create 'n'
 number address book entries into a csv file which would be used to
 import into a address book. I need suggestions for the same
 
 The fileds for csv file are as follows
 
 Title,First Name,Middle Name,Last
 Name,Suffix,Company,Department,Job Title,Business
 Street,Business Street 2,Business Street 3,Business
 City,Business State,Business Postal Code,Business Country,Home
 Street,Home Street 2,Home Street 3,Home City,Home State,Home
 Postal Code,Home Country,Other Street,Other Street 2,Other
 Street 3,Other City,Other State,Other Postal Code,Other
 Country,Assistant's Phone,Business Fax,Business Phone,Business
 Phone 2,Callback,Car Phone,Company Main Phone,Home Fax,Home
 Phone,Home Phone 2,ISDN,Mobile Phone,Other Fax,Other
 Phone,Pager,Primary Phone,Radio Phone,TTY/TDD
 Phone,Telex,Account,Anniversary,Assistant's Name,Billing
 Information,Birthday,Business Address PO
 Box,Categories,Children,Directory Server,E-mail Address,E-
 mail Type,E-mail Display Name,E-mail 2 Address,E-mail 2 Type,E-
 mail 2 Display Name,E-mail 3 Address,E-mail 3 Type,E-mail 3
 Display Name,Gender,Government ID Number,Hobby,Home Address PO
 Box,Initials,Internet Free
 Busy,Keywords,Language,Location,Manager's
 Name,Mileage,Notes,Office Location,Organizational ID
 Number,Other Address PO
 Box,Priority,Private,Profession,Referred
 By,Sensitivity,Spouse,User 1,User 2,User 3,User 4,Web
 Page
 
 All the entries written by csv file by script can be random  dummy as
 this address book is used for testing purpose.
 
 
 Thank you in advance,
 Kanthi


Hi Kanthi, the simple case is to make yourself a list of the fields. For
each field specify what type of data to generate and a lower and upper
bound for it's length/value.

fields = [ (Title, txt, 0, 4),
   (First, txt, 0, 40),
   (Tel, num, 8, 15)
   etc...]

Then repeatedly loop though that list generating random values of the
appropriate type and appending them to another list to build records.

import random

new_record = []
for each_field in fields:

  if each_field[1] == txt:
r = random.randint( each_field[2], each_field[3] )
new_record.append( r )

  elif each_field[1] == num:
r = random.randint( each_field[2], each_field[3] )
s = .join( [random.choice(qwerty...etc.) for i in range( r )] )
new_record.append( s )

print new_record()

Then basically make a big list of these records and squirt them out to
file. You might need read up on the random, csv and copy modules and
you'll probably want to expand on the data types it can generate.

Also I use the following class to choose random words from a specified
word list...

class WordList:
  def __init__(self, dictionary_filename):
self.dictionary_list = []
f = open(dictionary_filename,'r')
for each in f:
  #print each
  self.dictionary_list.append(each.rstrip())
f.close()
self.dictionary_length = len(self.dictionary_list)

  def random(self,x):
outlist = []
for each in range(0,x):
  outlist.append(self.dictionary_list[random.randrange(0,
self.dictionary_length-1)])
return ' '.join(outlist)


This would allow you to say:

firstnames = Wordlist('big_list_of_first_names.txt')

name = firstnames.random(1)

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


Re: datetime and the rich-companison operators

2008-12-08 Thread Chris Rebert
On Sun, Dec 7, 2008 at 11:41 PM, Ethan Furman [EMAIL PROTECTED] wrote:
 Greetings All!

 I am implementing a NullDate class in order to mirror dates and datetimes
 that have no value  (yes, this is for my dbf  module :)

 I'm still a bit fuzzy about class methods, hashing, and __new__, but my
 question of the moment is this:  it seems to me that with two dates or
 datetimes, they should either be equal, or one should precede the other, and
 this can be accomplished quite handily with __cmp__... so does anyone know
 why the rich comparisons were used in the datetime module? Was it simply a
 style choice, or is something being handled that __cmp__ couldn't cope with?

Probably because __cmp__ was removed in Python 3.0, thus requiring the
use of the rich comparison methods in its place.
See the earlier thread entitled Python 3 __cmp__ semantic change?.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com


 Thanks in advance!
 ~ethan~
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Equivalent of 'wget' for python?

2008-12-08 Thread Jerry Hill
On Mon, Dec 8, 2008 at 11:53 AM, r0g [EMAIL PROTECTED] wrote:
 urllib.urlretrieve(url_of_zip_file, destination_on_local_filesystem).

In python 3.0, that appears to be:

import urllib.request
urllib.request.urlretrieve(url, local_file_name)

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


Re: Equivalent of 'wget' for python?

2008-12-08 Thread Diez B. Roggisch
Jean-Paul Calderone wrote:

 On Mon, 08 Dec 2008 17:29:35 +0100, Diez B. Roggisch
 [EMAIL PROTECTED] wrote:
Robert Dailey wrote:

 Hi,

 I'm looking for a portable way to download ZIP files on the internet
 through Python. I don't want to do os.system() to invoke 'wget', since
 this isn't portable on Windows. I'm hoping the core python library has
 a library for this. Note that I'll be using Python 3.0.

Module urllib2

 
 There isn't such a module in Python 3.0.

If you knew that urllib2 has been removed/integrated/whatever into urllib,
it would have helped to mention that, don't you think?

To the OP: urllib.request.urlopen is your friend.

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


  1   2   3   4   >