Re: a type without a __mro__?

2005-02-06 Thread Alex Martelli
John Lenton <[EMAIL PROTECTED]> wrote:

> class C(type):
>   def __getattribute__(self, attr):
> if attr == '__mro__':
>   raise AttributeError, "What, *me*, a __mro__? Nevah!"
> return super(C, self).__getattribute__(attr)
> 
> class D(object):
>   __metaclass__ = C

Yay -- *exactly*!!!  This simple trick reproduces the problem AND shows
that using inspect.getmro fixes it.  EXACTLY what we needed.  Thanks!!!
Now I can make a proper patch with unittest as well as the fix.


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


Re: bytecode obfuscation

2005-02-06 Thread Adam DePrince
On Thu, 2005-02-03 at 16:58, Jarek Zgoda wrote:
> snacktime napisał(a):
> 
> > Everything except the libraries that actually connect to the
> > bank networks would be open source, and those libraries aren't
> > something that you would even want to touch anyways.
> 
> This sounds suspicious to me. Really. Normal payment clearance programs 
> have open-spec API's.

Dare I suggest that closed source is a plea for rounding fraud?

No amount of obfuscation is going to help you.  Just look at the battles
between virii authors and anti-virus software firms.  Even as early as
the 80's, viruses were employing elaborate encryption schemes to "hide"
from virus scanners; virus scanners in return emulated the cpu for the
first couple thousand cycles in hopes of finishing the decryption and
seeing the virus.  Of course, virus authors responded with
for(x=0;x<100;x++) and the halting problem inspired game of chicken
raged on ... the difference with your situation is if somebody is using
obscurity as a form of security, then it means that your system is
reachable, and it is only a matter of money and time before the
obscurity becomes not very obscure.  

My humble recommendation is to put your efforts into educating those you
work with that if they secure their communication channel  it won't
matter if the protocol spec leaks to the world.  Your adversary won't
have an opportunity to talk to your service no matter how good their
implementation of your protocol.

The worst case if you depend on obscurity:  The bad guys are rounding
off your pennies as you read this.

The worse case if you depend on encryption and open your spec:  You get
to publish your code, but might get competition.

Just my $0.02.

Adam DePrince 


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


Re: pickle/marshal internal format 'life expectancy'/backward compatibility

2005-02-06 Thread Adam DePrince
On Sat, 2005-02-05 at 17:04, Tim Peters wrote:
> [Philippe C. Martin]
> > I am looking into using the pickle format to store object/complex data
> > structures into a smart card as it would make the design of the embedded
> > application very simple.
> >
> > Yet the card might have to stay in the pocket of the customer for a few
> > years, during which the back office application responsible for
> > retrieving the information from the card might evolve as well as the
> > python release it relies upon.
> >
> > Is there a commitment for python releases to be able to interpret
> > 'older' pickle/marshal internal formats ?
> 
> Pickle and marshal have nothing in common, and there's no
> cross-release guarantee about marshal behavior.  Pickles are safe in
> this respect; indeed, each Python released to date has been able to
> load pickles created by all earlier Python releases.  Of course a
> pickle produced by a later Python may not be loadable by an earlier
> Python, although even in that direction you can get cross-release
> portability by forcing the newer Python to restrict itself to produce
> obsolete pickle formats.  Reading Lib/pickletools.py in a current
> release will explain all this.


How complicated is your data structure?  Might you just store:

repr(  )

and eval it later?  Trust is an issue; you are vulnerable to malicious
code, but no more so than with pickle or marshal.

One quick and dirty way to be a little safer is to "sign" the data you
store.

# To save your data
import sha
import cPickle
mysecret = "abc"
mydata = {"what":"my data structure"}
f = open( "/tmp/myfile.txt", "w+" )
mydata = cPickle.dumps( mydata, protocol=0 )
# I'm assuming this is a flash device ... lets be safe and not assume
# that write is buffered ... 
f.write( sha.new( mysecret + mydata ).digest() + mydata)



# To load your data
import sha
import cPickle
mysecret = "abc
f = open( "/tmp/myfile.txt", "w+" )
hash = f.read( sha.digest_size )
mydata = f.read()
if sha.new( mysecret + mydata ).digest() != hash:
raise "Somebody is tring to hack you!" 
mydata = cPickle.loads( mydata )

Of course, the security of this scheme is dependent on a lot, including
the strength of sha, your ability to keep your secret key secret, the
correctness of what I'm saying, etc etc etc.




Adam DePrince 


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


Re: Multiple constructors

2005-02-06 Thread Leif K-Brooks
Philip Smith wrote:
I don't seem to be able to define multiple versions of __init__ in my matrix 
class (ie to initialise either from a list of values or from 2 dimensions 
(rows/columns)).
You could either use an if statement with *args:
class Matrix(object):
def __init__(self, *args):
if len(args) == 1:
# Initialize from list of values
elif len(args) == 2:
# Initialize from rows/columns
else:
raise TypeError("Constructor accepts 1 or 2 arguments.")
Or with two different functions:
class Matrix(object):
def __init__(self, values):
# Initialize from a list of values
@classmethod
def from_pair(self, rows, columns):
return Matrix([rows, columns]) # Or with the right argument
--
http://mail.python.org/mailman/listinfo/python-list


Re: bicyclerepairman python24 windows idle :(

2005-02-06 Thread EuGeNe
Kim Changjune wrote:
EuGeNe wrote:
Hi there,
I am no expert but wanted to give bicyclerepairman 0.9 a go just to
see
what a refactoring browser is and does. Followed every step of the
install, I think, but idle doesn't start with the RepairMan section
in
config-extensions.def ... is it incompatible with 2.4?
Thanks for your help.
--
EuGeNe

There seems to be a change in idlelib in Python 2.4.
Apply following patch to BicycleRepairMan_Idle.py:
@@ -87,6 +87,7 @@
 mbar = editwin.menubar
 editwin.menudict[name] = menu = Menu(mbar, name = name)
 mbar.add_cascade(label = label, menu = menu, underline =
underline)
+self.editwin.fill_menus(self.menudefs)
 # Initialize Bicyclerepairman and import the code
 path = self.editwin.io.filename
thanks for the tip ... unfortunately it doesn't work either. IDLE 
doesn't start.

--
EuGeNe
[
www.boardkulture.com
www.actiphot.com
www.xsbar.com
]
--
http://mail.python.org/mailman/listinfo/python-list


Re: bicyclerepairman python24 windows idle :(

2005-02-06 Thread EuGeNe
Kim Changjune wrote:
EuGeNe wrote:
Hi there,
I am no expert but wanted to give bicyclerepairman 0.9 a go just to
see
what a refactoring browser is and does. Followed every step of the
install, I think, but idle doesn't start with the RepairMan section
in
config-extensions.def ... is it incompatible with 2.4?
Thanks for your help.
--
EuGeNe

There seems to be a change in idlelib in Python 2.4.
Apply following patch to BicycleRepairMan_Idle.py:
@@ -87,6 +87,7 @@
 mbar = editwin.menubar
 editwin.menudict[name] = menu = Menu(mbar, name = name)
 mbar.add_cascade(label = label, menu = menu, underline =
underline)
+self.editwin.fill_menus(self.menudefs)
 # Initialize Bicyclerepairman and import the code
 path = self.editwin.io.filename
sorry but it didn't make any difference ... idle doens't start :(
--
EuGeNe
[
www.boardkulture.com
www.actiphot.com
www.xsbar.com
]
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to read POSTed data

2005-02-06 Thread Pierre Quentel
Here is an example of how to get the POST data :
#def do_POST(self):
#ctype, pdict = 
cgi.parse_header(self.headers.getheader('content-type'))
#length = int(self.headers.getheader('content-length'))
#if ctype == 'multipart/form-data':
#self.body = cgi.parse_multipart(self.rfile, pdict)
#elif ctype == 'application/x-www-form-urlencoded':
#qs = self.rfile.read(length)
#self.body = cgi.parse_qs(qs, keep_blank_values=1)
#else:
#self.body = {}   # Unknown content-type
## throw away additional data [see bug #427345]
#while select.select([self.rfile._sock], [], [], 0)[0]:
#if not self.rfile._sock.recv(1):
#break
#self.handle_data()

where handle_data() is the method where you will process the data received
The part related to bug #427345 is copied from CGIHTTPServer
For an example of use you can take a look at the CustomHTTPServer in 
Karrigell (http://karrigell.sourceforge.net)

A+,
Pierre
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple constructors

2005-02-06 Thread vincent wehren
Philip Smith wrote:
Call this a C++ programmers hang-up if you like.
I don't seem to be able to define multiple versions of __init__ in my matrix 
class (ie to initialise either from a list of values or from 2 dimensions 
(rows/columns)).

Even if Python couldn't resolve the __init__ to use on the basis of argument 
types surely it could do so on the basis of argument numbers???

At any rate - any suggestions how I code this
Checking the number of arguments ain't all that hard:
class Klass:
   def __init__(*args):
   self.args = args
   if len(self.args) == 1:
   # etc.
This feels rather unpythonic, though. Maybe you could use factory 
functions, forgetting about  __init__ all together (2.2 or higher):

class Klass(object):
def fromList(seq):
result = Klass()
# populate attributes here
# and return the requested object
return result
fromList = staticmethod(fromList)
def fromDimensions(cols, rows):
result = Klass()
# populate attributes here
# and return the requested object
return result
   fromDimensions = staticmethod(fromDimensions)
   #more methods  here
k = Klass.fromList(seq)
etc..
Regards
--
Vincent Wehren



Thanks
Phil 


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


Re: [EVALUATION] - E01: The Java Failure - May Python Helps?

2005-02-06 Thread Terry Reedy

"Ilias Lazaridis" <[EMAIL PROTECTED]> wrote in message

>> Then 'print html_doc_instance' can print the html doc corresponding to 
>> the object model.
>
> I understand this procedure.
>
> I would like to use a standard way, which uses the standard metadata 
> [implicit/explicit defined].
>
> Does such standard exist?

I am not sure of what *you* mean by 'standard way'.  That is probably 
because Python and the community is not big on 'standard ways' other than 
what is specified in the two reference manuals.  And even then, Python is 
intentionally flexible in various ways (though not all).  So the answer to 
your question is probably 'no'.

Terry J. Reedy



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


Re: Word for a non-iterator iterable?

2005-02-06 Thread vincent wehren
Leif K-Brooks wrote:
Is there a word for an iterable object which isn't also an iterator, and 
therefor can be iterated over multiple times without being exhausted? 
"Sequence" is close, but a non-iterator iterable could technically 
provide an __iter__ method without implementing the sequence protocol, 
so it's not quite right.
How about 'reiterable'?
--
Vincent Wehren
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple constructors

2005-02-06 Thread Leif K-Brooks
Leif K-Brooks wrote:
@classmethod
def from_pair(self, rows, columns):
return Matrix([rows, columns]) # Or with the right argument
Er... I'm not sure why I named that argument "self", it should be "cls" 
if you don't want to  confuse anyone reading your code.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple constructors

2005-02-06 Thread Terry Reedy

"Philip Smith" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Call this a C++ programmers hang-up if you like.
>
> I don't seem to be able to define multiple versions of __init__ in my 
> matrix

Correct.

> class (ie to initialise either from a list of values or from 2 dimensions 
> (rows/columns)).
>
> Even if Python couldn't resolve the __init__ to use on the basis of 
> argument types surely it could do so on the basis of argument numbers???

Variable parameter counts are handled either with default values or the 
*restlist and **keydict mechanisms.

Keep in mind that the compiler cannot, in general, know, at compile time, 
what function object will be bound to a name at run time.  And that you can 
have only bind a name to one object.

> At any rate - any suggestions how I code this

The usual way is to write your own dispatch code to either execute the 
appropriate code block or call the appropriate function.

Or you could write a function of functions that returns a function that 
dispatches to one of the functions according to its arg count.  Something 
like (untested, all exceptions passed through):

def arg_count_dispatcher_maker(*funcs):
def arg_count_dispatcher(*args):
return funcs[len(args)](*args)
return arg_count_dispatcher

which you use like this:
__init__ = arg_count_dispatcher_maker(func0, func1, func2)

Terry J. Reedy 



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


Re: Multiple constructors

2005-02-06 Thread Alex Martelli
Philip Smith <[EMAIL PROTECTED]> wrote:

> Call this a C++ programmers hang-up if you like.
> 
> I don't seem to be able to define multiple versions of __init__ in my matrix

Indeed, you can never define ``multiple versions'' of the same name in
the same scope: one scope + one name -> one object.

That's what a name (in a given scope, which I won't keep repeating)
MEANS -- in Python as well as in common sense.

> class (ie to initialise either from a list of values or from 2 dimensions
> (rows/columns)).
> 
> Even if Python couldn't resolve the __init__ to use on the basis of argument
> types surely it could do so on the basis of argument numbers???

It could, if it didn't think a name is a name is a name.  By sticking to
resolution JUST BY NAME, instead of by name plus who knows what else,
however, Python gains a lot of conceptual simplicity without any loss of
functionality.  Therefore, it's a great design choice.


> At any rate - any suggestions how I code this

My preferred suggestion is to accept that one name === one object: you
want two different objects (constructors), give them two different
names.  One, if you wish, can be __init__ -- the other could be a
staticmethod or even better a classmethod.  Or, have two named methods.

class Matrix(object):
def __init__(self, values):
" init self from values "
@classmethod
def withDimensions(cls, x, y):
return cls([0.0]*x for i in xrange(y))
@classmethod
def fromValues(cls, values):
return cls(values)

Now, Matrix.withDimensions(3, 4) and Matrix.fromValues([[1,2],[3,4]])
are both available and maximally clear, and the latter you can also call
as Matrix([[1,2],[3,4]]) if you wish.  The advantage of using
classmethod is that if you later go and subclass

class SpecialMatrix(Matrix):
   ...

you can call the classmethods on this subclass and get an instance of
the subclass, which can sometimes be handy -- better than using
staticmethods (or factory functions ``outside the class'') and
``hardwiring'' what class they instantiate.


I don't particularly like the concept of a function or method which does
drastically different things -- I'd rather see one function have ONE
function (taking the second repetition as meaning ``role'', ``task'').
This goes for __init__, too.  Still, if you're keen on the idea, you can
of course have your __init__ take optional arguments, check their
presence and/or type, and whatever other devilry; I just think it's not
a very good design, but it does end up with just the same effect as C++
overloaded constructors, which you seem to like.  If you want to do this
all the time, you could even build appropriate infrastructure for this
task -- a little custom descriptor and metaclass, and/or decorators.
Such infrastructure building is in fact fun and instructive -- as long
as you don't fall into the trap of *using* such complications in
production code, where Python's simplicity rules;-).


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


Re: Word for a non-iterator iterable?

2005-02-06 Thread Alex Martelli
Leif K-Brooks <[EMAIL PROTECTED]> wrote:

> Is there a word for an iterable object which isn't also an iterator, and
> therefor can be iterated over multiple times without being exhausted?
> "Sequence" is close, but a non-iterator iterable could technically 
> provide an __iter__ method without implementing the sequence protocol,
> so it's not quite right.

Not just ``technically'' -- a dict is a good and very common example of
just such a "non-iterator, non-sequence iterable".

As you're focusing on "can be iterated over multiple-times", I like
"re-iterable"; it centers on what you can DO with the object, rather
than quibbling what it ISN'T;-)


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


Re: [EVALUATION] - E01: The Java Failure - May Python Helps?

2005-02-06 Thread Alex Martelli
Fredrik Lundh <[EMAIL PROTECTED]> wrote:

> Markus Wankus wrote:
> 
> > Google his name - he has been banned from Netbeans and Eclipse (and
> > Hibernate, and others...) for good reason.  Can you imagine how much of
> > a Troll you need to be to *actually* get "banned" from the newsgroups of
> > open source projects such as those?
> 
> have Pythoneers ever "banned" anyone from a public forum?  it's not like
> we haven't seen trolls and crackpots before, you know.

I don't see how banning is technically possible in unmoderated groups.
Shunning, or pelting the troll with abuse whenever he shows up, etc,
etc, sure.  But, banning?


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


Re: bytecode obfuscation

2005-02-06 Thread Alex Martelli
snacktime <[EMAIL PROTECTED]> wrote:
   ...
> How difficult is it to turn python bytecode into it's original source?

It's pretty easy, not really the original source (you lose comments etc)
but close enough to read and understand.

>  Is it that much different than java (this is what they will probably
> compare it to) ?

It's not very different from Java, or for that matter from C: Python's
bytecode is a bit higher-level than Java's, which is a bit higher level
than typical machine code, but not enough to make a difference if there
is good illicit profit to be made in disassembling and studying it.

> Also, I'm curious how much demand their is for this application in the
> Python world.  The application replaces online credit card

There is as much _wishing_ for magic bullets to slay all monsters, and
magic wands to cure all ills, in the Python world as in others, and
generally just about the same recognition that the magic bullets and
wands are not technically achievable.  You can arrange things so that
somebody wishing to study and reproduce your code will spend 10 hours
instead of 5, maybe (with effort) can go all the way up to making them
spend 20 hours -- but if reproducing that code is worth to them a few
thousand bucks, you're toast anyway.

Whatever code you let out of your control, it WILL get cracked if
there's a profit in cracking it -- and sometimes even if there ain't
(cfr, the cracks of hard-to-crack games abounding on warez sites).

So, if you have any code whose secrecy is important, you just cannot
allow it to get out of your control -- keep it on a solid and closely
guarded server and allow access to it only via well-controlled web
services or the like.  For example:

> processors(Verisign, Authorizenet) by providing a platform that
> connects directly to the bank networks for credit card processing, and

...the code would have to connect (with non-secrecy-critical code) to a
secure server which then does the secrecy-critical connection to the
bank networks -- assuming the secrecy IS critical for that part.

If you're currently distributing that ``secrecy critical'' code as JVM
bytecodes or intel machine code, and there IS indeed a profit to be made
in cracking it, rest assured that it IS cracked, somewhere.


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


Re: [EVALUATION] - E01: The Java Failure - May Python Helps?

2005-02-06 Thread Ilias Lazaridis
Terry Reedy wrote:
"Ilias Lazaridis" <[EMAIL PROTECTED]> wrote in message
Then 'print html_doc_instance' can print the html doc corresponding to 
the object model.
I understand this procedure.
I would like to use a standard way, which uses the standard metadata 
[implicit/explicit defined].

Does such standard exist?
I am not sure of what *you* mean by 'standard way'.  
a formal standard (like e.g. ODMG for OODBMS).
a quasi standard (e.g. an widely accepted definition/inpementation etc.)
That is probably 
because Python and the community is not big on 'standard ways' other than 
what is specified in the two reference manuals.  
I would say this is a "standard".
Can one please point me to a downloadable version of the 2 reference 
manuals (did not found them)?

And even then, Python is 
intentionally flexible in various ways (though not all).  
Flexibility is of course always very positive.
So the answer to your question is probably 'no'.
Terry J. Reedy
.
--
http://lazaridis.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.4 binaries for accessing PostgreSQL from Windows?

2005-02-06 Thread Frank Millman

Frank Millman wrote:
> Hi all
>
> The subject line says it all.
>
> I have been using pypgsql to access PostgreSQL from Linux and from
> Windows, and it works fine.
>
> I am upgrading to Python 2.4. I can recompile pypgsql for Linux, but
I
> do not have a Windows compiler. SourceForge has a binary for Python
> 2.3, which is the one I have been using. It does not have one for
2.4.
>
> I tried the psycopg site, but it does not seem to have binaries at
all.
>
> Does anyone know if either of these will be available in binary form
> for Python 2.4 on Windows?
>

Thanks for your replies, Gerhard and Josef. I have looked at both
solutions, but neither of them seem quite ideal. Hopefully you can show
me a simple way to overcome my problems.

In the case of pyPgSQL, it is overkill for me to load PgAdmin3 on each
Windows workstation running my accounting app. The binary for Python2.3
had a small libpq.pyd which was perfect for my needs. Don't you have
something similar for 2.4?

I have tried psycopg, and I must say I like it. It installs very
easily, and seems faster than pyPgSQL. My initial testing worked fine,
but as soon as I tried to use it from my app I ran into a problem. I
use wxPython as my front end, and it returns all strings as Python
unicode objects. If I pass these to a query, I get "TypeError: argument
1 must be str, not unicode". I could go through my app and convert all
strings back to type str, but it seems unnecessary. Is there a better
solution?

TIA for any advice.

Frank

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


Re: How do I convert arithemtic string (like "2+2") to a number?

2005-02-06 Thread Reinhold Birkenfeld
Michael Hartl wrote:
> Adam brings up a good point: eval is a very general function which
> evaluates an arbitrary Python expression.  As a result, it (and its
> close cousin exec) should be used with caution if security is an issue.

To get a secure eval for simple mathematical expressions, it should
suffice to check the string in the following way:

It does not contain characters other than operators, numbers, dots and
parentheses (perhaps you want to allow 'e' for floats, but you should
make sure that the 'e' is surrounded by numbers or optionally followed
by a +/- sign).

If you want to go a step further, you could parse the string to eval
with the parser/tokenize/... modules and verify the parse tree that it
contains nothing except operators and numbers.

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


Re: Multiple constructors

2005-02-06 Thread Reinhold Birkenfeld
vincent wehren wrote:
> Philip Smith wrote:
>> Call this a C++ programmers hang-up if you like.
>> 
>> I don't seem to be able to define multiple versions of __init__ in my matrix 
>> class (ie to initialise either from a list of values or from 2 dimensions 
>> (rows/columns)).
>> 
>> Even if Python couldn't resolve the __init__ to use on the basis of argument 
>> types surely it could do so on the basis of argument numbers???
>> 
>> At any rate - any suggestions how I code this
> 
> Checking the number of arguments ain't all that hard:
> 
> class Klass:
> def __init__(*args):
> self.args = args
> if len(self.args) == 1:
> # etc.
> 
> This feels rather unpythonic, though. 

And it won't work, as `self' is not defined. ;)

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


Python scripts a PC Interfacing equipment

2005-02-06 Thread Pramode C E
Hello,

The Phoenix project aims to bring low cost PC-based experimental
Physics to the classroom. Read a short intro here:

http://linuxgazette.net/111/pramode.html


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


Download a file from FTP server to local machine

2005-02-06 Thread rozita raissi

Hello,
 
I'm writing an ftp client script which must run in explorer. My script must be placed on and run from a web server. User can connect through it to a FTP server. If user requests to download a file from FTP server, file is downloaded to web server on which my script is running. How can I transfere downloaded file from web server to client local machine?
 
Regards.  
Yahoo! Messenger - Communicate instantly..."Ping" your friends 
today! Download Messenger Now-- 
http://mail.python.org/mailman/listinfo/python-list

pygame.mixer.music not playing

2005-02-06 Thread Marian Aldenhövel
Hi,
I am trying to make pygame play music on windows. This simple program:
import pygame,time
pygame.init()
print "Mixer settings", pygame.mixer.get_init()
print "Mixer channels", pygame.mixer.get_num_channels()
pygame.mixer.music.set_volume(1.0)
pygame.mixer.music.load('file1.mp3)
print "Play"
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
print "Playing", pygame.mixer.music.get_pos()
time.sleep(1)

print "Done"
seems to work. It runs the loop and prints values that look like ms into the
file. After a reasonable time corresponding to the length of "file1.mp3" the
loop is exited and the program ends.
The same thing happens for .mp3 files, .ogg files and .wav files.
Fine. The only problem is that there is no sound :-).
What am I doing wrong? pyGame example games do play sound, but I have not
found an example that uses music.
My ultimate goal is to build a MP3 jukebox that runs on Windows and Linux. I
have chosen pyGame as I am making a graphical Frontend using OpenGL. I have
also tried to look at pymad (which I could not get to work on Windows, no
C-Compiler on this machine and I could not find binaries) and audiere (no
skipping, at least in the python binding. A feature I would like to have.)
Ciao, MM
--
Marian Aldenhövel, Rosenhain 23, 53123 Bonn. +49 228 624013.
http://www.marian-aldenhoevel.de
"Wir brauchen keine Opposition, wir sind bereits Demokraten."
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I convert arithemtic string (like "2+2") to a number?

2005-02-06 Thread Adomas
Well, a bit more secure would be

eval(expression, {'__builtins__': {}}, {})

or alike.

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


Re: WYSIWYG wxPython "IDE"....?

2005-02-06 Thread Tim Hoffman
Have you tried Boa Constructor ?
http://boa-constructor.sourceforge.net/
Simon John wrote:
I'm writing my 2nd large wxPython program, and after the problems I
found doing the first's layout in code, I'd like to look at using a
'WYSIWYG' IDE, like VisualStudio does for MFC.
I've tried a few that I found, wxGlade is probably the best, although
it seems to be not 100% WYSIWYG (like the widgets in the preview are
not much like the final program), wxDesigner has a horrid GUI for a GUI
designer! VisualWX gave me the 'now what?' feeling when I started a new
project.
I find the sizer layout thing is what's holding these programs back, is
there another wxWidgets layout system, so that I could just drag'n'drop
widgets wherever I want in a window, more like Qt or MFC?
I'd like to just put a TextCtrl with a few buttons underneath it
without having to create two boxsizers or a gridsizer!
I'd like to create something like the main XMMS (or Winamp) window:
http://xmms.org/files/Skins/images/winamp_x_xmms.png
But that would be a 3-way vertical sizer, a 2-way horizontal and a
2-way vertical at least just for the main (top left) window.
--
http://mail.python.org/mailman/listinfo/python-list


Re: dynamic func. call

2005-02-06 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> Try this:
> 
> def myfunc():
>   print "helo"
> 
> s = "myfunc()"
> a = eval(s)
> 

No, please don't try that. Good uses for eval are *very* rare, and this 
isn't one of them.

Use the 'a = locals()[x]()' suggestion (or vars() instead of locals()), or 
even better put all the functions callable by this method into a class and 
use getattr() on an instance of the class.

A Pythonic way to do this sort of thing is to put all the functions that 
are callable indirectly into a class and give them names which contain a 
prefix to make it obvious that they are callable in this way and then add 
the prefix onto the string:

class C:
   def command_myfunc(self):
  return 42

   def default_command(self):
  raise NotImplementedError('Unknown command')

   def execute(self, s):
  return getattr(self, 'command_'+s, self.default_command)()

commands = C()
print commands.execute('myfunc')

That way you can be quickly tell which functions can be called indirectly 
and which can't; you can control what happens when no suitable function 
exists; and you can easily extend the functionality by subclassing your 
base class.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple constructors

2005-02-06 Thread Philip Smith
Thanks to all of you

Some useful ideas in there, even if some of them stretch my current 
knowledge of the language.

C++ to Python is a steep 'unlearning' curve...

Phil

"Philip Smith" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Call this a C++ programmers hang-up if you like.
>
> I don't seem to be able to define multiple versions of __init__ in my 
> matrix class (ie to initialise either from a list of values or from 2 
> dimensions (rows/columns)).
>
> Even if Python couldn't resolve the __init__ to use on the basis of 
> argument types surely it could do so on the basis of argument numbers???
>
> At any rate - any suggestions how I code this
>
> Thanks
>
> Phil
> 


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


After 40 years ... Knuth vol 4 is to be published!!

2005-02-06 Thread Laura Creighton
"More than forty years in the making, the long-anticipated Volume 4
of The Art of Computer Programming is about to make its debuta. in
parts. Rather than waiting for the complete book, Dr. Knuth and
Addison-Wesley are publishing it in installments ("fascicles") a la
Charles Dickens.

See http://www.bookpool.com/.x/xx/ct/163 for an excerpt and more info
on Volume 4.

And Addison-Wesley is offering Bookpool customers an exclusive sneak
peek -- the first official excerpt from the series."

(above from the same site)
Yippee!
Laura

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


Re: [EVALUATION] - E01: The Java Failure - May Python Helps?

2005-02-06 Thread Stephen Kellett
In message <[EMAIL PROTECTED]>, Ilias Lazaridis 
<[EMAIL PROTECTED]> writes
Can one please point me to a downloadable version of the 2 reference 
manuals (did not found them)?
Well, there is an obvious website address to visit and you can see the 
word "documentation" on that website without scrolling.

Use Google or a different search engine to find the obvious website.
Stephen
--
Stephen Kellett
Object Media Limitedhttp://www.objmedia.demon.co.uk
RSI Information:http://www.objmedia.demon.co.uk/rsi.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: OT: why are LAMP sites slow?

2005-02-06 Thread Brian Beck
Refactoring a database on a live system is a giant pain in the ass,
simpler file-based approaches make incremental updates easier.
The Wikipedia example has been thrown around, I haven't looked at the
code either;  except for search why would they need a database to
look up an individual WikiWord?  Going to the database requires reading
an index when pickle.load(open('words/W/WikiWord')) would seem sufficient.
I'm not so sure about this. If whatever is at, for example, 
words/W/WikiWord is just the contents of the entry, sure. But what about 
all the metadeta that goes along with that record? If you were to add a 
new field that is mandatory for all word records, you'd have to traverse 
the words directory and update each file, and that would require your 
own home-spun update scripts (of questionable quality). Worse, if the 
modifications are conditional.

As much as I hate working with relational databases, I think you're 
forgetting the reliability even the most poorly-designed database 
provides. Continuing with the words example: assuming all words would 
otherwise be stored in a table, consider the process of updating the 
database schema--all entries are guaranteed to conform to the new 
schema. With separate files on a filesystem, there is a much higher 
chance of malformed or outdated entries. Of course, this all depends on 
how reliable your implementation is, but consider which aspect you'd 
rather leave open to experimentation: loss of data integrity and 
possibly even data itself, or speed and efficiency?

--
Brian Beck
Adventurer of the First Order
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple constructors

2005-02-06 Thread vincent wehren
Reinhold Birkenfeld wrote:
vincent wehren wrote:
Philip Smith wrote:
Call this a C++ programmers hang-up if you like.
I don't seem to be able to define multiple versions of __init__ in my matrix 
class (ie to initialise either from a list of values or from 2 dimensions 
(rows/columns)).

Even if Python couldn't resolve the __init__ to use on the basis of argument 
types surely it could do so on the basis of argument numbers???

At any rate - any suggestions how I code this
Checking the number of arguments ain't all that hard:
class Klass:
   def __init__(*args):
   self.args = args
   if len(self.args) == 1:
   # etc.
This feels rather unpythonic, though. 

And it won't work, as `self' is not defined. ;)
You're right of course!
Note to self: Must stop shooting from the hip ;)
--
Vincent


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


Re: variable declaration

2005-02-06 Thread Arthur
On Sun, 6 Feb 2005 08:47:31 +0100, [EMAIL PROTECTED] (Alex Martelli)
wrote:

>
>Even the various "success stories" we've collected (both on websites,
>and, more impressive to PHBs, into paper booklets O'Reilly has printed)
>play a role.  ``NASA uses it for space missions, so of course we must
>use it to control our hot dog franchises'' -- we DID say we're talking
>about stupid firms, right?

>This is a good development, overall.  Against stupidity, the gods
>themselves contend in vain; Python's entrance into stupid firms broadens
>its potential appeal from less than 10% to around 100% of the market,
>which is good news for sellers of books, tools, training, consultancy
>services, and for Python programmers everywhere -- more demand always
>helps.  *BUT* the price is eternal vigilance...

What if:

There was a well conducted market survey conclusive to the effect that
adding optional strict variable declaration would, in the longer run,
increase Python's market share dramatically.

It just would. 

More books. more jobs, etc.

Why would it?

My sense of how the real world works is that there is going to be one
anti-Python advocate lying in wait for the first bug he can find that
he can say would have been caught if Python had strict variable
declaration, as he always knew it should. 

He wants to be the PHB someday. The current PHB knows that, and since
being sensitive to these kinds of realities is how he got to be the
PHB, he is too smart to open himself up to this kind of risk.

The PHB can pretty safely make the use of the option optional.  As
long as he is a position to jump down the throat of the programmer who
created the bug.   

"The option is there, why the hell didn't you use it".

What is the correct language design decision in light of these
realities?

My answer is, I think, the same as your answer. In fact, its simpler
for me - I don't write Python books.

But isn't this kind of where Python is at the moment?

Art 


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


Re: changing local namespace of a function

2005-02-06 Thread Kent Johnson
Bo Peng wrote:
Kent Johnson wrote:
You are still including the compile overhead in fun2. If you want to 
see how fast the compiled code is you should take the definition of 
myfun out of fun2:
I assumed that most of the time will be spent on N times execution of 
myfunc.
Doh! Right.
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: bad generator performance

2005-02-06 Thread Johannes Ahl-mann
> Um. Under my definition of "recursion", you haven't really removed
> recursion in the generator version. That is, you're still calling the
> depthFirstIterator method upon each iteration--you've just changed from
> list-concatenation to yielding instead, which trades off list-management
> overhead for closure-maintenance overhead. 
yup, i am aware that my generator version is also recursive. but what i
thought this would do is "generate" a lazy list of return values (in
theory at least).
but this still doesn't explain why the yielding is so much slower than
the list concatenation!

> A truly non-recursive
> implementation would probably exist outside of whatever class you've got
> this method in, and would keep its own pointer to the current node as it
> traversed the tree.


i loved the generator solution because it was short, concise and lazy,
but if i am going to write the closure/continuation/recursion handling
manually i'd rather go with the memory-consuming list concatenation...
a non-recursive solution to traversing a recursive data type is bound to
get ugly, isn't it?

i just wondered if there was a concise, clean way of doing this with
generators which i had overlooked, or whether there was some blatant
mistake in my code.

thx,

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


Re: [EVALUATION] - E01: The Java Failure - May Python Helps?

2005-02-06 Thread Ilias Lazaridis
Stephen Kellett wrote:
In message <[EMAIL PROTECTED]>, Ilias Lazaridis 
<[EMAIL PROTECTED]> writes

Can one please point me to a downloadable version of the 2 reference 
manuals (did not found them)?
Well, there is an obvious website address to visit and you can see the 
word "documentation" on that website without scrolling.
which leads to:
http://python.org/doc/
which leads to:
http://docs.python.org/download.html
The conviently downloadable documentation-pack contains 4 "reference" 
type manuals.

I assume the mentioned "2 reference manuals" were contained therein.
Use Google or a different search engine to find the obvious website.
Thank you.
I prefere interaction with the community.
.
--
http://lazaridis.com
--
http://mail.python.org/mailman/listinfo/python-list


Python versus Perl ?

2005-02-06 Thread surfunbear

 I've read some posts on Perl versus Python and studied a bit of my
Python book.

 I'm a software engineer, familiar with C++ objected oriented
development, but have been using Perl because it is great for pattern
matching, text processing, and automated testing. Our company is really
fixated on risk managnemt and the only way I can do enough testing
without working overtime (which some people have ended up doing) is by
automating my testing. That's what got me started on Perl.

 I've read that many people prefer Python and that it is better than
Perl. However, I want to ask a few other questions.


1. Perl seems to have alot of packaged utilities available through
CPAN, the comprehensive perl network. These can aid in building
parsers, web development, perl DBI is heavily used. This seems to be a
very important benifit. I'm not sure that Python is as extenive at all
in that regard ? Perl also has excellent pattern matching compared to
sed, not sure about how Python measures up,
 but this seems to make perl ideally suited to text processing.

2. Python is apparantly better at object oriented. Perl has some kind
of name spacing, I have used that in a limited way. Does Perl use a
cheap and less than optimal Object oriented approach ?
That was what someone at work said, he advocates Python.
Is it likely that Perl will improve it's object oriented features
in the next few years ?

3. Perl is installed on our system and alot of other systems.
You don't have to make sys admins go out of there way to make it
available. It's usualy allready there. I also did a search of job
postings on a popular website. 108 jobs where listed that require
knowledge of Perl, only 17 listed required Python. Becomeing more
familiar with Perl might then be usefull for ones resume ?



 If Python is better than Perl, I'm curious how really significant
those advantages are ?

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


Re: bytecode obfuscation

2005-02-06 Thread Philippe Fremy
Adam DePrince wrote:
No amount of obfuscation is going to help you.
Theorically, that's true. Anything obfuscated can be broken, just like 
the non obfuscated version. However it takes more skills and time to 
break it. And that's the point. By raising the barrier for breaking a 
product, you just eliminate a lot of potential crackers.

The worst case if you depend on obscurity:  The bad guys are rounding
off your pennies as you read this.
That's the worst case, we all know that. A good case is to rely on open 
spec and standard. However, obscurity can help if added on top of that.

I remember an article of Fyodor explaining that if you run your internal 
apache server on port 1234 (for an enterprise) with all the normal 
security turned on, you avoid 80% of the common cracker. You should not 
rely on the port number for security but changing it improves it.

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


Re: bad generator performance

2005-02-06 Thread Alex Martelli
Johannes Ahl-mann <[EMAIL PROTECTED]> wrote:

> a non-recursive solution to traversing a recursive data type is bound to
> get ugly, isn't it?

Not necessarily: sometimes using an explicit stack can be quite pretty,
depending.  E.g.:

def all_leaves(root):
stack = [root]
while stack:
rightmost = stack.pop()
if is_leaf(rightmost):
yield rightmost
else:
stack.extend(rightmost.all_children())

This isn't the traversing you're looking for, but it is _a_ traversing
of a recursive data type, non-recursive, and IMHO quite pretty.


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


Re: Python versus Perl ?

2005-02-06 Thread Reinhold Birkenfeld
[EMAIL PROTECTED] wrote:
>  I've read some posts on Perl versus Python and studied a bit of my
> Python book.
> 
>  I'm a software engineer, familiar with C++ objected oriented
> development, but have been using Perl because it is great for pattern
> matching, text processing, and automated testing. Our company is really
> fixated on risk managnemt and the only way I can do enough testing
> without working overtime (which some people have ended up doing) is by
> automating my testing. That's what got me started on Perl.
> 
>  I've read that many people prefer Python and that it is better than
> Perl. However, I want to ask a few other questions.

"Better than Perl" is a very general statement. In my personal opinion,
this is true for every project being larger than one file of ~200 LOC.

> 1. Perl seems to have alot of packaged utilities available through
> CPAN, the comprehensive perl network. These can aid in building
> parsers, web development, perl DBI is heavily used. This seems to be a
> very important benifit. I'm not sure that Python is as extenive at all
> in that regard ?

There are the Python Package Index (PyPI), the Vaults of Parnassus, and
when you don't find a needed package there, just come and ask here;
almost always a decent solution is found.

A thing similar to CPAN is being worked on by various people, though I
don't know when it will become mature.

> Perl also has excellent pattern matching compared to
> sed, not sure about how Python measures up,
>  but this seems to make perl ideally suited to text processing.

Python has regular expressions much like Perl. The only difference is
that Perl carries syntactic support for them, while in Python regular
expressions are ordinary objects with methods etc.

> 2. Python is apparantly better at object oriented. Perl has some kind
> of name spacing, I have used that in a limited way. Does Perl use a
> cheap and less than optimal Object oriented approach ?
> That was what someone at work said, he advocates Python.
> Is it likely that Perl will improve it's object oriented features
> in the next few years ?

There is the Perl 6 movement, but when you read some of the docs at
http://dev.perl.org, you will come to the conclusion that

- Perl 6 lies at least 3-5 years in the future and
- it will be a huge mess. Someone here once said "Perl 6 is the ultimate
failure of Perl's philosophy". There may be split views about this...

> 3. Perl is installed on our system and alot of other systems.
> You don't have to make sys admins go out of there way to make it
> available. It's usualy allready there.

Same goes with Python; it is installed per default on most modern
Unices. Windows is a completely different chapter, however, Perl isn't
more widespread there.

> I also did a search of job
> postings on a popular website. 108 jobs where listed that require
> knowledge of Perl, only 17 listed required Python. Becomeing more
> familiar with Perl might then be usefull for ones resume ?

It doesn't harm, of course. Recent statistics about programmers'
salaries indicate, however, that Python ranks top (I somehow lost the URL).

> If Python is better than Perl, I'm curious how really significant
> those advantages are ?

Try to decide yourself. The Python tutorial and website are your friends.

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


Re: Insane import behaviour and regrtest.py: heeelp

2005-02-06 Thread John J. Lee
Nick Coghlan <[EMAIL PROTECTED]> writes:

> John J. Lee wrote:
> > The only change I made to regrtest other than the print statements was
> > to add Lib to sys.path, so I pick up modules from CVS instead of the
> > installed 2.4 versions (yeah, I know I should build and install a
> > python2.5 executable from CVS, but I don't see how that's relevant here).
> 
> I didn't read your whole message so I may be off track here, but
> regrtest.py has some arguably demented path handling behaviour, and
> it's driven mainly by the physical location of regrtest.py. In
> particular:
> 
> def findtestdir():
>  if __name__ == '__main__':
>  file = sys.argv[0]
>  else:
>  file = __file__
>  testdir = os.path.dirname(file) or os.curdir
>  return testdir
> 
> So intead of adding anything to sys.path, tweak the call to 'main' on
> the final line to set "testdir" appropriately.

Nope: that just affects finding the *names* of the tests.  It does not
determine the location from which they are actually imported.  I tried
it, and I get the same results as before (the test modules from my
installed copy of Python are picked up instead of the local copies in
my CVS checkout's Lib/test, apparently entirely contrary to sys.path).


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


Re: Python versus Perl ?

2005-02-06 Thread Kartic
[EMAIL PROTECTED] said the following on 2/6/2005 8:19 AM:
 I've read some posts on Perl versus Python and studied a bit of my
Python book.
 I'm a software engineer, familiar with C++ objected oriented
development, but have been using Perl because it is great for pattern
matching, text processing, and automated testing. Our company is really
fixated on risk managnemt and the only way I can do enough testing
without working overtime (which some people have ended up doing) is by
automating my testing. That's what got me started on Perl.
Python is great for pattern matching using the re module. If you are 
talking about the ~= operator, that is not available in Python but you 
can your favorite Regexp matches/searches/replacements using the re 
module. And actually I like Python re sub better as it has a clean 
syntax. One can provide a replacement function to the sub method where 
one can manipulate the matched groups. Please see 
http://www.amk.ca/python/howto/regex/ for more info.

Automated testing - One of the best languages to create automated test 
cases and still remember after a few months what your test cases... that 
is how clean Python syntax is. And you have not specified exactly what 
kind of automation you do. I code test cases for Win32 as well as 
testing data exchange over FTP and Telnet.

I know a lot of toy and serious parsers written in Python. Heck, there 
is even a Python implementation in Python. Text Processing is simply 
superb, combined the the re module. I am not too qualified to talk about 
text processing but lets say life is a breeze! You can read about Python 
Text Processing at http://gnosis.cx/TPiP/ - this is a whole book 
dedicated to text processing in Python. Also see 
http://www.python.org/moin/LanguageParsing


1. Perl seems to have alot of packaged utilities available through
CPAN, the comprehensive perl network. These can aid in building
parsers, web development, perl DBI is heavily used. This seems to be a
very important benifit. I'm not sure that Python is as extenive at all
in that regard ? Perl also has excellent pattern matching compared to
sed, not sure about how Python measures up,
 but this seems to make perl ideally suited to text processing.
While, AFAIK, there is no CPANish library, Python comes with "batteries" 
included, i.e., almost everything you would need to churn out the 
programs you need. For everything else, there are independent projects. 
But take a look at the Vault of Parnassus for a BIG collection of Python 
modules/projects/applications.

Python has a DBI compliant API which means all compliant modules support 
the same syntax. And Python has modules supports all major databases. 
See http://www.python.org/topics/database/

2. Python is apparantly better at object oriented. Perl has some kind
of name spacing, I have used that in a limited way. Does Perl use a
cheap and less than optimal Object oriented approach ?
That was what someone at work said, he advocates Python.
Is it likely that Perl will improve it's object oriented features
in the next few years ?
Well, Perl's lack of a decent OO approach is one reason I converted to 
Python. Another was Perl's syntax; I could not read my own code unless I 
had put copious amounts of comments. Python enforces clean coding using 
indentation levels that associates blocks of code; so no need of a {} or 
BEGIN/END and you will be amazed at how indentation, which IMHO, any 
programmer should anyway practice for readability, can make the code 
easy to comprehend.

3. Perl is installed on our system and alot of other systems.
You don't have to make sys admins go out of there way to make it

That actually depends on the OS. I believe Sun OS comes with Perl and 
that is because of the historic use of Perl for sys admin work. Redhat 8 
onwards comes with Python installed because Redhat's install process is 
written in Python. Windows comes with neither. And for your sysadmins, 
installing Python should not be difficult at all. As long as you 
identify the need and tell them that is what they must do for your 
accomplish your tasks efficiently, I don't see this a stumbling block at 
all!

> available. It's usually allready there. I also did a search of job
> postings on a popular website. 108 jobs where listed that require
> knowledge of Perl, only 17 listed required Python. Becomeing more
> familiar with Perl might then be usefull for ones resume ?
I don't see the correlation between the number of jobs available and 
fashion-statement of a language, if that is what you are insinuating. My 
job does not require me to know Python, but I use it and effectively. 
So, how does one account for that? And since you already have a job and 
are considering using Python for your current job, it should not matter 
to you. Moreover you increase your marketability by learning both Perl 
and Python...you have access to 108 + 17 jobs :-)

True, there are a few Python "shops" but there are many jobs that ask 
for knowledge of

Curses on Windows

2005-02-06 Thread Peter
Last November I posted a message asking for advice on using simple
screen handling techniques under Windows.  Since then I have been
occupied with family / job /Christmas /living  and trying to
understand curses under linux (it works, seems very complex, sure I'm
missing something ...).  Only now am I returning to my original query.

One reply (in fact the only reply - thanks Tim Golden) suggested I
look at http://flangy.com/dev/python/curses/

Just tried that and got the message

"You don't have permission to access
/dev/python/curses/files/wcurses-0.1-py2.4.zip on this server."

any ideas why I can't access it - or any alternative URL's, or indeed
any other suggestions at all!  Grateful for any reply.

The email address is the one I registered under Google, and is now
defunct!

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


Re: [EVALUATION] - E01: The Java Failure - May Python Helps?

2005-02-06 Thread Ilias Lazaridis
"Ilias Lazaridis" <[EMAIL PROTECTED]> wrote in message 
[...]
I want to add metadata to everything within my design (functions, data,
classes, ...), if possible with a standard way.
[...]
I want to generate things (code, txt, html etc.) out of my object-model,
whilst using with a flexible generator, if possible a standard one.
Example: ArcheTypes, autogeneration of forms and pages
"The creation of a new Type using Archetypes involves a main text file 
(python) that defines the fields and other objects within your type, 
their properties, and their behavior. Archetypes uses this information 
to auto generate on demand all forms and pages needed to add, edit, and 
view your types data. When you have written this file, you then have a 
product that you would install just like any other CMF/Plone product."

source: http://plone.org/documentation/archetypes/
-
Archetype is defined within a python file.
Does this include  metadata?
If yes: in a standard way (e.g. usable in other developments, too)?
Archetypes uses a generator.
Is this a standard generator (thus I don't have to learn/use another one 
in another context)?

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


Re: How do I convert arithemtic string (like "2+2") to a number?

2005-02-06 Thread John J. Lee
"Adomas" <[EMAIL PROTECTED]> writes:

> Well, a bit more secure would be
> 
> eval(expression, {'__builtins__': {}}, {})
> 
> or alike.

Don't believe this without (or even with ;-) very careful thought,
anyone.  Google for rexec.


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


Re: pygame.mixer.music not playing

2005-02-06 Thread M.E.Farmer
Marian Aldenhövel wrote:
> Hi,
>
> I am trying to make pygame play music on windows. This simple
program:
>
>   import pygame,time
>   pygame.init()
>   print "Mixer settings", pygame.mixer.get_init()
>   print "Mixer channels", pygame.mixer.get_num_channels()
>   pygame.mixer.music.set_volume(1.0)
>   pygame.mixer.music.load('file1.mp3)
>   print "Play"
>   pygame.mixer.music.play()
>
>   while pygame.mixer.music.get_busy():
>   print "Playing", pygame.mixer.music.get_pos()
>   time.sleep(1)
>
>   print "Done"
>
> seems to work. It runs the loop and prints values that look like ms
into the
> file. After a reasonable time corresponding to the length of
"file1.mp3" the
> loop is exited and the program ends.
>
> The same thing happens for .mp3 files, .ogg files and .wav files.
>
> Fine. The only problem is that there is no sound :-).
>
> What am I doing wrong? pyGame example games do play sound, but I have
not
> found an example that uses music.
>
> My ultimate goal is to build a MP3 jukebox that runs on Windows and
Linux. I
> have chosen pyGame as I am making a graphical Frontend using OpenGL.
I have
> also tried to look at pymad (which I could not get to work on
Windows, no
> C-Compiler on this machine and I could not find binaries) and audiere
(no
> skipping, at least in the python binding. A feature I would like to
have.)
>
> Ciao, MM
> --
> Marian Aldenhövel, Rosenhain 23, 53123 Bonn. +49 228 624013.
> http://www.marian-aldenhoevel.de
> "Wir brauchen keine Opposition, wir sind bereits Demokraten."

Hello Marian,
First thing out i must tell you that pygame is ok for games but the
music quality is sometimes sketchy, you must set the bit rate to get
good sound quality and there are many other pitfalls. Search the net.
You are not the first to try and build a jukebox out of pygame ;)

Py> import pygame
Py> pygame.mixer.init()
Py> pygame.mixer.music.load('c:/everyday.mp3')
Py> pygame.mixer.play()
Py> pygame.mixer.music.fadeout(4000)

You have a typo in the code you posted that may be your problem.
M.E.Farmer

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


ANN: SPE 0.7.2.A IDE with wxGlade, Uml & Blender support

2005-02-06 Thread s_t_a_n_i
Spe is a python IDE with auto-indentation, auto completion, call tips,
syntax coloring, uml viewer, syntax highlighting, class explorer,
source index, auto todo list, sticky notes, integrated pycrust shell,
python file browser, recent file browser, drag&drop, context help, ...
Special is its blender support with a blender 3d object browser and its
ability to run interactively inside blender. Spe ships with wxGlade
(gui designer), PyChecker (source code doctor) and Kiki (regular
expression console). Spe is extensible with wxGlade.

The sidebar now features a file browser. I'm now trying to form a team
for future development of SPE. Besides me four people will join the
project:

- Sam Widmer for CVS and bugfixes. So soon more collaboration on SPE
will be possible.
- Nir Aides (author of rpdb) for helping implementing the remote
debugger
- Kevin Walzer for the OS X Port of SPE. Please contact him for Mac
specific issues. Spe for the Mac will be distributed through:
http://www.wordtech-software.com/spe.html
- Jelle Feringa for documentation. The goal is to provide a pdf manual
with the SPE distribution based on the SPE wiki:
http://www.stani.be/spe/wiki Anyone who has comments or wants to edit
the wiki as well can contact Jelle.

If you like SPE, please contribute by coding, writing documentation or
donating. I would like to thank especially Michael Balk, who gave the
largest
donation ever to SPE.

Also I would like to thank Michael Foord, who made SPE part of a new
Python distribution, called "movable python". It gives you the
possibility to carry your favorite developping environment on a USB
stick. So you can continue your work on any computer or test your
modules for different python versions. This distribution opens a lot of
new possibilities, check it out!! For more info, visit
http://www.voidspace.org.uk/python/programs.shtml#movpy

:Batteries included:
  - Kiki:
  Regular Expression (regex) console. For more info:
  http://project5.freezope.org/kiki/index.html
  - PyChecker:
  PyChecker is a tool for finding bugs in python source code. It
  finds problems that are typically caught by a compiler for
  less dynamic languages, like C and C++. It is similar to lint.
  For more info: http://pychecker.sourceforge.net
  - wxGlade:
  wxGlade is a GUI designer written in Python with the
  popular GUI toolkit wxPython, that helps you create
  wxWindows/wxPython user interfaces. As you can guess by the
  name, its model is Glade, the famous GTK+/GNOME GUI builder,
  with which wxGlade shares the philosophy and the look & feel
  (but not a line of code). For more info:
  http://wxglade.sourceforge.net

:New features:
- sidebar browser (iniated by Attila Magyar)

:Bug fixes:
- segfaults in Browser
- indentation can now be different from 4
- mac osx fixes for kiki, wxGlade & XRC
- scrollbars of UML view
- initial sizing and positioning are now restored

:Donations(177.20euro):
- Michael Balk
- Jason Powell
- David Ko Feng
- Winchell Chung
- Matthias Haberkorn
- Kristjan Kannike
- Robert Cowham
- Andre Roberge
- Chris S

:Contributors:
  - Sam Widmer
  - Attila Magyar
  - Kevin Walzer
  - Thurston Stone

:Requirements:
  - full python 2.3+
  - wxpython 2.5.3.8+
  - optional blender 2.35+

:Links:
- Homepage: http://spe.pycs.net
- Website:  http://projects.blender.org/projects/spe/
- Screenshots:  http://spe.pycs.net/pictures/index.html
- Forum:http://projects.blender.org/forum/?group_id=30
- RSS feed: http://spe.pycs.net/weblog/rss.xml

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


RE: bad generator performance

2005-02-06 Thread Jimmy Retzlaff
Johannes Ahl-mann wrote:
> i just wondered if there was a concise, clean way of doing this with
> generators which i had overlooked, or whether there was some blatant
> mistake in my code.

Aside from the recursion question...

You don't really give the complete story so it's hard to tell what
exactly is going on. For example, I would assume the recursion is
calling the same method (i.e., depthFirstIterator1 or
depthFirstIterator2), but then you posted separate timing information
for a "recursive helper function" so I'm not so sure. Also there is not
much of a hint as to the nature of your data.

Below is a test where each of your 2 methods calls itself recursively.
To make it work I had to build a data tree - I used the files and
folders in my C:\Python23 directory. In my testing (on Python 2.3.4 on
Windows XP), the generator version takes about 1/4 of the time that the
list version takes. If both versions call the list version of the method
recursively (i.e., you're only getting the benefit of the generator at
the top level of the recursion), the generator version is still about
20% faster.

Timing differences could potentially depend on your data also - things
like how deep vs. wide your tree is.

Jimmy


import os
import time

class Node:
def __init__(self, pathname):
self.thisIsAFolder = os.path.isdir(pathname)
self.children = []
if self.isFolder():
for filename in os.listdir(pathname):
childpathname = os.path.join(pathname, filename)
self.children.append(Node(childpathname))

def isFolder(self):
return self.thisIsAFolder

def depthFirstIterator1(self, depth = 0):
ret = [[self, True, depth]]

if self.isFolder():
  for c in self.children:
ret = ret + c.depthFirstIterator1(depth = depth + 1)

return ret + [[self, False, depth]]

def depthFirstIterator2(self, depth = 0):
yield [self, True, depth]

if self.isFolder():
  for c in self.children:
for y in c.depthFirstIterator2(depth = depth + 1):
  yield y

yield [self, False, depth]


x = Node(r'C:\Python23')
for iterator in (x.depthFirstIterator1, x.depthFirstIterator2):
print iterator.__name__,
start = time.time()
for item in iterator():
pass
print round(time.time()-start, 2)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python versus Perl ?

2005-02-06 Thread Roy Smith
[EMAIL PROTECTED] wrote:

>  I've read some posts on Perl versus Python and studied a bit of my
> Python book.
> 
>  I'm a software engineer, familiar with C++ objected oriented
> development, but have been using Perl because it is great for pattern
> matching, text processing, and automated testing. Our company is really
> fixated on risk managnemt and the only way I can do enough testing
> without working overtime (which some people have ended up doing) is by
> automating my testing. That's what got me started on Perl.

Automated testing is essential in almost any software project, and not just 
to make sure you don't have to work overtime.
 
>  I've read that many people prefer Python and that it is better than
> Perl. However, I want to ask a few other questions.

Keep in mind that this is a somewhat biased audience to ask a question like 
that.  For the most part, c.l.p. is inhabited by rabid Pythonistas :-)
 
> 1. Perl seems to have alot of packaged utilities available through
> CPAN, the comprehensive perl network.

There is no doubt that there's a lot of stuff on CPAN, and the architecture 
of the repository makes it relatively easy to find what you want and get it 
running.  On the other hand, there are a lot of add-on modules for Python 
too.  You mention DBI; Python's version of that is the DB-API, and there 
are quite a few modules that implement it 
(http://www.python.org/topics/database/modules.html).

> Perl also has excellent pattern matching compared to
> sed, not sure about how Python measures up,
> but this seems to make perl ideally suited to text processing.

As far as regular espressions themselves, Python supports exactly the same 
regex syntax that Perl does.  The packaging is a little different; instead 
of being built-in to the language, it's a module you import and use in an 
object-oriented way.

> 2. Python is apparantly better at object oriented. Perl has some kind
> of name spacing, I have used that in a limited way. Does Perl use a
> cheap and less than optimal Object oriented approach?

Python's OO support was designed-in from the ground up.  Perl's is an ugly 
wart held on with duct tape.

> That was what someone at work said, he advocates Python.
> Is it likely that Perl will improve it's object oriented features
> in the next few years ?

There is a "Perl 6" project going on, which I imagine will have some major 
changes to the language, but you'll have to ask the Perl people about that.

> 3. Perl is installed on our system and alot of other systems.
> You don't have to make sys admins go out of there way to make it
> available. It's usualy allready there.

Python now comes standard with a lot of operating systems, but it is 
certainly true that if there is one lingua franca in the computer world 
(and certainly the Unix world), Perl is it.  If your prime motivation is 
portability, that might be the feature which tips the balance in favor of 
Perl.

> I also did a search of job
> postings on a popular website. 108 jobs where listed that require
> knowledge of Perl, only 17 listed required Python. Becomeing more
> familiar with Perl might then be usefull for ones resume?

There is no doubt that most employers expect you to know Perl.  Even if 
it's not on the job spec, there's enough Perl out there in the world that 
it really is worth knowing.  If your career goal is sysadmin rather than 
programming, then I'd say Perl is absolutely essential to know.
 
> If Python is better than Perl, I'm curious how really significant
> those advantages are?

Well, now we're back to that biased audience stuff again.  My answer is 
that of course it's better.  The biggest advantage of Python is that it has 
a clean syntax with designed-in support of OOP.

Perl's basic syntax is a jumble of stuff stolen from shell, awk, sed, and 
grep, with some vague OO ideas glommed onto it.  The heavy reliance on 
punctuation makes it almost impossible to read.

My suggestion is to learn Python, then make up your own mind.  Grab one of 
the tutorials available on-line and spend an afternoon getting the basics 
down.  Next step, pick a small real-life project and invest a couple of 
days doing it in Python.  By then, you should have a better idea of whether 
it's worth investing some more time to get deeper into it.

One you know C++, Perl, and Python, you'll have exposure to a pretty broad 
range of programming paradigms.  But, don't stop there.  If your goal is to 
be a professional programmer, keep learning languages.  Learn some because 
they'll provide a paycheck, learn others because they'll expose you to 
different ideas.  In today's world, I'd put Java, SQL, VB, and C# in the 
"paycheck" group.  I'd put Lisp, Smalltalk, and Postscript in the "personal 
improvement" group.  Things like Python, Tcl, and Ruby fall somewhere 
in-between; they're interesting because they explore different corners of 
the "how to design a programming language" universe, but they also have a 
reasonable chance of be

Re: variable declaration

2005-02-06 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] (Alex Martelli) wrote:

> This is a good development, overall.  Against stupidity, the gods
> themselves contend in vain; Python's entrance into stupid firms broadens
> its potential appeal from less than 10% to around 100% of the market,
> which is good news for sellers of books, tools, training, consultancy
> services, and for Python programmers everywhere -- more demand always
> helps.  *BUT* the price is eternal vigilance...

I'm not sure what that last sentence is supposed to mean, but I have 
visions (nightmares?) of someday having ANSI, ISO, IEEE, or some other such 
organization notice that something useful exists which they haven't yet 
standardized/broken and decide to form a committee to do it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python versus Perl ?

2005-02-06 Thread moma
Reinhold Birkenfeld wrote:
[EMAIL PROTECTED] wrote:
I've read some posts on Perl versus Python and studied a bit of my
Python book.
I'm a software engineer, familiar with C++ objected oriented
development, but have been using Perl because it is great for pattern
matching, text processing, and automated testing. Our company is really
fixated on risk managnemt and the only way I can do enough testing
without working overtime (which some people have ended up doing) is by
automating my testing. That's what got me started on Perl.
I've read that many people prefer Python and that it is better than
Perl. However, I want to ask a few other questions.

"Better than Perl" is a very general statement. In my personal opinion,
this is true for every project being larger than one file of ~200 LOC.

1. Perl seems to have alot of packaged utilities available through
CPAN, the comprehensive perl network. These can aid in building
parsers, web development, perl DBI is heavily used. This seems to be a
very important benifit. I'm not sure that Python is as extenive at all
in that regard ?

There are the Python Package Index (PyPI), the Vaults of Parnassus, and
when you don't find a needed package there, just come and ask here;
almost always a decent solution is found.
A thing similar to CPAN is being worked on by various people, though I
don't know when it will become mature.

Perl also has excellent pattern matching compared to
sed, not sure about how Python measures up,
but this seems to make perl ideally suited to text processing.

Python has regular expressions much like Perl. The only difference is
that Perl carries syntactic support for them, while in Python regular
expressions are ordinary objects with methods etc.

2. Python is apparantly better at object oriented. Perl has some kind
of name spacing, I have used that in a limited way. Does Perl use a
cheap and less than optimal Object oriented approach ?
That was what someone at work said, he advocates Python.
Is it likely that Perl will improve it's object oriented features
in the next few years ?

There is the Perl 6 movement, but when you read some of the docs at
http://dev.perl.org, you will come to the conclusion that
- Perl 6 lies at least 3-5 years in the future and
- it will be a huge mess. Someone here once said "Perl 6 is the ultimate
failure of Perl's philosophy". There may be split views about this...

3. Perl is installed on our system and alot of other systems.
You don't have to make sys admins go out of there way to make it
available. It's usualy allready there.

Same goes with Python; it is installed per default on most modern
Unices. Windows is a completely different chapter, however, Perl isn't
more widespread there.

I also did a search of job
postings on a popular website. 108 jobs where listed that require
knowledge of Perl, only 17 listed required Python. Becomeing more
familiar with Perl might then be usefull for ones resume ?

It doesn't harm, of course. Recent statistics about programmers'
salaries indicate, however, that Python ranks top (I somehow lost the URL).

If Python is better than Perl, I'm curious how really significant
those advantages are ?

Try to decide yourself. The Python tutorial and website are your friends.
Reinhold

I like Ruby because it inherits so many (best) features from Python and 
Perl ;)  Someday all these languages will compile to a common 
intermediate representation (ref. YAML: http://yaml.kwiki.org  || 
http://yaml.org )

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/79533
http://www.cs.washington.edu/homes/kd/courses/pythonruby.pdf
http://www.ntecs.de/old-hp/s-direktnet/rb/download_ruby.html
http://www.ruby-lang.org/en/
// moma
--
http://mail.python.org/mailman/listinfo/python-list


Confused with methods

2005-02-06 Thread jfj
I don't understand.
We can take a function and attach it to an object, and then call it
as an instance method as long as it has at least one argument:
#
class A:
  pass
def foo(x):
  print x
A.foo = foo
a=A()
a.foo()
#
However this is not possible for another instance method:

class A:
 pass
class B:
 def foo(x,y)
 print x,y
b=B()
A.foo = b.foo
a=A()
# error!!!
a.foo()
##
Python complains that 'foo() takes exactly 2 arguments (1 given)'.
But by calling "b.foo(1)" we prove that it is indeed a function which takes
exactly one argument.
Isn't that inconsistent?
Thanks,
Gerald.
--
http://mail.python.org/mailman/listinfo/python-list


Re: OT: why are LAMP sites slow?

2005-02-06 Thread Lee Harr
On 2005-02-06, Brian Beck <[EMAIL PROTECTED]> wrote:
>> Refactoring a database on a live system is a giant pain in the ass,
>> simpler file-based approaches make incremental updates easier.
>> 

> As much as I hate working with relational databases, I think you're 
> forgetting the reliability even the most poorly-designed database 
> provides. Continuing with the words example: assuming all words would 
> otherwise be stored in a table, consider the process of updating the 
> database schema--all entries are guaranteed to conform to the new 
> schema.


Not only that, but with a well-design RDBMS you can put your
schema changes inside of a transaction and make sure everything
is right before committing.

Isn't there a saying like ... those who create file-based
databases are destined to re-create a relational database
management system poorly?  ;o)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: variable declaration

2005-02-06 Thread Alex Martelli
Roy Smith <[EMAIL PROTECTED]> wrote:

> > which is good news for sellers of books, tools, training, consultancy
> > services, and for Python programmers everywhere -- more demand always
> > helps.  *BUT* the price is eternal vigilance...
> 
> I'm not sure what that last sentence is supposed to mean, but I have 

You seem to...:

> visions (nightmares?) of someday having ANSI, ISO, IEEE, or some other such
> organization notice that something useful exists which they haven't yet
> standardized/broken and decide to form a committee to do it.

...so we'd better be careful (==eternal vigilance)...


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


Re: Confused with methods

2005-02-06 Thread Matthias Kempka
Hi Gerald,
When you define an instance method, the first parameter (in the 
definition) represents the instance. By convention, you would name it 
"self":

#
class B:
   def foo(self, x):
  print "we have two parameters: " + str(self) + " and " + x
#
then calling
##
b = B()
b.foo("x")
##
would be equivalent to
##
b = B()
B.foo(b, "x")
##
So, as you have noted, you need at least one parameter to attach the 
method to an instance. This is because the instance _is_ the parameter. 
Python does this for you internally.

For more documentation you should read the paragraph about classes in 
the tutorial.

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


Re: bad generator performance

2005-02-06 Thread Johannes Ahl-mann
> You don't really give the complete story so it's hard to tell what
> exactly is going on. For example, I would assume the recursion is
> calling the same method (i.e., depthFirstIterator1 or
> depthFirstIterator2), but then you posted separate timing information
> for a "recursive helper function" so I'm not so sure. Also there is not
> much of a hint as to the nature of your data.

yeah, sorry. i'm not myself lately ;-))
forget about the helper function, that was nonsense! i used a helper
function to build a huge tree as test data, but that is the same
function for both cases!

the program is supposed to manage bookmarks and i thought it would be a
good idea to represent the bookmarks as a tree (with folders as internal
nodes and bookmarks as leaves).
so, a tree is never going to hold more than say 2000 nodes and is going
to be rather wide than deep!

> In my testing (on Python 2.3.4 on
> Windows XP), the generator version takes about 1/4 of the time that the
> list version takes. If both versions call the list version of the method
> recursively (i.e., you're only getting the benefit of the generator at
> the top level of the recursion), the generator version is still about
> 20% faster.
>
> Timing differences could potentially depend on your data also - things
> like how deep vs. wide your tree is.

thx a lot and sorry for not supplying my data type and test data!
hmm, that totally contradicts my profiling results... on my machine the
generator version is repeatedly 10 times slower than the list version as
well with python2.3 as with python2.4.
i don't want to spam the list with hundreds of lines of source code, so
i'll just cry a little and try to do something else than prematurely
optimising my bookmark script *gg*

thx,

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


Re: Python versus Perl ?

2005-02-06 Thread Alex Martelli
Reinhold Birkenfeld <[EMAIL PROTECTED]> wrote:
   ...
> > Perl also has excellent pattern matching compared to
> > sed, not sure about how Python measures up,
> >  but this seems to make perl ideally suited to text processing.
> 
> Python has regular expressions much like Perl. The only difference is
> that Perl carries syntactic support for them, while in Python regular
> expressions are ordinary objects with methods etc.

In many ways, Python's modularity is advantageous here.  However, since
(I believe) about Perl 5.2 or so, Perl's regular expressions aren't --
they're more powerful than regular expressions, because you can embed
arbitrary Perl code in them as part of the matching process.  Python's
regular expressions are very close to those of Perl 5.X for some X<2 (I
think it was 5.2 where the code-embedding trick was introduced, but
that's something of a guess on my part).

> > I also did a search of job
> > postings on a popular website. 108 jobs where listed that require
> > knowledge of Perl, only 17 listed required Python. Becomeing more
> > familiar with Perl might then be usefull for ones resume ?
> 
> It doesn't harm, of course. Recent statistics about programmers'
> salaries indicate, however, that Python ranks top (I somehow lost the URL).

"Software Development" magazine has run such polls for years, and the
fact that Pythonistas' salaries are at the top has been true since the
first such poll -- not a huge difference, but statistically significant.
What this finding _means_ is, of course, somewhat of a mystery
(correlation isn't causation), as is, of course, the OP's less formal
observation about job postings.


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


Re: Confused with methods

2005-02-06 Thread Dan Perl

"jfj" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I don't understand.
> We can take a function and attach it to an object, and then call it
> as an instance method as long as it has at least one argument:
>
> #
> class A:
>   pass
>
> def foo(x):
>   print x
>
> A.foo = foo
> a=A()
> a.foo()
> #
>
> However this is not possible for another instance method:
>
> 
> class A:
>  pass
>
> class B:
>  def foo(x,y)
>  print x,y
>
> b=B()
> A.foo = b.foo
> a=A()
>
> # error!!!
> a.foo()
> ##
>
> Python complains that 'foo() takes exactly 2 arguments (1 given)'.
> But by calling "b.foo(1)" we prove that it is indeed a function which 
> takes
> exactly one argument.
>
> Isn't that inconsistent?

You called b.foo(1) but a.foo().  Note one argument in the first call and no 
arguments in the second call.  Would you have called a.foo(1), you would 
have gotten the same result as with b.foo(1).  I suppose that was just a 
small omission on your part, but what are you trying to do anyway?  It's a 
very strange use of instance methods. 


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


Re: Confused with methods

2005-02-06 Thread Alex Martelli
jfj <[EMAIL PROTECTED]> wrote:

> I don't understand.
> We can take a function and attach it to an object, and then call it
> as an instance method as long as it has at least one argument:
> 
> #
> class A:
>pass
> 
> def foo(x):
>print x
> 
> A.foo = foo
> a=A()
> a.foo()
> #

Right.  If you want to understand how this happens, look at the
foo.__get__ special method, which makes foo (like every other function)
a *descriptor*.  One you've set foo as an attribute of class A, the
access a.foo calls foo.__get__(a, A) which returns an object of class
"instance method".


> However this is not possible for another instance method:
> 
> 
> class A:
>   pass
> 
> class B:
>   def foo(x,y)
>   print x,y
> 
> b=B()
> A.foo = b.foo

What you're assigning here as an attribute of class A is not a
descriptor: it does not have a special method __get__.

> a=A()
> 
> # error!!!
> a.foo()

Since A.foo does not have a method __get__, it's just returned when you
access it (on instance a).  It's already an instance method -- but it's
bound to instance b of class B.

> ##
> 
> Python complains that 'foo() takes exactly 2 arguments (1 given)'.
> But by calling "b.foo(1)" we prove that it is indeed a function which takes
> exactly one argument.

Calling something does not prove it's a function.  Python has a lot of
callable objects, and functions are just one callable types.  So, you're
mistaken if you think that by calling (whatever) you prove said whatever
is a function (of any kind).

The error message you're seeing does come from a function -- the im_func
attribute of b.foo, which is a function foo taking two arguments
(created and set into class B by the "def foo(x, y):" above, even though
you forgot the colon I'm sure you intended to type it).

 
> Isn't that inconsistent?

That Python has many callable types, not all of which are descriptors?
I don't see any inconsistency there.  Sure, a more generalized currying
(argument-prebinding) capability would be more powerful, but not more
consistent (there's a PEP about that, I believe).

If what you want is to focus on the error message, you can completely
separate it from the idea of having set b.foo as an attribute of class
A.  Just try calling b.foo() without arguments and you'll get exactly
the same error message -- from the underlying function foo, which is
also b.foo.im_func (the function's FIRST argument is bound to
b.foo.im_self, which is b; whence the error being about function foo
taking exactly two arguments and only one having been given).


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


Re: bad generator performance

2005-02-06 Thread Fredrik Lundh
Johannes Ahl-mann wrote:

> the program is supposed to manage bookmarks and i thought it would be a
> good idea to represent the bookmarks as a tree (with folders as internal
> nodes and bookmarks as leaves).
> so, a tree is never going to hold more than say 2000 nodes and is going
> to be rather wide than deep!

maybe

http://pyxml.sourceforge.net/topics/xbel/

stored and manipulated using

http://effbot.org/zone/element-index.htm

would simplify things for you?

 



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


Re: Python versus Perl ?

2005-02-06 Thread Courageous


> If Python is better than Perl, I'm curious how really significant
>those advantages are ?

The main advantage is Python's cleanliness. In Perl, there are so
many different ways of writing a thing, that to be adept in perl,
you have to know them all, otherwise you won't be able to read another
person's code.

Python and Perl accomplish similar things, but have strikingly different
design philosophies. Perl's design philosophy is the kitchen sink: throw
it all in. Python's is, "let's keep this simple." We add things carefully,
and with great deliberation, or not at all.

As a consequence, Python is far easier to learn than Perl.

This has non-trivial consequences on your enterprise operations.

For example, getting new engineers up to speed on the old code base is
a great deal easier.

C//

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


Re: pygame.mixer.music not playing

2005-02-06 Thread Marian Aldenhövel
Hi,
Search the net. You are not the first to try and build a jukebox out of pygame ;)
I did find a few, yes.
Currently this is a toy project as I am learning the language, so early
success means more to me than perfect results. And, as I said, I do not really
have an alternative.
Maybe some way to remote control another player would be in order. Leave it
to software that is specialized and all. But I would want something that runs
on Windows and Linux which narrows down my options.
You have a typo in the code you posted that may be your problem.
You are refering to the missing ' in the filename?
  pygame.mixer.music.load('file1.mp3)
No, that's not the problem. I did paste working code but I then edited out the
full absolute path that I had coded into the program and introduced the error.
I also tried your sample but no difference. Must be something on my system
as it does seem to play...
Ciao, MM
--
Marian Aldenhövel, Rosenhain 23, 53123 Bonn. +49 228 624013.
http://www.marian-aldenhoevel.de
"Wir brauchen keine Opposition, wir sind bereits Demokraten."
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I convert arithemtic string (like "2+2") to a number?

2005-02-06 Thread Michael Spencer
John J. Lee wrote:
"Adomas" <[EMAIL PROTECTED]> writes:

Well, a bit more secure would be
eval(expression, {'__builtins__': {}}, {})
or alike.

Don't believe this without (or even with ;-) very careful thought,
anyone.  Google for rexec.
John
This module provides a more systematic way to set up restricted evaluation:
"""Restricted evaluation
Main entry point: r_eval()
For usage see class tests or run them using testall()"""
import types
import compiler
import operator
import sys, os # used only for testing
ast = compiler.ast
class Eval_Error(Exception):
def __init__(self,error,descr = None,node = None):
self.error = error
self.descr = descr
def __repr__(self):
return "%s: %s" % (self.error, self.descr)
__str__ = __repr__
class AbstractVisitor(object):
"""Standard depth-first AST walker - dispatches to methods
based on Node class name"""
def __init__(self):
self._cache = {} # dispatch table
def visit(self, node,**kw):
if node is None: return None
cls = node.__class__
meth = self._cache.setdefault(cls,
getattr(self,'visit'+cls.__name__,self.default))
return meth(node, **kw)
def default(self, node, **kw):
for child in node.getChildNodes():
return self.visit(child, **kw)
visitExpression = default

class Eval(AbstractVisitor):
"""An AST walker that implements a replacement to built-in eval.
See r_eval for entry point/usage.
Provides hooks for managing name resolution, proxying objects,
and controlling attribute access
Does not implement:
List Comprehensions, Generator Expressions, Lambda
Ellipsis (can this be used without numpy?)
"""
def __init__(self, context = globals()):
super(Eval,self).__init__()
self.context = context
# Namespace interface.  Safe implementations should override these methods
# to implement restricted evaluation.  This implementation simply
# evals the name in self.context and provides no proxying or
# attribute lookup restrictions
def lookup(self, objname):
"""Called only by visitName.  Raise an exception here
to prevent any direct name resolution, but note that
objects may be returned by callables or attribute lookups"""
return eval(objname, self.context)
def getObject(self, obj):
"""Called by all name resolvers and by CallFunc.  Provides
a hook for proxying unsafe objects"""
return obj
def getAttribute(self,obj,attrname):
"""Called by visitGetattr"""
return getattr(obj,attrname)
# End Namespace interface
# Syntax nodes follow by topic group.  Delete methods to disallow
# certain syntax.
# Object constructor nodes
def visitConst(self, node, **kw):
return node.value
def visitDict(self,node,**kw):
return dict([(self.visit(k),self.visit(v)) for k,v in node.items])
def visitTuple(self,node, **kw):
return tuple(self.visit(i) for i in node.nodes)
def visitList(self,node, **kw):
return [self.visit(i) for i in node.nodes]
def visitSliceobj(self,node,**kw):
return slice(*[self.visit(i) for i in node.nodes])
def visitEllipsis(self,node,**kw):
raise NotImplementedError, "Ellipsis"
# Binary Ops
def visitAdd(self,node,**kw):
return self.visit(node.left) + self.visit(node.right)
def visitDiv(self,node,**kw):
return self.visit(node.left) / self.visit(node.right)
def visitFloorDiv(self,node,**kw):
return self.visit(node.left) // self.visit(node.right)
def visitLeftShift(self,node,**kw):
return self.visit(node.left) << self.visit(node.right)
def visitMod(self,node,**kw):
return self.visit(node.left) % self.visit(node.right)
def visitMul(self,node,**kw):
return self.visit(node.left) * self.visit(node.right)
def visitPower(self,node,**kw):
return self.visit(node.left) ** self.visit(node.right)
def visitRightShift(self,node,**kw):
return self.visit(node.left) >> self.visit(node.right)
def visitSub(self,node,**kw):
return self.visit(node.left) - self.visit(node.right)
# Unary ops
def visitNot(self,node,*kw):
return not self.visit(node.expr)
def visitUnarySub(self,node,*kw):
return -self.visit(node.expr)
def visitInvert(self,node,*kw):
return ~self.visit(node.expr)
def visitUnaryAdd(self,node,*kw):
return +self.visit(node.expr)
# Logical Ops
def visitAnd(self,node,**kw):
return reduce(lambda a,b: a and b,[self.visit(arg) for arg in 
node.nodes])
def visitBitand(self,node,**kw):
return reduce(lambda a,b: a & b,[self.visit(arg) for arg in node.nodes])
def visitBitor(self,node,**kw):
return reduce(lambda a,b: a | b,[self.visit(arg) for arg in node.nodes])
def visitBitxor(self,node,**kw):
return reduce(lambda a,b: a 

Re: IPython colors in windows

2005-02-06 Thread Claudio Grondi
Hi,

I have done some more work on Console.py
from the readline package version 1.12, adding
support for background colors and testing of proper
function of them (run the Console.py script to
see coloured output).
Added was also the possibility to set the default
text/background colors for colored output using:
  Console.setStandardBackgroundColorTo(strColor)
  Console.setStandardForegroundColorTo(strColor)
where strColor can be one of:
[
 '(dark)black'
,'(dark)red',
,'(dark)green'
,'(dark)yellow'
,'(dark)blue'
,'(dark)purple'
,'(dark)cyan'
,'(dark)white'
,'light black'
,'light red'
,'light green'
,'light yellow'
,'light blue'
,'light purple'
,'light cyan'
,'light white'
]

There are some comments added where e.g.
the colors are named including their HTML color
notation to clarify which colors are displayed.
I work on Windows 2000 SP 4, so it will be
interesting for me to get some feedback if the
colors are the same in other Windows versions.
Which colors are displayed on Linux/Unix by
the native readline?

There are also some other changes done to
make the code better readable (from my
personal point of view ;-)

The blnIPythonFixActive flag allows to set colored
text output of IPython to (dark)white background
(instead of the standard one, which is  in my
Console the 'light white' one i.e. I work with white
background as IDLE does).

Another modification is, that when a text without
escape sequences is passed to Console.write(),
no escape sequences are sent, so, that the
colouring stays the same until it is explicitely
reset. I find this behaviour more strightforward
than the implicit writing of texts in the standard
colors if no colors are specified.

If someone is interested to check it out I have
uploaded it to:
 http://people.freenet.de/AiTI-IT/Python/Console.py

The extended Console.py module can be used
standalone for writing of any coloured texts
to the console using alternatively .
  Console.setStandardBackgroundColorTo(strColor)
  Console.setStandardForegroundColorTo(strColor)
  with resetting the colors
or the build-in ANSI escape sequences for the
text and the background.

Utilizing the code or some parts of it in
the next release of readline is welcome.

Claudio

"Gary Bishop" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> On SourceForge you will find release 1.12 of my Python readline
> module. If you don't want to hack the colors, there is no reason to
> upgrade from 1.11 to 1.12. They *should* work the same.
>
> But if you'd like to hack the iPython colors this new version makes it
> possible.  In your ipythonrc file add a line like:
>
> execfile hackcolors.py
>
> Now in hackcolors.py you can change colors and backgrounds like this:
>
> hackcolors.py
> import readline
>
> # reach deep into the bowels of readline to get the color table
> escape_to_color = readline.rl.console.escape_to_color
>
> # change a color
> escape_to_color['0;32'] = 0x72
>
> del escape_to_color
> del readline
>
> #
>
> The two hex digits are the background and foreground color
> respectively. In the example above I'm setting the color to green on a
> grey background. Here is the table that is normally used to translate
> colors.
>
>   escape_to_color = { '0;30': 0x0, #black
>   '0;31': 0x4, #red
>   '0;32': 0x2, #green
>   '0;33': 0x4+0x2, #brown?
>   '0;34': 0x1, #blue
>   '0;35': 0x1+0x4, #purple
>   '0;36': 0x2+0x4, #cyan
>   '0;37': 0x1+0x2+0x4, #grey
>   '1;30': 0x1+0x2+0x4, #dark gray
>   '1;31': 0x4+0x8, #red
>   '1;32': 0x2+0x8, #light green
>   '1;33': 0x4+0x2+0x8, #yellow
>   '1;34': 0x1+0x8, #light blue
>   '1;35': 0x1+0x4+0x8, #light purple
>   '1;36': 0x1+0x2+0x8, #light cyan
>   '1;37': 0x1+0x2+0x4+0x8, #white
>   '0': None,
>   }
>
> An interested party should be able to arbitrarily map colors and their
> backgrounds.
>
> Enjoy,
> gb
>


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


Re: pickle/marshal internal format 'life expectancy'/backward compatibility

2005-02-06 Thread Philippe C. Martin
> How complicated is your data structure?  Might you just store:

that's the thing: I don't want to know: My goal is to be able to design
my SC applications without having to change the file system every time I
wish to add/subtract data to be store - I should say 'constant' data to be
stored for this pickle solution would only work with data that the SC
application just stores but does not understand/nor needs to.
For instance, the data structure could simple have a name and address to
start with (when the cards get issued) then the customer might want to add
the person's pictures. In such a case, I would not have to release a new
smart card application (could be burned in the silicon) but simply load
the new structure at issuance time.

> Of course, the security of this scheme is dependent on a lot, including
> the strength of sha, your ability to keep your secret key secret, the
> correctness of what I'm saying, etc etc etc.

The crypto/mutual authentification scheme is handled by the smart
card/HSM or in some _very_ light applications, by the smart card and
pycrypto (no HSM or batch card on the "terminal" side)

Regards,

Philippe





On Sun, 06 Feb 2005 02:20:34 -0500, Adam DePrince wrote:

> On Sat, 2005-02-05 at 17:04, Tim Peters wrote:
>> [Philippe C. Martin]
>> > I am looking into using the pickle format to store object/complex data
>> > structures into a smart card as it would make the design of the embedded
>> > application very simple.
>> >
>> > Yet the card might have to stay in the pocket of the customer for a few
>> > years, during which the back office application responsible for
>> > retrieving the information from the card might evolve as well as the
>> > python release it relies upon.
>> >
>> > Is there a commitment for python releases to be able to interpret
>> > 'older' pickle/marshal internal formats ?
>> 
>> Pickle and marshal have nothing in common, and there's no
>> cross-release guarantee about marshal behavior.  Pickles are safe in
>> this respect; indeed, each Python released to date has been able to
>> load pickles created by all earlier Python releases.  Of course a
>> pickle produced by a later Python may not be loadable by an earlier
>> Python, although even in that direction you can get cross-release
>> portability by forcing the newer Python to restrict itself to produce
>> obsolete pickle formats.  Reading Lib/pickletools.py in a current
>> release will explain all this.
> 
> 
> How complicated is your data structure?  Might you just store:
> 
> repr(  )
> 
> and eval it later?  Trust is an issue; you are vulnerable to malicious
> code, but no more so than with pickle or marshal.
> 
> One quick and dirty way to be a little safer is to "sign" the data you
> store.
> 
> # To save your data
> import sha
> import cPickle
> mysecret = "abc"
> mydata = {"what":"my data structure"}
> f = open( "/tmp/myfile.txt", "w+" )
> mydata = cPickle.dumps( mydata, protocol=0 )
> # I'm assuming this is a flash device ... lets be safe and not assume
> # that write is buffered ... 
> f.write( sha.new( mysecret + mydata ).digest() + mydata)
> 
> 
> 
> # To load your data
> import sha
> import cPickle
> mysecret = "abc
> f = open( "/tmp/myfile.txt", "w+" )
> hash = f.read( sha.digest_size )
> mydata = f.read()
> if sha.new( mysecret + mydata ).digest() != hash:
>   raise "Somebody is tring to hack you!" 
> mydata = cPickle.loads( mydata )
> 
> Of course, the security of this scheme is dependent on a lot, including
> the strength of sha, your ability to keep your secret key secret, the
> correctness of what I'm saying, etc etc etc.
> 
> 
> 
> 
> Adam DePrince

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


Re: CGI POST problem was: How to read POSTed data

2005-02-06 Thread Dan Perl

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Dan Perl wrote:
>
>> how is a multipart POST request parsed by CGIHTTPServer?
> [...]
> CGIHTTPServer, on the other hand, I have never really trusted. I would
> suspect that fella.

It turns out I was wrong thinking that the POST requests I was handling were 
multipart.  Blame that on my limited knowledge of HTTP.  At least the 
content-type header in the request doesn't say that they are multipart.  I 
checked with the an Ethereal sniffer and my Firefox browser on Windows sends 
a request with 'content-type: application/x-www-form-urlencoded' and the 
form data in the body of the request, after the headers.  I'll assume for 
now that this is a valid HTTP POST request as I believe that Firefox is 
responsible for it alone and that it is not determined by my HTML form.

Pierre Quentel's suggestion for an implementation of do_POST in the "How to 
read POSTed data" seems to handle requests of this kind, although I didn't 
personally try it.  But the run_cgi method in CGIHTTPServer expects the form 
data to be only in the POST header line, in the path of the URL, like in a 
GET request.  I cannot find form data being parsed any other way if the 
content-type is x-www-form-urlencoded.  Am I missing something?  Also, I 
don't know if this means anything, but shouldn't CGIHTTPServer use the cgi 
module if cgi has all those useful parsing utilities?

Dan 


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


Re: Insane import behaviour and regrtest.py: heeelp

2005-02-06 Thread Tim Peters
[John J. Lee]
> ...
> I tried it, and I get the same results as before (the test modules from my
> installed copy of Python are picked up instead of the local copies in
> my CVS checkout's Lib/test, apparently entirely contrary to sys.path).

Try running Python with -vv (that's two letter "v", not one letter
"w").  That will display a long-winded account of everything Python
tries in order to satisfy an import.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to read POSTed data

2005-02-06 Thread Dan Perl

"Pierre Quentel" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Here is an example of how to get the POST data :
>
> #def do_POST(self):
> #ctype, pdict = 
> cgi.parse_header(self.headers.getheader('content-type'))
> #length = int(self.headers.getheader('content-length'))
> #if ctype == 'multipart/form-data':
> #self.body = cgi.parse_multipart(self.rfile, pdict)
> #elif ctype == 'application/x-www-form-urlencoded':
> #qs = self.rfile.read(length)
> #self.body = cgi.parse_qs(qs, keep_blank_values=1)
> #else:
> #self.body = {}   # Unknown content-type
> ## throw away additional data [see bug #427345]
> #while select.select([self.rfile._sock], [], [], 0)[0]:
> #if not self.rfile._sock.recv(1):
> #break
> #self.handle_data()
>
> where handle_data() is the method where you will process the data received
>
> The part related to bug #427345 is copied from CGIHTTPServer
>
> For an example of use you can take a look at the CustomHTTPServer in 
> Karrigell (http://karrigell.sourceforge.net)

Pierre, I am repeating some questions I already stated in another thread, 
'CGI POST problem', but do you have any opinions on how CGIHTTPServer's 
do_POST handles requests?  It looks to me like it always expects form data 
to be part of the POST command header, in the path of the URL, just like a 
GET request.  Am I understanding the code incorrectly?  It would also make 
sense to me that CGIHTTPServer should use the cgi module like you do in your 
example, but it doesn't use cgi.  Any opinions on that?  Is there a history 
there?  I don't know enough about HTTP, especially about its history, but 
was this a change in the HTTP specification at some point?

Thanks,

Dan 


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


Re: How do I enter/receive webpage information?

2005-02-06 Thread Jorgen Grahn
On 05 Feb 2005 22:58:52 +, John J. Lee <[EMAIL PROTECTED]> wrote:
> Jorgen Grahn <[EMAIL PROTECTED]> writes:
> [...]
>> I did it this way successfully once ... it's probably the wrong approach in 
>> some ways, but It Works For Me.
>> 
>> - used httplib.HTTPConnection for the HTTP parts, building my own requests
>>   with headers and all, calling h.send() and h.getresponse() etc.
>> 
>> - created my own cookie container class (because there was a session
>>   involved, and logging in and such things, and all of it used cookies)
...

> I see little benefit and significant loss in using httplib instead of
> urllib2, unless and until you get a particulary stubborn problem and
> want to drop down a level to debug.  It's easy to see and modify
> urllib2's headers if you need to get low level.

That's quite possibly true. I remember looking at and rejecting
urllib/urllib2, but I cannot remember my reasons. Maybe I didn't feel they
were documented well enough (in Python 2.1, which is where I live).

[more useful info snipped]

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused with methods

2005-02-06 Thread jfj
Dan Perl wrote:
"jfj" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
However this is not possible for another instance method:

class A:
pass
class B:
def foo(x,y)
print x,y
b=B()
A.foo = b.foo
a=A()
# error!!!
a.foo()
##
Python complains that 'foo() takes exactly 2 arguments (1 given)'.
But by calling "b.foo(1)" we prove that it is indeed a function which 
takes
exactly one argument.

Isn't that inconsistent?

You called b.foo(1) but a.foo().  Note one argument in the first call and no 
arguments in the second call.  Would you have called a.foo(1), you would 
have gotten the same result as with b.foo(1).  I suppose that was just a 
small omission on your part, but what are you trying to do anyway?  It's a 
very strange use of instance methods. 


No omission.
If I say:
x=b.foo
x(1)
Then, without looking at the previous code, one can say that "x" is a
function which takes one argument. Continuing with "x":
A.foo = x
# this is ok
A.foo(1)
a=A()
# this is not ok
a.foo()
I expected that when we add this "x" to a class's dictionary and
then we request it from an instance of that class, it will be
converted to an bound-method and receive its --one-- argument
from the referring instance.
So "a.foo()" == "A.foo(a)" == "x(a)" == "b.foo(a)" == "B.foo(b,a)",
or at least "why not?" (head exploded?:)
I'm not trying to do something specific with this though.
G.
--
http://mail.python.org/mailman/listinfo/python-list


Re: An Ode To My Two Loves

2005-02-06 Thread Jorgen Grahn
On Sat, 05 Feb 2005 12:33:47 -0500, Jamey Cribbs <[EMAIL PROTECTED]> wrote:
> At the risk of calling my manhood into question,
...
> Under the influence of some kind of strange force and will probably be 
> embarrassed when he snaps out of it,

You shouldn't be -- I don't think I've seen anyone talk much about this
before, at least not from this angle.

It's something that worries me frequently -- I feel guilty when I introduce
Python into ("force Python upon") an organization. Because I hate having
/other/ people's favorite toy languages forced down /my/ throat ...

I also notice I forget one language after doing another for a few weeks. And
it's not just brackets and semicolons -- I also try to use one language's
idioms in the other. People who /claim/ they have no trouble switching
languages seem to have the same problem.

I refuse to think that Using One Language For Everything is the
solution. But I cannot explain it rationally.

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confused with methods

2005-02-06 Thread jfj
Alex Martelli wrote:
jfj <[EMAIL PROTECTED]> wrote:
Isn't that inconsistent?

That Python has many callable types, not all of which are descriptors?
I don't see any inconsistency there.  Sure, a more generalized currying
(argument-prebinding) capability would be more powerful, but not more
consistent (there's a PEP about that, I believe).
Thanks for the explanation.
The inconsistency I see is that if I wanted this kind of behavior
I would've used the staticmethod() builtin (which in a few words
alters __get__ to return the function unmodified).
So I would write
 A.foo = staticmethod (b.foo)
But now, it always acts as staticmethod:(
Anyway, if there's a PEP about it, I'm +1 because its "pythonic".
G.
--
http://mail.python.org/mailman/listinfo/python-list


Re: variable declaration

2005-02-06 Thread Jeremy Bowers
On Sun, 06 Feb 2005 07:30:33 -0500, Arthur wrote:
> What if:
> 
> There was a well conducted market survey conclusive to the effect that
> adding optional strict variable declaration would, in the longer run,
> increase Python's market share dramatically.
> 
> It just would.
> 
> Why would it?

What if, by eating a special mixture of cheddar and marshmallows, you
could suddenly fly?

It just would.

Why would it?

(The point, since I don't trust you to get it: The "absurd question" is
neither a valid argument technique, nor is it even good rhetoric. You
might as well go straight to "What if I'm right and you're wrong? What
then, huh?")

> My sense of how the real world works is that there is going to be one
> anti-Python advocate lying in wait for the first bug he can find that he
> can say would have been caught if Python had strict variable declaration,
> as he always knew it should.
> 
> He wants to be the PHB someday. The current PHB knows that, and since
> being sensitive to these kinds of realities is how he got to be the PHB,
> he is too smart to open himself up to this kind of risk.
> 
> The PHB can pretty safely make the use of the option optional.  As long as
> he is a position to jump down the throat of the programmer who created the
> bug.

You really aren't very good at this "debate" thing.

"Look, I can construct a certain scenario whereby the dangers you propose
don't occur (assuming that I'm even right about my scenario in the first
place which is highly questionable). How do you respond to *that*? Huh?
Huh? Huh? Where's your precious 'overwhelming pattern' now?"

It hasn't gone anywhere.

> What is the correct language design decision in light of these realities?

In light of the above, I question your use of the plural.

> But isn't this kind of where Python is at the moment?

Only for you.

Despite the tone of the rest of this message, I mean that. It's obviously
a huge stumbling block for you. It isn't for the rest of us, and once
again, I assure you, it's going to take more than spinning implausible
isolated entirely theoretical examples to convince us otherwise.

Not only do you argue solely from anecdote, even the aforementioned
"implausible isolated entirely theoretical" anecdote, it appears to be all
you understand. You're going to have to do better than that. Producing a
*real* study that shows declaration would be a good thing, instead of an
implausible entirely theoretical one, would be a good start.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python versus Perl ?

2005-02-06 Thread Jorgen Grahn
On 6 Feb 2005 05:19:09 -0800, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
...
>  I'm a software engineer, familiar with C++ objected oriented
> development, but have been using Perl because it is great for pattern
> matching, text processing, and automated testing. Our company is really
> fixated on risk managnemt and the only way I can do enough testing
> without working overtime (which some people have ended up doing) is by
> automating my testing. That's what got me started on Perl.
> 
>  I've read that many people prefer Python and that it is better than
> Perl. However, I want to ask a few other questions.

I could go on and on, but this essay by Eric Raymond says it better:

  http://www.linuxjournal.com/article/3882

> 3. Perl is installed on our system and alot of other systems.
> You don't have to make sys admins go out of there way to make it
> available. It's usualy allready there.

Python is in most Linux installations ... but it's much more rare than perl
elsewhere. Yes, this is a reason to write smaller text-processing and
automation hacks in perl.

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


newbie wants to compile python list of filenames in selected directories

2005-02-06 Thread anthonyberet
Hi, I am new at Python, and very rusty at the one language I was good 
at, which was BASIC.

I want to write a script to compare filenames in chosen directories, on 
windows machines. Ideally it would compose a list of strings of all the 
filenames in the directories, and those directories would be chosable by 
the user of the script.

I am quite happy to do my own legwork on this , I realise it is simple 
stuff, but can anyone point me in the right direction to start?

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


Re: newbie wants to compile python list of filenames in selected directories

2005-02-06 Thread Greg Krohn
anthonyberet wrote:
Hi, I am new at Python, and very rusty at the one language I was good 
at, which was BASIC.

I want to write a script to compare filenames in chosen directories, on 
windows machines. Ideally it would compose a list of strings of all the 
filenames in the directories, and those directories would be chosable by 
the user of the script.

I am quite happy to do my own legwork on this , I realise it is simple 
stuff, but can anyone point me in the right direction to start?

Thanks
os.listdir does almost exactly what you are asking for. For a little 
more flexibility, you can use os.path.walk, although it's not quite as 
newb friendly.

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


Re: pygame.mixer.music not playing

2005-02-06 Thread Greg Krohn
Marian Aldenhövel wrote:
Hi,
I am trying to make pygame play music on windows. This simple program:
import pygame,time
pygame.init()
print "Mixer settings", pygame.mixer.get_init()
print "Mixer channels", pygame.mixer.get_num_channels()
pygame.mixer.music.set_volume(1.0)
pygame.mixer.music.load('file1.mp3)
print "Play"
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
print "Playing", pygame.mixer.music.get_pos()
time.sleep(1)

print "Done"
I tried this exact same code (except the mp3 filename, of course) on my 
machine and it worked fine. ActivePython 2.3.4 and Pygame 1.6. Could it 
be a hardware problem?

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


Re: variable declaration

2005-02-06 Thread Arthur
On Sun, 06 Feb 2005 08:20:29 -0500, Jeremy Bowers <[EMAIL PROTECTED]>
wrote:

>On Sun, 06 Feb 2005 07:30:33 -0500, Arthur wrote:
>> What if:
>> 
>> There was a well conducted market survey conclusive to the effect that
>> adding optional strict variable declaration would, in the longer run,
>> increase Python's market share dramatically.
>> 
>> It just would.
>> 
>> Why would it?
>
>What if, by eating a special mixture of cheddar and marshmallows, you
>could suddenly fly?
>
>It just would.
>
>Why would it?
>
>(The point, since I don't trust you to get it: The "absurd question" is
>neither a valid argument technique, nor is it even good rhetoric. You
>might as well go straight to "What if I'm right and you're wrong? What
>then, huh?")

You miss my point in so many ways, its not worth enumerating.  Most
essentially is the fact that I am making no effort to be right about
anything, and don't care to be right about anything, and know better
than to hope to be  right about anything here.

>
>> My sense of how the real world works is that there is going to be one
>> anti-Python advocate lying in wait for the first bug he can find that he
>> can say would have been caught if Python had strict variable declaration,
>> as he always knew it should.
>> 
>> He wants to be the PHB someday. The current PHB knows that, and since
>> being sensitive to these kinds of realities is how he got to be the PHB,
>> he is too smart to open himself up to this kind of risk.
>> 
>> The PHB can pretty safely make the use of the option optional.  As long as
>> he is a position to jump down the throat of the programmer who created the
>> bug.
>
>You really aren't very good at this "debate" thing.

I'm a lot bettter at  it, I think, when I am trying to debate.  

*You* don't get it. I'm not. 

>
>"Look, I can construct a certain scenario whereby the dangers you propose
>don't occur (assuming that I'm even right about my scenario in the first
>place which is highly questionable). How do you respond to *that*? Huh?
>Huh? Huh? Where's your precious 'overwhelming pattern' now?"
>
>It hasn't gone anywhere.
>
>> What is the correct language design decision in light of these realities?
>
>In light of the above, I question your use of the plural.

And you would question the use of the singular, as well, if I catch
your dirft. 

>
>> But isn't this kind of where Python is at the moment?
>
>Only for you.
>
>Despite the tone of the rest of this message, I mean that. It's obviously
>a huge stumbling block for you. It isn't for the rest of us, and once
>again, I assure you, it's going to take more than spinning implausible
>isolated entirely theoretical examples to convince us otherwise.

I don't know who the rest of you are.  Whoever the rest of you are,
I'm OK with not being one of you. Really I am.

>Not only do you argue solely from anecdote, even the aforementioned
>"implausible isolated entirely theoretical" anecdote, it appears to be all
>you understand. You're going to have to do better than that. Producing a
>*real* study that shows declaration would be a good thing, instead of an
>implausible entirely theoretical one, would be a good start.

I am arguing, to the extent that I am arguing, from the hypothetical.
You can counter by saying that my hypothical premise is not even a
possiblity.

Among what you don't understand. I think, is that I would be wishing
that you were right.  But of course you wouldn't be.

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


Re: pygame.mixer.music not playing

2005-02-06 Thread Daniel Bickett
Marian Aldenhövel wrote:
> Maybe some way to remote control another player would be in order. Leave it
> to software that is specialized and all. But I would want something that runs
> on Windows and Linux which narrows down my options.

Perhaps Zinf?

http://www.zinf.org/

-- 
Daniel Bickett
dbickett at gmail.com
http://heureusement.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: empty classes as c structs?

2005-02-06 Thread Steven Bethard
Nick Coghlan wrote:
By assigning to __dict__ directly, you can use the attribute view either 
as it's own dictionary (by not supplying one, or supplying a new one), 
or as a convenient way to programmatically modify an existing one. For 
example, you could use it to easily bind globals without needing the 
'global' keyword:

Py> class attr_view(object):
... def __init__(self, data):
... self.__dict__ = data
...
Py> def f():
...   gbls = attr_view(globals())
...   gbls.x = 5
...
Py> x
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'x' is not defined
Py> f()
Py> x
5
Hmm... interesting.  This isn't the main intended use of 
Bunch/Struct/whatever, but it does seem like a useful thing to have... 
I wonder if it would be worth having, say, a staticmethod of Bunch that 
produced such a view, e.g.:

class Bunch(object):
...
@staticmethod
def view(data):
result = Bunch()
result.__dict__ = data
return result
Then you could write your code as something like:
gbls = Bunch.view(globals())
I'm probably gonna need more feedback though from people though to know 
if this is a commonly desired use case...

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


loops -> list/generator comprehensions

2005-02-06 Thread jamesthiele . usenet
I wrote this little piece of code to get a list of relative paths of
all files in or below the current directory (*NIX):

walkList  = [(x[0], x[2]) for x in os.walk(".")]
filenames = []
for dir, files in walkList:
filenames.extend(["/".join([dir, f]) for f in files])

It works fine, I don't need to change it, but I know there is a one
liner list/generator comprehension to do this - I'm just not well
enough versed in comprehensions to figure it out. Can someone please
show me what it is?

Even better, is there a generalized way to transform simple loops into
comprehensions that someone can point me to?

james

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


Re: ANN: Frog 1.3 released (python 'blog' application)

2005-02-06 Thread Irmen de Jong
Jorey Bump wrote:
Thanks, I'm impressed. However, I feel as though the file manager should be 
integrated with Frog in a such a way that it is enabled automatically for 
users when they are created. The mkuser.py script felt a bit awkward, 
especially when creating users was so easy in the administrative interface. 
I can only agree with this :)
And once logged in, a user shouldn't need to authenticate to the file 
manager separately. 
That is a feature that Snakelets (the web server) doesn't provide yet.
You can only be authenticated on a per-webapp basis.
It is on my to-do list to add a centralized login thing.
I understand that the file manager was developed as a standalone webapp, 
but the virtual user support is a big plus in Frog, and it would be great 
to start uploading images to blogfiles/user/ right away.
Agreed, and I think it will be better integrated in a future version.
For now, you'll just have to login twice or hack your own centralized
logon thing ;-)
Have fun,
--Irmen de Jong
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple constructors

2005-02-06 Thread Steven Bethard
Alex Martelli wrote:
If you want to do this
all the time, you could even build appropriate infrastructure for this
task -- a little custom descriptor and metaclass, and/or decorators.
Such infrastructure building is in fact fun and instructive -- as long
as you don't fall into the trap of *using* such complications in
production code, where Python's simplicity rules;-).
+1 QOTW.
I think this is one of the "great truths" of Python.  Descriptors, 
metaclasses, decorators, etc. are all there to let you do interesting, 
useful things.  But if you're using such constructs for more than a few 
special cases, then you're missing out on a simple solution that Python, 
almost certainly, makes beautiful.

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


Re: remove duplicates from list *preserving order*

2005-02-06 Thread Francis Girard
Hi,

I think your last solution is not good unless your "list" is sorted (in which 
case the solution is trivial) since you certainly do have to see all the 
elements in the list before deciding that a given element is not a duplicate. 
You have to exhaust the iteratable before yielding anything.

Besides that, I was thinking that the best solution presented here proceed in 
two steps :

1- Check that an element is not already in some ordered data type of already 
seen element

2- If not, put the element in that structure

That's probably twice the work.

There might be some way to do both at the same time, i.e.

- Put the element in the data structure only if not already there and tell me, 
with some boolean, if you did put the element.

Then you have to do the work of finding the right place where to insert 
(fetch) the element only once. I don't see any easy way to do this in python, 
other than rolling your sleeves and code your own data structure in Python, 
which would be slowlier than the provided dict or set C implementation.

I think this a hole into the Pythin libs.

Regards

Francis Girard

Le jeudi 3 Février 2005 21:39, Steven Bethard a écrit :
> I'm sorry, I assume this has been discussed somewhere already, but I
> found only a few hits in Google Groups...  If you know where there's a
> good summary, please feel free to direct me there.
>
>
> I have a list[1] of objects from which I need to remove duplicates.  I
> have to maintain the list order though, so solutions like set(lst), etc.
> will not work for me.  What are my options?  So far, I can see:
>
> def filterdups(iterable):
>  result = []
>  for item in iterable:
>  if item not in result:
>  result.append(item)
>  return result
>
> def filterdups(iterable):
>  result = []
>  seen = set()
>  for item in iterable:
>  if item not in seen:
>  result.append(item)
>  seen.add(item)
>  return result
>
> def filterdups(iterable):
>  seen = set()
>  for item in iterable:
>  if item not in seen:
>  seen.add(item)
>  yield item
>
> Does anyone have a better[2] solution?
>
> STeve
>
> [1] Well, actually it's an iterable of objects, but I can convert it to
> a list if that's helpful.
>
> [2] Yes I know, "better" is ambiguous.  If it helps any, for my
> particular situation, speed is probably more important than memory, so
> I'm leaning towards the second or third implementation.

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


ANN: 'twander' 3.193 Released And Available

2005-02-06 Thread Tim Daneliuk
'twander' Version 3.193 is now released and available for download at:
 http://www.tundraware.com/Software/twander
The last public release was 3.160.
Existing users are encouraged to upgrade to this release as it has
a number of bug fixes and several significant new features including:
  - It is now possible to "filter" which files even appear in the
interface using an arbitrary (Python) regular expression.
This is very handy in large directories with, say, thousands
of files, when you only want to deal with some small subset of
those files.
  - The configuration language now supports "Execution Variables" -
aka "backtick" variables - for embedding calls to external
programs into the configuration.
  - User prompting now supports default values.  You can set a
user prompt and pre-load the most likely response to the question
in the reply dialog.
Complete details of all fixes, changes, and new features can be found in
the WHATSNEW.txt file included in the distribution.
Users are strongly encouraged to join the twander-users mailing list as
described in the documentation.
A FreeBSD port has been submitted as well.

What Is 'twander'?
--
'twander' is a macro-programmable Filesystem Browser that runs on both
Unix-like systems as well as Win32 systems. It embraces the best ideas
of both similar GUI-driven programs (Konqueror, Windows Explorer) as
well as text-based interfaces (Midnight Commander, List, Sweep).
Or, If You Prefer The "Elevator Pitch"
--
'twander' is:
   - A better file browser for Unix and Win32. (Tested on FreeBSD, Linux, 
Win32.)
   - A way to make browsing the same on all the OSs you use.
   - A macro-programmable tool that lets *you* define the features.
   - A GUI navigation front-end for your shell.
   - A way to "can" workflows for your technically-challenged colleagues.
   - A way to free yourself from the shackles of the mouse.
   - A way to significantly speed up your day-to-day workflow.
   - A Python/Tkinter application - about 5000 lines of code/comments
   - A RCT (Really Cool Tool) that will have you addicted in a day or two
See the web page for more information, a screen shot, and the complete
documentation.
--
Tim Daneliuk
[EMAIL PROTECTED]








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


Re: loops -> list/generator comprehensions

2005-02-06 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
I wrote this little piece of code to get a list of relative paths of
all files in or below the current directory (*NIX):
walkList  = [(x[0], x[2]) for x in os.walk(".")]
filenames = []
for dir, files in walkList:
filenames.extend(["/".join([dir, f]) for f in files])
It works fine, I don't need to change it, but I know there is a one
liner list/generator comprehension to do this - I'm just not well
enough versed in comprehensions to figure it out. Can someone please
show me what it is?
I've used os.path.join instead of "/".join since it's more general, but 
other than that, this should be eqivalent:

filenames = [os.path.join(dirpath, filename)
 for dirpath, _, filenames in os.walk('.')
 for filename in filenames]

Even better, is there a generalized way to transform simple loops into
comprehensions that someone can point me to?
Well, generally, you need to write your loops to use an append, and then 
the translation to LC is simpler.

filenames = []
for dirpath, _, filenames in os.walk('.'):
for filename in filenames:
filenames.append(os.path.join(dirpath, filename))
Now that you know what it looks like with an append, you simply move the 
expression in the append to the top, and leave the fors in the same order:

filenames = [os.path.join(dirpath, filename)
 for dirpath, _, filenames in os.walk('.')
 for filename in filenames]
HTH,
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: Error!

2005-02-06 Thread administrata
"John Machin" <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> administrata wrote:
> > I'm programming Car Salesman Program.
> > It's been "3 days" learning python...
> 
> >From whom or what book or what tutorial?
> 
> > But, i got problem
> 
> You got problemS. What Jeff & Brian wrote, plus:
> 
> You have "change" instead of "charge".
> 
> You forgot to add in the base price -- "actual price" according to you
> comprises only the taxes and fees. Where is your car yard? We'd each
> like to order a nice shiny red Ferrari :-)
> 
> Cheers,
> John

Thx 4 helps everyone! :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: remove duplicates from list *preserving order*

2005-02-06 Thread Steven Bethard
Francis Girard wrote:
I think your last solution is not good unless your "list" is sorted (in which 
case the solution is trivial) since you certainly do have to see all the 
elements in the list before deciding that a given element is not a duplicate. 
You have to exhaust the iteratable before yielding anything.
I don't follow.  The first time I see an element, it is not a duplicate, 
so I yield it.  After that, the element should show up in the 'seen' 
list, which means I won't yield any of the remaining equivalent 
elements.  Could you explain your logic here?

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


Re: "Collapsing" a list into a list of changes

2005-02-06 Thread Alan McIntyre
Thanks to everybody that responded; I appreciate all the input, even if 
I didn't respond to all of it individually. :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to read POSTed data

2005-02-06 Thread Pierre Quentel

Pierre, I am repeating some questions I already stated in another thread, 
'CGI POST problem', but do you have any opinions on how CGIHTTPServer's 
do_POST handles requests?  It looks to me like it always expects form data 
to be part of the POST command header, in the path of the URL, just like a 
GET request.  Am I understanding the code incorrectly?  
The code in CGIHTTPServer is not very easy to understand, but it does
read the request body, as many bytes as indicated in the Content-Length
header. See line 262 (in the Python 2.4 distribution) or 250 in Python 
2.3 (this is the Windows version) :

data = self.rfile.read(nbytes)
Then this data is sent to the standard input of the CGI script. If this 
script is a Python program using the cgi module, it usually creates a 
cgi.FieldStorage() instance : upon creation, the standard input is read 
(in self.read_urlencoded() for instance) and the string collected is 
processed to produce a dictionary-like object, with keys matching the 
form field names

This is compliant with the CGI specification (HTTP doesn't say anything 
about the management of data sent by POST requests). The code I sent is 
an alternative to CGI, leaving the management of this data (available in 
self.body) to a method of the RequestHandler instance

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


Re: Insane import behaviour and regrtest.py: heeelp

2005-02-06 Thread John J. Lee
Tim Peters <[EMAIL PROTECTED]> writes:

> [John J. Lee]
> > ...
> > I tried it, and I get the same results as before (the test modules from my
> > installed copy of Python are picked up instead of the local copies in
> > my CVS checkout's Lib/test, apparently entirely contrary to sys.path).
> 
> Try running Python with -vv (that's two letter "v", not one letter
> "w").  That will display a long-winded account of everything Python
> tries in order to satisfy an import.

Thanks.

I'm still puzzled, though.  Reading the -vv output, I see that when
importing test_cookielib (which is currently the only line in my
regrtest.py -f file), Python doesn't appear to look in Lib/test to
find module "test.test_cookielib" (the actual string passed by
regrtest.py to __import__): see the output below.

Why does Python not look in

/usr/local/src/python/python/dist/src/Lib/test

for test_cookielib.py{,c,o}??


Snippet to show print statements I added to my regrtest.py :

. try:
. save_stdout = sys.stdout
. try:
. if cfp:
. sys.stdout = cfp
. print test  # Output file starts with test name
. if test.startswith('test.'):
. abstest = test
. else:
. # Always import it from the test package
. abstest = 'test.' + test
.+print >> sys.stderr, ">>>sys.path", sys.path
. the_package = __import__(abstest, globals(), locals(), [])
.+print >> sys.stderr, ">>>the_package.__path__", 
the_package.__path__
. the_module = getattr(the_package, test)
. # Most tests run to completion simply as a side-effect of

Only other change to regrtest.py:

. if __name__ == '__main__':
. # Remove regrtest.py's own directory from the module search path.  This
. # prevents relative imports from working, and relative imports will screw
. # up the testing framework.  E.g. if both test.test_support and
. # test_support are imported, they will not contain the same globals, and
. # much of the testing framework relies on the globals in the
. # test.test_support module.
. mydir = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
. i = pathlen = len(sys.path)
. while i >= 0:
. i -= 1
. if os.path.abspath(os.path.normpath(sys.path[i])) == mydir:
. del sys.path[i]
. if len(sys.path) == pathlen:
. print 'Could not find %r in sys.path to remove it' % mydir
.+lib = "/usr/local/src/python/python/dist/src/Lib"
.+sys.path.insert(0, lib)
.-main()
.+main(testdir=lib)


Here's what I've got in my CVS checkout:

Lib[0]$ pwd
/hda/usr/local/buf/python/python/dist/src/Lib
Lib[0]$ ls test/test_cookielib* | grep -v 'patch\|latest\|~'
test/test_cookielib.py
test/test_cookielib.pyc


And the output:

Lib[0]$ python2.4 -u -vv test/regrtest.py -f test/torun -v 2>&1 | less
[...long snip...]
# trying /usr/local/lib/python2.4/lib-tk/time.py
# trying /usr/local/lib/python2.4/lib-tk/time.pyc
# trying /usr/local/lib/python2.4/lib-dynload/time.so
dlopen("/usr/local/lib/python2.4/lib-dynload/time.so", 2);
import time # dynamically loaded from 
/usr/local/lib/python2.4/lib-dynload/time.so
test_cookielib
>>>sys.path ['/usr/local/src/python/python/dist/src/Lib', 
>>>'/home/john/lib/python', '/usr/local/lib/python24.zip', 
>>>'/usr/local/lib/python2.4', '/usr/local/lib/python2.4/plat-linux2', 
>>>'/usr/local/lib/python2.4/lib-tk', 
>>>'/usr/local/lib/python2.4/lib-dynload', 
>>>'/usr/local/lib/python2.4/site-packages']
# trying /usr/local/lib/python2.4/test/test_cookielib.so
# trying /usr/local/lib/python2.4/test/test_cookielibmodule.so
# trying /usr/local/lib/python2.4/test/test_cookielib.py
import test.test_cookielib # from 
/usr/local/lib/python2.4/test/test_cookielib.py
# can't create /usr/local/lib/python2.4/test/test_cookielib.pyc
# trying /usr/local/lib/python2.4/test/re.so
# trying /usr/local/lib/python2.4/test/remodule.so
# trying /usr/local/lib/python2.4/test/re.py
# trying /usr/local/lib/python2.4/test/re.pyc
# trying /usr/local/lib/python2.4/test/time.so
# trying /usr/local/lib/python2.4/test/timemodule.so
# trying /usr/local/lib/python2.4/test/time.py
# trying /usr/local/lib/python2.4/test/time.pyc
# trying /usr/local/lib/python2.4/test/test.so
# trying /usr/local/lib/python2.4/test/testmodule.so
# trying /usr/local/lib/python2.4/test/test.py
# trying /usr/local/lib/python2.4/test/test.pyc
>>>the_package.__path__ ['/usr/local/lib/python2.4/test']
# trying /usr/local/lib/python2.4/test/test_sets.so
# trying /usr/local/lib/python2.4/test/test_setsmodule.so
# trying /usr/local/lib/python2.4/test/test_sets.py
# /usr/local/lib/python2.4/test/test_sets.pyc matches 
/usr/local/lib/python2.4/test/test_sets.py
import test.test_sets # precompiled from 
/usr/local/lib/python2.4/test/test_sets.pyc
# trying /usr/local/lib/python2.4/test/operator.so
# tryi

Re: newbie wants to compile python list of filenames in selected directories

2005-02-06 Thread John J. Lee
Greg Krohn <[EMAIL PROTECTED]> writes:
> anthonyberet wrote:
[...]
> > I want to write a script to compare filenames in chosen directories,
> > on windows machines. Ideally it would compose a list of strings of
> > all the filenames in the directories, and those directories would be
> > chosable by the user of the script.
[...]
> 
> os.listdir does almost exactly what you are asking for. For a little
> more flexibility, you can use os.path.walk, although it's not quite as
> newb friendly.
> 
> -greg

os.walk is perhaps newbie-friendlier than os.path.walk.

Or perhaps not: not having read the tutorial &c. for some time, I
don't know how good they are on generators...


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


[noob] Questions about mathematical signs...

2005-02-06 Thread administrata
Hi! I'm programming maths programs.
And I got some questions about mathematical signs.

1. Inputing suqare like a * a, It's too long when I do time-consuming
   things. Can it be simplified?

2. Inputing fractions like (a / b) + (c / d), It's tiring work too.
   Can it be simplified?

3. How can i input root?

thx 4 reading :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Googling for wmi and python....

2005-02-06 Thread Harald Massa
I upgraded Python to 2.4

now the game really starts, looking all over the internet for all the 
packages ... I needed Tim Goldens WMI ... and googeld, dropping there:


http://www.microsoft.com/technet/scriptcenter/scripts/python/misc/wmi/defau
lt.mspx

With comment: Sample scripts for retrieving WMI configuration information. 
These sample scripts were written using Python for Windows. For sample 
scripts written using VBScript, please visit the Script Repository home 
page.


And that is above Tims GREAT WMI.module ... 

just wanted to drop that note.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: empty classes as c structs?

2005-02-06 Thread Alex Martelli
Steven Bethard <[EMAIL PROTECTED]> wrote:

> Hmm... interesting.  This isn't the main intended use of 
> Bunch/Struct/whatever, but it does seem like a useful thing to have...
> I wonder if it would be worth having, say, a staticmethod of Bunch that
> produced such a view, e.g.:
> 
> class Bunch(object):
>  ...
>  @staticmethod
>  def view(data):
>  result = Bunch()
>  result.__dict__ = data
>  return result
> 
> Then you could write your code as something like:
> 
> gbls = Bunch.view(globals())
> 
> I'm probably gonna need more feedback though from people though to know
> if this is a commonly desired use case...

Reasonably so, is my guess.  Witness the dict.fromkeys classmethod -- it
gives you, on dict creation, the same kind of nice syntax sugar that
wrapping a dict in a bunch gives you for further getting and setting
(and with similar constraints: all keys must be identifiers and not
happen to clash with reserved words).

I think this ``view'' or however you call it should be a classmethod
too, for the same reason -- let someone handily subclass Bunch and still
get this creational pattern w/o extra work.  Maybe a good factoring
could be something like:

class Bunch(object):

def __init__(self, *a, **k):
self.__dict__.update(*a, **k)

def getDict(self):
return self.__dict__

def setDict(self, adict):
self.__dict__ = adict

theDict = property(getDict, setDict, None, 
   "direct access to the instance dictionary"
  )

@classmethod
def wrapDict(cls, adict, *a, **k):
result = cls.__new__(cls, *a, **k)
result.setDict(adict)
cls.__init__(result, *a, **k)
return result

I'm thinking of use cases where a subclass of Bunch might override
setDict (to do something else in addition to Bunch.setDict, e.g.
maintain some auxiliary data structure for example) -- structuring
wrapDict as a classmethod in a ``Template Method'' DP might minimize the
amount of work, and the intrusiveness, needed for the purpose.  (I don't
have a real-life use case for such a subclass, but it seems to cost but
little to provide for it as a possibility anyway).

[[given the way property works, one would need extra indirectness in
getDict and setDict -- structuring THEM as Template Methods, too -- to
fully support such a subclass; but that's a well-known general issue
with property, and the cost of the extra indirection -- mostly in terms
of complication -- should probably not be borne here, it seems to me]]


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


Re: newbie wants to compile python list of filenames in selected directories

2005-02-06 Thread Caleb Hattingh
Hi Anthony
Here is some stuff to get you started (this is from memory, I'm not  
checking it, but should be mostly helpful):

***
import os
os.chdir('C:\My Documents')  # Can use this to jump around to different  
folders
fileNames = os.listdir('.')  # Checks the now current folder
namesToMatch = ['readme.txt','readme.doc'] # Buncha names to find

for item in fileNames:  # check every filename
  if item in namesToMatch:  # is this item in the required list?
print 'Match found: '+item  # if you found one, say so.
***
Hope this helps.
Caleb

On Sun, 06 Feb 2005 18:29:34 +, anthonyberet <[EMAIL PROTECTED]> wrote:
Hi, I am new at Python, and very rusty at the one language I was good  
at, which was BASIC.

I want to write a script to compare filenames in chosen directories, on  
windows machines. Ideally it would compose a list of strings of all the  
filenames in the directories, and those directories would be chosable by  
the user of the script.

I am quite happy to do my own legwork on this , I realise it is simple  
stuff, but can anyone point me in the right direction to start?

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


Re: loops -> list/generator comprehensions

2005-02-06 Thread Caleb Hattingh
I would be interested to see an example of code that is more concise but  
yet as *clear* as the one you already have.  I can actually read and  
understand what you've got there.   That's cool :)

On 6 Feb 2005 11:28:37 -0800, <[EMAIL PROTECTED]> wrote:
I wrote this little piece of code to get a list of relative paths of
all files in or below the current directory (*NIX):
walkList  = [(x[0], x[2]) for x in os.walk(".")]
filenames = []
for dir, files in walkList:
filenames.extend(["/".join([dir, f]) for f in files])
It works fine, I don't need to change it, but I know there is a one
liner list/generator comprehension to do this - I'm just not well
enough versed in comprehensions to figure it out. Can someone please
show me what it is?
Even better, is there a generalized way to transform simple loops into
comprehensions that someone can point me to?
james
--
http://mail.python.org/mailman/listinfo/python-list


Re: [noob] Questions about mathematical signs...

2005-02-06 Thread Jeff Epler
On Sun, Feb 06, 2005 at 12:26:30PM -0800, administrata wrote:
> Hi! I'm programming maths programs.
> And I got some questions about mathematical signs.
> 
> 1. Inputing suqare like a * a, It's too long when I do time-consuming
>things. Can it be simplified?

You can write powers with the "**" operator.  In this case,
a ** 2

> 2. Inputing fractions like (a / b) + (c / d), It's tiring work too.
>Can it be simplified?

Because of the rules of operator precedence,
a / b + c / d
has the same meaning as the expression you gave.

> 3. How can i input root?

Assuming that you've already executed
import math
Here are some ways to find the square root of a number:
math.sqrt(4)
4 ** .5
math.pow(4, .5)

Jeff


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

Re: IPython colors in windows

2005-02-06 Thread Fernando Perez
Claudio Grondi wrote:

> It works for me as it is now, so probably it is better to wait for the
> next release of IPython with a cleaner implementation of color
> schemes before further efforts towards support for choosing
> of background colors for each colorized text output in IPython
> via extension of Console.py of the readline module.

Just to clarify something: there's essentially zero chance that the next ipython
version will provide for user-level color scheme customizations in a clean,
friendly way.  I simply have more important improvements I need to work on,
with a very finite amount of time for it all.  If you send me a patch, I'll be
delighted to include it, but otherwise this will take a back seat.

The main reason for this is that I'm starting to play with a rewrite of the
config file system, to move away from a special plain text format, into using
regular python files.  This will bring multiple advantages, and once a true
python syntax is available to users, these kinds of changes can be allowed with
a far cleaner interface than the hacks required right now.

So for now, I'd suggest you live with the hacks, while a better, permanent
solution arrives.  But don't expect that improvement right away.

Regards,

f

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


Re: OT: why are LAMP sites slow?

2005-02-06 Thread Steve Holden
Lee Harr wrote:
On 2005-02-06, Brian Beck <[EMAIL PROTECTED]> wrote:
Refactoring a database on a live system is a giant pain in the ass,
simpler file-based approaches make incremental updates easier.

As much as I hate working with relational databases, I think you're 
forgetting the reliability even the most poorly-designed database 
provides. Continuing with the words example: assuming all words would 
otherwise be stored in a table, consider the process of updating the 
database schema--all entries are guaranteed to conform to the new 
schema.

Not only that, but with a well-design RDBMS you can put your
schema changes inside of a transaction and make sure everything
is right before committing.
Bear in mind, however, that *most* common RDBMS will treat each DDL 
statement as implicitly committing, so transactional change abilities 
*don't* extend to schema changes.

Isn't there a saying like ... those who create file-based
databases are destined to re-create a relational database
management system poorly?  ;o)
regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.pycon.org/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: returning True, False or None

2005-02-06 Thread Francis Girard
I think it is evil to do something "at your own risk" ; I will certainly not 
embark some roller coaster at my own risk.

I also think it is evil to scan the whole list (as "max" ought to do) when 
only scanning the first few elements would suffice most of the time.

Regards

Francis Girard

Le vendredi 4 Février 2005 21:13, Steven Bethard a écrit :
> Fredrik Lundh wrote:
> > Steven Bethard wrote:
> >> Raymond Hettinger wrote:
> >>> return max(lst)
> >>
> >> Very clever!  Thanks!
> >
> > too clever.  boolean > None isn't guaranteed by the language
> > specification:
>
> Yup.  I thought about mentioning that for anyone who wasn't involved in
> the previous thread discussing this behavior, but I was too lazy.  ;)
> Thanks for pointing it out again.
>
> This implementation detail was added in Python 2.1a1, with the following
> note[1]:
>
> "The outcome of comparing non-numeric objects of different types is
> not defined by the language, other than that it's arbitrary but
> consistent (see the Reference Manual).  An implementation detail changed
> in 2.1a1 such that None now compares less than any other object.  Code
> relying on this new behavior (like code that relied on the previous
> behavior) does so at its own risk."
>
> Steve
>
> [1] http://www.python.org/2.1/NEWS.txt

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


  1   2   >