Xinetd & python server script. problem to get data from from client

2007-07-30 Thread ilia . meerovich
Hello
I wrote simple script to test communication:
When i connect via telnet like: "telnet localhost 51423" the server is
working send and receive information. but when i connected to him via
client scrip so client script receive messages from server but server
doesn't receive message from client. In xinetd.conf and servers conf
file "only_from = 0.0.0.0/0" already choosen. What can i do?
Here below are my client and server:
Thank you :)

Server:

#!/usr/bin/env python
# example

import sys
import os

print "Wellcome"
print "please enter the string"
sys.stdout.flush()
line = sys.stdin.readline().strip()
print "You entered %d characters." % len(line)
sys.stdout.flush()

client:

import sys
import string
import os
import time
import socket
import popen2

PORT = 51423
HOST = ""#sys.argv[1]
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
print "Connected from:", sock.getsockname()
print "Connected to:",sock.getpeername()
while 1:
 print "waiting"
 result = sock.recv(1024)
 print result
 sock.send('foo')
 print "Sent: foo"
 if result == 3:
 break

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


Re: Installing mod_python on mac os 10.4.7

2007-07-30 Thread 7stud
> Yeah!  So is my install good?  Why didn't the Directory tags in
> httpd.conf work?

Ok.  I got the mod_python manual's Testing directions to work as
well.  The Testing section actually says:

---
Add the following Apache directives, which can appear in ... the main
server configuration file...and

you will need to make sure the AllowOverride directive applicable
to this directory has at least FileInfo specified. (The default is
None, which will not work.)


AddHandler mod_python .py
PythonHandler mptest
PythonDebug On

(Substitute /some/directory above for something applicable to your
system, usually your Apache ServerRoot)


I'm not sure how they expect people to interpret that to mean that you
need to add(in my case):


AllowOverride FileInfo


to Apache's httpd.conf file.  But, in any case when I add that, I get
the message "Hello World!" to display when I type:

http://localhost/modPythonPages/mptest.py

in my browser's address bar.

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


Re: Pythonic way for missing dict keys

2007-07-30 Thread Duncan Booth
Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> 
> Instead of doing:
> 
> 
> if callable(function): function()
> 
> you should do:
> 
> try:
> function()
> except TypeError:
> pass
> 
> 
> That should work for most uses of callable(), but isn't quite the
> same. (What if function() has side-effects, or is expensive, and you
> want to determine if it is callable, but not actually call it _now_?)

The replacement for callable(x) is simply hasattr(x, '__call__').
Once upon a time it may have been that functions didn't have a __call__ 
attribute (I haven't checked back on really old Pythons top see if this 
was the case), but these

>> Also, what is the replacement of reduce? I think I remember seeing
>> somewhere that lists comprehension would be (but also remember the
>> advise that reduce will be quicker).
> 
> No, a list comprehension isn't equivalent to reduce(). There is no
> replacement for reduce().

There are of course several replacements for specialised uses of reduce: 
sum, any, all. There is no general purpose replacement, but you can 
write one in a few lines if you really need it.

> 
> It's a shame really. Oh well, maybe it will sneak back in via a
> functional module, or itertools, or something. What a waste, what a
> waste.

I'm sure it will reappear in some other module, but that's the correct 
place for a little used function, not in builtins.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to write GUI and event separately in wxPython??

2007-07-30 Thread Marc 'BlackJack' Rintsch
On Sun, 29 Jul 2007 23:34:14 -0700, Jia Lu wrote:

>  I am making an application with wxpython.
>  But I got a problem when I want to change the display string
> according to process status.
> 
>  I passed the frame to the processing function and use the
> frame.txtobj to change displaying strings.
> 
>  I found it is a bad method to do that.
>  Can any one tell me how to do that usually?
> ( How to separate GUI and Control code? )

One possibility here is to give a callback function into the worker
function that gets called while the function does it's work.  Simple
example:

def do_work(arguments, callback=lambda msg: None):
callback('Start processing.')
for percent in xrange(0, 101):
callback('finished %d%%...' % percent)
callback('Done.')

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing mod_python on mac os 10.4.7

2007-07-30 Thread 7stud
The Testing section of the mod_python manual says to add the following
to httpd.conf(with my directory structure):


AddHandler mod_python .py
PythonHandler mptest
PythonDebug On


and your tutorial says to add this to httpd.conf:

---

 AllowOverride FileInfo

Replace "/some/directory" with the absolute pathname to the directory
in which the ".htaccess" file is located.
---

and the mod_python Testing section also cryptically refers to that
addition, so is there any reason why you can't combine them into:



AllowOverride FileInfo
AddHandler mod_python .py
PythonHandler mptest
PythonDebug On




It seems to work for me.  I deleted the .htaccess file out of the ../
modPythonPages/ directory, I made that change to httpd.conf, I
restarted apache, and mptest.py displays the proper message.

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


Re: Any reason why cStringIO in 2.5 behaves different from 2.4?

2007-07-30 Thread Stefan Behnel
Stefan Scholl wrote:
> Michael L Torrie <[EMAIL PROTECTED]> wrote:
>> xml.sax's use of parseString() is exactly correct.  xml.sax should
>> *never* parse python unicode strings as by definition XML must be
>> encoded as a *byte stream*, which is what a python string is.
> 
> I don't care about the definition of XML at this point of the
> program.

Maybe you should, as you're dealing with XML. But then, maybe you're lucky and
no-one will have to use your software.


> It's not parseString() that tells me something is wrong with the
> parameter. It's cStringIO, which is used on platforms where it is
> available. On other platforms no exceptions are thrown, because
> then StringIO is used, which behaves in Python 2.4 and Python 2.5
> the same, regarding unicode strings.
> 
> Other libraries like LXML (not included) parse unicode strings.

But only in very well defined cases. lxml actually checks if the string uses
an XML declaration. And if it does, you will get an exception.

lxml's parser only accepts a unicode object as input if the unicode object is
the only way to determine the encoding. That's lxml's interpretation of
transport-provided encoding information, which is allowed by the spec.

If you want PyXML to behave the same, go ahead and send a patch to python-dev
or xml-sig.


> And these are two additional lines in my code now:
> 
> if isinstance(string, unicode):
> string = string.encode("utf-8")

This will only work as long as your XML does not have an encoding declaration.
Does your code guarantee that? Because otherwise it is broken. Have you
documented that?


>> A python /unicode/ string could be held internally in any number of
>> ways, 2, 3, 4, or even 8 bytes per character if the implementation
>> demanded it (a bit contrived, I admit).  Since the xml parser is only
>> ever intended to parse *XML*, why should it ever know what to do with
>> python unicode strings, which could be stored any number of ways, making
>> byte-parsing impossible.
> 
> xml.sax is no external parser.

Right, it's a package. But it contains an *XML* parser.


> The program doesn't have to
> communicate with the outside world at this point of execution.
> The Python programm calls a Python function of a Python class and
> passes a Python unicode string as parameter.

A sequence of unicode characters, right.

Why not just pass XML? Would make your life easier.


> The behavior of cStringIO (the original topic of this thread) is
> correct and documented. parseString() uses the old idiom where
> cStringIO is imported as StringIO, when available. Despite the
> fact that they behave differently.
> 
> In my personal opinion: If parseString() shouldn't support
> unicode strings, then it should check for it and throw a
> meaningful exception.

Well, it does. But not because you passed a unicode string but because you
passed a unicode string that does not map 1:1 to the standard XML 1-byte
encoding. A sequence of plain ASCII characters passed as a unicode string is
perfectly ok.

So, the API is even forgiving enough to accept unicode strings, it just obeys
the XML spec after that, that's all.


> At the moment the code just looks as if someone has overlooked
> the fact that unicode strings (with non-ascii characters in it)
> cause a problem. Missing test?

No, just wrong assumption on your side. Read the spec, learn, think, understand.


>> So your code is faulty in its assumptions, not xml.sax.
> 
> As I said in the conclusion, a few messages before: Undocumented,
> implementation dependent behavior.

Well, the implementation was correct *under the assumption* that cStringIO
behaved as expected. But as cStringIO deviated from its documentation,
xml.sax.parseString could not work as expected.


> Or maybe just a bug, considering the following on
> http://docs.python.org/lib/module-xml.sax.html
> 
> A typical SAX application uses three kinds of objects:
> readers, handlers and input sources. ``Reader'' in this
> context is another term for parser, i.e. some piece of
> code that reads the bytes or characters from the input
> source, and produces a sequence of events.
> 
> 
> Bytes _or_ characters.

I think they were just trying to have more people understand what they wanted
to say, not only those who know XML.

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


Cross platform Python app deployment

2007-07-30 Thread Will McGugan
Hi,

Is there some reference regarding how to package a Python application 
for the various platforms? I'm familiar with Windows deployment - I use 
Py2Exe & InnoSetup - but I would like more information on deploying on 
Mac and Linux.

TIA,

Will McGugan
--
http://www.willmcgugan.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to write GUI and event separately in wxPython??

2007-07-30 Thread Steve Holden
Marc 'BlackJack' Rintsch wrote:
> On Sun, 29 Jul 2007 23:34:14 -0700, Jia Lu wrote:
> 
>>  I am making an application with wxpython.
>>  But I got a problem when I want to change the display string
>> according to process status.
>>
>>  I passed the frame to the processing function and use the
>> frame.txtobj to change displaying strings.
>>
>>  I found it is a bad method to do that.
>>  Can any one tell me how to do that usually?
>> ( How to separate GUI and Control code? )
> 
> One possibility here is to give a callback function into the worker
> function that gets called while the function does it's work.  Simple
> example:
> 
> def do_work(arguments, callback=lambda msg: None):
> callback('Start processing.')
> for percent in xrange(0, 101):
> callback('finished %d%%...' % percent)
> callback('Done.')
> 
 >>> [x for x in xrange(0, 101)] == [y for y in xrange(101)]
True
 >>>

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: wxGlade: Who knows how to drive this application?

2007-07-30 Thread Steve Holden
Alberto Griggio wrote:
>> Here are some things I can think of, in no particular order:
> 
> Thanks! I can't promise I'll take care of all of them (some are nontrivial
> to implement, and would probably take a lot of time), but this list is
> definitely valuable (e.g. I can circulate it through the other developers
> to see if there's any volunteer...)
> 
Roel's list is clearly based on much more experience than I have with 
wxGlade, and is pretty much a superset of mine. You are right, that is 
valuable feedback for a developer. Sorry ny own comments were less directed.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -
-- 
http://mail.python.org/mailman/listinfo/python-list


TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why?

2007-07-30 Thread Gilbert Fine
This is a very strange exception raised from somewhere in our program.
I have no idea how this happen. And don't know how to reproduce. It
just occurs from time to time.

Can anyone give me some suggestion to fix this?

Thanks.

--
Gilbert

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


Re: TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why?

2007-07-30 Thread Steve Holden
Gilbert Fine wrote:
> This is a very strange exception raised from somewhere in our program.
> I have no idea how this happen. And don't know how to reproduce. It
> just occurs from time to time.
> 
> Can anyone give me some suggestion to fix this?
> 
If it's raised from "somewhere in your program" the first this to do is 
disable the except clause that is apparently stopping you from getting a 
full traceback, then post that traceback with an appropriate code snippet.

People on this list are good at guessing, but it's better to give then 
some hard information to work with.

Otherwise you are calling the shop (garage?) and saying "My car doesn't 
work, can you tell me how to fix it, please?"

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -
-- 
http://mail.python.org/mailman/listinfo/python-list


import struct in Python z/OS

2007-07-30 Thread miridian
Hi,

I'm porting a Python program from Linux to z/OS using
this Python port

http://www.teaser.fr/~jymengant/mvspython/mvsPythonPort.html

I get the following

Python 2.4.1 (#43, Apr 23 2005, 23:35:50) [C] on mvs
Type "help", "copyright", "credits" or "license" for more information.
 >>> import struct
Traceback (most recent call last):
   File "", line 1, in ?
ImportError: No module named struct


as far as I can see the module struct (and a lot of other, like time, 
math etc.) is compiled as dll
   ./build/lib.os390-10.00-7060-2.4/struct.dll

but not configured correctly.
:-(

Any hint ?

Thank you in advance.


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


Re: TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why?

2007-07-30 Thread Marc 'BlackJack' Rintsch
On Mon, 30 Jul 2007 03:36:33 -0700, Gilbert Fine wrote:

> This is a very strange exception raised from somewhere in our program.
> I have no idea how this happen. And don't know how to reproduce. It
> just occurs from time to time.

Maybe different `Decimal`\s?  Here's how to reproduce such a traceback:

In [20]: from decimal import Decimal

In [21]: a = Decimal()

In [22]: class Decimal(object):
   : pass
   :

In [23]: b = Decimal()

In [24]: a - b
 Traceback (most recent call last)

/home/bj/ in ()

: unsupported operand type(s) for -: 'Decimal' and 
'Decimal'

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to write GUI and event separately in wxPython??

2007-07-30 Thread Marc 'BlackJack' Rintsch
On Mon, 30 Jul 2007 06:32:55 -0400, Steve Holden wrote:

>  >>> [x for x in xrange(0, 101)] == [y for y in xrange(101)]
> True

First I thought: Why the unnecessary list comprehension but to my surprise:

In [33]: xrange(42) == xrange(42)
Out[33]: False

That's strange.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why?

2007-07-30 Thread Duncan Booth
Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:

> On Mon, 30 Jul 2007 03:36:33 -0700, Gilbert Fine wrote:
> 
>> This is a very strange exception raised from somewhere in our
>> program. I have no idea how this happen. And don't know how to
>> reproduce. It just occurs from time to time.
> 
> Maybe different `Decimal`\s?  Here's how to reproduce such a
> traceback: 
> 


Or even just one Decimal type but not one which supports subtraction:

>>> class Decimal(object):
 pass

>>> a = Decimal()
>>> b = Decimal()
>>> a-b

Traceback (most recent call last):
  File "", line 1, in 
a-b
TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'

Another option of course is that Decimal() did support substraction but 
someone deleted it:

>>> from decimal import Decimal
>>> del Decimal.__sub__
>>> Decimal()-Decimal()

Traceback (most recent call last):
  File "", line 1, in 
Decimal()-Decimal()
TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'

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


Re: Hex editor display - can this be more pythonic?

2007-07-30 Thread Neil Cerutti
On 2007-07-30, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Sun, 29 Jul 2007 18:30:22 -0700, CC <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
>> 
>> Yeah, with this I'm not that concerned about Windows.  Though, can WinXP 
>> still load the ansi.sys driver?
>>
>   I'm actually not sure...
>
>   I think if one uses the 16-bit command parser it is available, but
> not the 32-bit parser...
>
> command.com vs cmd.exe

Yes.  You can load the ansi.sys driver in command.com on Windows
2000 and XP, and it will work with simply batch files. But it
doesn't work with Python, for reasons I don't know enough about
Windows console programs to understand.

-- 
Neil Cerutti
The audience is asked to remain seated until the end of the recession.
--Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Professional Grant Proposal Writing Workshop (September 2007: Simon Fraser University)

2007-07-30 Thread Anthony Jones


The Grant Institute's Grants 101: Professional Grant Proposal Writing Workshop will be held at Simon Fraser University at Harbour Centre, September 12 - 14
, 2007. Interested development professionals, researchers, faculty, and graduate students should register as soon as possible, as demand means that seats will fill up quickly. Please forward, post, and distribute this e-mail to your colleagues and listservs. 
 
All participants will receive certification in professional grant writing from the Institute. For more information call (213) 817 - 5308 or visit The Grant Institute at www.thegrantinstitute.com.
 
Please find the program description below:
 
The Grant Institute
Grants 101: Professional Grant Proposal Writing Workshop
will be held at
Simon Fraser University at Harbour Centre
Vancouver,  British Columbia
September 12 - 14, 2007
8:00 AM - 5:00 PM
 

The Grant Institute's Grants 101 course is an intensive and detailed introduction to the process, structure, and skill of professional proposal writing. This course is characterized by its ability to act as a thorough overview, introduction, and refresher at the same time. In this course, participants will learn the entire proposal writing process and complete the course with a solid understanding of not only the ideal proposal structure, but a holistic understanding of the essential factors, 
which determine whether or not a program gets funded. Through the completion of interactive exercises and activities, participants will complement expert lectures by putting proven techniques into practice. This course is designed for both the beginner looking for a thorough introduction and the intermediate looking for a refresher course that will strengthen their grant acquisition skills. This class, simply put, is designed to get results by creating professional grant proposal writers. 

 
Participants will become competent program planning and proposal writing professionals after successful completion of the Grants 101 course. In three active and informative days, students will be exposed to the art of successful grant writing practices, and led on a journey that ends with a masterful grant proposal. 
 
Grants 101 consists of three (3) courses that will be completed during the three-day workshop. 
 
(1) Fundamentals of Program Planning
 
This course is centered on the belief that "it's all about the program." This intensive course will teach professional program development essentials and program evaluation. While most grant writing "workshops" treat program development and evaluation as separate from the writing of a proposal, this class will teach students the relationship between overall program planning and grant writing. 
 
(2) Professional Grant Writing
 

Designed for both the novice and experienced grant writer, this course will make each student an overall proposal writing specialist. In addition to teaching the basic components of a grant proposal, successful approaches, and the do's and don'ts of grant writing, this course is infused with expert principles that will lead to a mastery of the process. Strategy resides at the forefront of this course's intent to illustrate grant writing as an integrated, multidimensional, and dynamic endeavor. 
Each student will learn to stop writing the grant and to start writing the story. Ultimately, this class will illustrate how each component of the grant proposal represents an opportunity to use proven techniques for generating support.
 
(3) Grant Research
 

At its foundation, this course will address the basics of foundation, corporation, and government grant research. However, this course will teach a strategic funding research approach that encourages students to see research not as something they do before they write a proposal, but as an integrated part of the grant seeking process. Students will be exposed to online and database research tools, as well as publications and directories that contain information about foundation, corporation, and 
government grant opportunities. Focusing on funding sources and basic social science research, this course teaches students how to use research as part of a strategic grant acquisition effort.
 
Registration
$597.00 USD tuition includes all materials and certificates.
 
Each student will receive:
*The Grant Institute Certificate in Professional Grant Writing
*The Grant Institute's Guide to Successful Grant Writing
*The Grant Institute Grant Writer's Workbook with sample proposals, forms, and outlines
 
Registration Methods
 
1) On-Line - Complete the online registration form at www.thegrantinstitute.com under Register Now. We'll send your confirmation by e-mail. 
 
2) By Phone - Call (213) 817 - 5308 to register by phone. Our friendly Program Coordinators will be happy to assist you and answer your questions. 
 
3) By E-mail - Send an e-mail with your name, organization, and basic contact information to [EMAIL PROTECTED] and we will reserve your slot and send you

Re: Cross platform Python app deployment

2007-07-30 Thread Benjamin Niemann
Hi,

Will McGugan wrote:

> Is there some reference regarding how to package a Python application
> for the various platforms? I'm familiar with Windows deployment - I use
> Py2Exe & InnoSetup - but I would like more information on deploying on
> Mac and Linux.

The standard way to package portable Python apps is a tarball with a
setup.py script. That should work on all systems where Python is already
installed, including Windows. Read ,
if you have not already done so.

If you want more 'native' packages (as you already have for Windows, where
users are used to have a graphical installer), you'll have to
create .deb, .rpm, .whatever packages. You usually won't have to bother
about the Python interpreter, because it is either already present (it's a
standard package on most systems) or it will be pulled in via a package
dependency.
distutils already allows you to create rpm packages.


HTH

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://pink.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cross platform Python app deployment

2007-07-30 Thread Diez B. Roggisch
Will McGugan wrote:

> Hi,
> 
> Is there some reference regarding how to package a Python application
> for the various platforms? I'm familiar with Windows deployment - I use
> Py2Exe & InnoSetup - but I would like more information on deploying on
> Mac and Linux.

On mac, there is py2app that allows to create application-bundles you can
then install. Either including a python interpreter, or using an installed
one.

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


Re: Pythonic way for missing dict keys

2007-07-30 Thread Steven D'Aprano
On Mon, 30 Jul 2007 07:37:05 +, Duncan Booth wrote:

> Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> 
>> 
>> Instead of doing:
>> 
>> 
>> if callable(function): function()
>> 
>> you should do:
>> 
>> try:
>> function()
>> except TypeError:
>> pass
>> 
>> 
>> That should work for most uses of callable(), but isn't quite the
>> same. (What if function() has side-effects, or is expensive, and you
>> want to determine if it is callable, but not actually call it _now_?)
> 
> The replacement for callable(x) is simply hasattr(x, '__call__').
> Once upon a time it may have been that functions didn't have a __call__ 
> attribute (I haven't checked back on really old Pythons top see if this 
> was the case), but these

Your sentence seems to have run out early :)

Thanks, I didn't know that -- I remember that Back In The Day checking if
something was callable was tricky, because it could be a function, a
method, or a class with __call__. It makes much more sense to make all
callables go through __call__.



>>> Also, what is the replacement of reduce? I think I remember seeing
>>> somewhere that lists comprehension would be (but also remember the
>>> advise that reduce will be quicker).
>> 
>> No, a list comprehension isn't equivalent to reduce(). There is no
>> replacement for reduce().
> 
> There are of course several replacements for specialised uses of reduce: 
> sum, any, all. There is no general purpose replacement, but you can 
> write one in a few lines if you really need it.

True. But writing the same basic algorithm over and over again is about as
far from best practice as you can get without being a PHP programmer.
*wink* Currying is easy to do too, but Python has grown a function
functools.partial() to do it properly. That's as it should be.

(Yes, I know that's a misuse of the term currying, but it's a common one,
and easier than saying "Making a partial function".)


>> It's a shame really. Oh well, maybe it will sneak back in via a
>> functional module, or itertools, or something. What a waste, what a
>> waste.
> 
> I'm sure it will reappear in some other module, but that's the correct
> place for a little used function, not in builtins.

Oh, I would have no problem at all with reduce being banished to the
functtools module. But it's a shame to have to go through the whole PEP
process, and risk Guido saying no.


-- 
Steven.

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


Detecting __future__ features

2007-07-30 Thread Steven D'Aprano
How would one tell at runtime if a particular feature has been enabled by
the "from __future__ import thing" statement?

For example, I can do this:

if 1/2 == 0: 
print "classic division in use"
else:
print "true division in use"


I could even do this:

from keyword import keyword
if keyword("with"):
print "with statement enabled"
else:
print "with statement not enabled"

(I don't especially care whether the feature in question has been enabled
via an explicit call to import, or because it has become the default.)

Is there any general mechanism? 


-- 
Steven.

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


Re: Detecting __future__ features

2007-07-30 Thread Lawrence Oluyede
Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> Is there any general mechanism? 

I'd just use the expected future feature and if the result is not what I
expect (or Python raises any kind of exception, like using a keyword not
present) I'd think I'm in the past :-)

-- 
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand 
something when his salary depends on not
understanding it" - Upton Sinclair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Detecting __future__ features

2007-07-30 Thread Neil Cerutti
On 2007-07-30, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> How would one tell at runtime if a particular feature has been
> enabled by the "from __future__ import thing" statement?

I don't understand the qualification, "at runtime," you're
making. What's wrong with just importing what you want and using
it? If it's already been enabled, no harm will come from the
import statement.

-- 
Neil Cerutti
Will the highways on the Internet become more few? --George W. Bush
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Detecting __future__ features

2007-07-30 Thread André
On Jul 30, 9:39 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2007-07-30, Steven D'Aprano
>
> <[EMAIL PROTECTED]> wrote:
> > How would one tell at runtime if a particular feature has been
> > enabled by the "from __future__ import thing" statement?
>
> I don't understand the qualification, "at runtime," you're
> making. What's wrong with just importing what you want and using
> it? If it's already been enabled, no harm will come from the
> import statement.
>

I'm not the OP, so perhaps I am missing his intent. However, I can see
a good reason for asking this question.

I seem to recall that the "from __future__ import" statement can only
be done at the beginning of a script.  What if you are designing a
module meant to be imported, and used by other programs over which you
have no control?   You can't use "from __future__ import" in your
module.  So, you may have to find a way to figure out what's been
done.  (the example given with the division operator is a good one).

André
> --
> Neil Cerutti
> Will the highways on the Internet become more few? --George W. Bush


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

Re: Detecting __future__ features

2007-07-30 Thread Antti Rasinen

On 2007-07-30, at 15:29, Steven D'Aprano wrote:

> How would one tell at runtime if a particular feature has been  
> enabled by
> the "from __future__ import thing" statement?
>
> (I don't especially care whether the feature in question has been  
> enabled
> via an explicit call to import, or because it has become the default.)
>
> Is there any general mechanism?

You probably have to care about imports vs. language defaults. But  
it's not very difficult.

For imports you can use __future__ to help you. If your namespace  
contains a feature you want to check for and it is identical to the  
same feature in __future__, then the code has used from __future__  
import feature. You could probably try something like this:

import __feature__
feature = "division"
if globals().get(feature, None) == __future__.__dict__[feature]:
 print "Bingo!"

You can probably figure out how to use sys.version_info to check  
whether the current Python version is higher than the one specified  
in a feature line:

import __future__
import sys
if sys.version_info >= __future__.division.mandatory:
 print "Bingo! Two in a row!"

Check the __future__ docstrings for more information.

-- 
[ [EMAIL PROTECTED] <*> Antti Rasinen ]

This drone-vessel speaks with the voice and authority of the Ur-Quan.

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


Re: Detecting __future__ features

2007-07-30 Thread Neil Cerutti
On 2007-07-30, André <[EMAIL PROTECTED]> wrote:
> On Jul 30, 9:39 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>> I don't understand the qualification, "at runtime," you're
>> making. What's wrong with just importing what you want and
>> using it? If it's already been enabled, no harm will come from
>> the import statement.
>>
>
> I'm not the OP, so perhaps I am missing his intent. However, I
> can see a good reason for asking this question.
>
> I seem to recall that the "from __future__ import" statement
> can only be done at the beginning of a script.  What if you are
> designing a module meant to be imported, and used by other
> programs over which you have no control?   You can't use "from
> __future__ import" in your module.  So, you may have to find a
> way to figure out what's been done.  (the example given with
> the division operator is a good one).

Is "from __future__ import" really that lame?

-- 
Neil Cerutti
8 new choir robes are currently needed, due to the addition of several new
members and to the deterioration of some of the older ones. --Church Bulletin
Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Detecting __future__ features

2007-07-30 Thread Carsten Haese
On Mon, 2007-07-30 at 12:53 +, André wrote:
> On Jul 30, 9:39 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> > On 2007-07-30, Steven D'Aprano
> >
> > <[EMAIL PROTECTED]> wrote:
> > > How would one tell at runtime if a particular feature has been
> > > enabled by the "from __future__ import thing" statement?
> >
> > I don't understand the qualification, "at runtime," you're
> > making. What's wrong with just importing what you want and using
> > it? If it's already been enabled, no harm will come from the
> > import statement.
> >
> 
> I'm not the OP, so perhaps I am missing his intent. However, I can see
> a good reason for asking this question.
> 
> I seem to recall that the "from __future__ import" statement can only
> be done at the beginning of a script.

Incorrect. It must be done at the beginning of the *file*.

>   What if you are designing a
> module meant to be imported, and used by other programs over which you
> have no control?   You can't use "from __future__ import" in your
> module.

Incorrect. You can use a __future__ import in a module as long as you do
it at the beginning of the modul file.

>   So, you may have to find a way to figure out what's been
> done.  (the example given with the division operator is a good one).

No. __future__ directives are scoped to the module. Observe:


$ cat f1.py
def f1():
  print 1/2

f1()
import f2
f2.f2()

$ cat f2.py
from __future__ import division

def f2():
  print 1/2

$ python f1.py 
0
0.5

As you can see, f1 uses past semantics, f2 uses future semantics. Just
use whatever __future__ directives you need for your module at the
beginning of your module, and everything will just work.

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Detecting __future__ features

2007-07-30 Thread Diez B. Roggisch
Neil Cerutti wrote:

> On 2007-07-30, André <[EMAIL PROTECTED]> wrote:
>> On Jul 30, 9:39 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>>> I don't understand the qualification, "at runtime," you're
>>> making. What's wrong with just importing what you want and
>>> using it? If it's already been enabled, no harm will come from
>>> the import statement.
>>>
>>
>> I'm not the OP, so perhaps I am missing his intent. However, I
>> can see a good reason for asking this question.
>>
>> I seem to recall that the "from __future__ import" statement
>> can only be done at the beginning of a script.  What if you are
>> designing a module meant to be imported, and used by other
>> programs over which you have no control?   You can't use "from
>> __future__ import" in your module.  So, you may have to find a
>> way to figure out what's been done.  (the example given with
>> the division operator is a good one).
> 
> Is "from __future__ import" really that lame?

Well, if you consider it lame, how about you being a 7331 haX0r who tells us
how python is going to handle this then:

def foo():
yield 1

if random_condition():
   from __future__ import generators

def bar():
yield 2

The point is that from __future__ can massively alter the behavior of the
parser - accepting keywords that otherwise won't be keywords, as in this
example, and many more.

Making the switch between different parser-implementations on the fly isn't
technically impossible - but really, really, really complicated. But then,
if it's lameness sucks so much, you might wanna take a stab at it?

Diez

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

Re: How to write GUI and event separately in wxPython??

2007-07-30 Thread kyosohma
On Jul 30, 1:34 am, Jia Lu <[EMAIL PROTECTED]> wrote:
> HI all
>
>  I am making an application with wxpython.
>  But I got a problem when I want to change the display string
> according to process status.
>
>  I passed the frame to the processing function and use the
> frame.txtobj to change displaying strings.
>
>  I found it is a bad method to do that.
>  Can any one tell me how to do that usually?
> ( How to separate GUI and Control code? )
>
> Thank you.

If you're doing a long running task that needs to send data
periodically to the GUI front-end for status, there's some good ways
listed here: http://wiki.wxpython.org/LongRunningTasks

The wiki seems down right now (8:40 CST 07/30/2007), but hopefully
it'll be up soon.

Mike

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


Re: Detecting __future__ features

2007-07-30 Thread Jean-Paul Calderone
On Mon, 30 Jul 2007 15:48:00 +0200, "Diez B. Roggisch" <[EMAIL PROTECTED]> 
wrote:
>Neil Cerutti wrote:
>
>> On 2007-07-30, André <[EMAIL PROTECTED]> wrote:
>>> On Jul 30, 9:39 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
 I don't understand the qualification, "at runtime," you're
 making. What's wrong with just importing what you want and
 using it? If it's already been enabled, no harm will come from
 the import statement.

>>>
>>> I'm not the OP, so perhaps I am missing his intent. However, I
>>> can see a good reason for asking this question.
>>>
>>> I seem to recall that the "from __future__ import" statement
>>> can only be done at the beginning of a script.  What if you are
>>> designing a module meant to be imported, and used by other
>>> programs over which you have no control?   You can't use "from
>>> __future__ import" in your module.  So, you may have to find a
>>> way to figure out what's been done.  (the example given with
>>> the division operator is a good one).
>>
>> Is "from __future__ import" really that lame?
>
>Well, if you consider it lame, how about you being a 7331 haX0r who tells us
>how python is going to handle this then:
>
>def foo():
>yield 1
>
>if random_condition():
>   from __future__ import generators
>
>def bar():
>yield 2
>
>The point is that from __future__ can massively alter the behavior of the
>parser - accepting keywords that otherwise won't be keywords, as in this
>example, and many more.
>
>Making the switch between different parser-implementations on the fly isn't
>technically impossible - but really, really, really complicated. But then,
>if it's lameness sucks so much, you might wanna take a stab at it?
>

I think you misunderstood the behavior which was being called lame.  The
earlier poster was suggesting that only the first Python code to run any
where in a process could perform future imports.  This is, of course, not
true.  It's only restricted to the first Python code to run in a particular
file.

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

Re: Detecting __future__ features

2007-07-30 Thread Neil Cerutti
On 2007-07-30, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> Making the switch between different parser-implementations on
> the fly isn't technically impossible - but really, really,
> really complicated. But then, if it's lameness sucks so much,
> you might wanna take a stab at it?

I was considering the following specific quote:

  What if you are designing a module meant to be imported, and
  used by other programs over which you have no control?   You
  can't use "from __future__ import" in your module."

If that were true, I think it would indeed be lame. Of course, it
isn't true, right?

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


Making Gridded Widgets Expandable

2007-07-30 Thread Jim
Hi,
I'm looking at page 548 of Programming Python (3rd Edition) by Mark
Lutz.
The following GUI script works with no problem, i.e., the rows and
columns expand:
=
# Gridded Widgets Expandable page 548

from Tkinter import *
colors = ["red", "white", "blue"]

def gridbox(root):
Label(root, text = 'Grid').grid(columnspan = 2)
r = 1
for c in colors:
l = Label(root, text=c, relief=RIDGE, width=25)
e = Entry(root, bg=c,   relief=SUNKEN, width=50)
l.grid(row=r, column=0, sticky=NSEW)
e.grid(row=r, column=1, sticky=NSEW)
root.rowconfigure(r, weight=1)
r += 1
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)

root = Tk()
gridbox(Toplevel(root))
Button(root, text="Quit", command=root.quit).grid()
mainloop()
=
However, the following GUI script using class does not expand rows and
columns:
=
# Gridded Widgets Expandable 2

from Tkinter import *
colors = ["red", "white", "blue"]

class GUI(Frame):
def __init__(self,master):
Frame.__init__(self,master)
self.grid()
self.gridbox()

def gridbox(self):
Label(self, text = 'Grid').grid(columnspan = 2)
r = 1
for c in colors:
l = Label(self, text=c, relief=RIDGE, width=25)
e = Entry(self, bg=c,   relief=SUNKEN, width=50)
l.grid(row=r, column=0, sticky=NSEW)
e.grid(row=r, column=1, sticky=NSEW)
self.rowconfigure(r, weight=1)
r += 1
self.columnconfigure(0, weight=1)
self.columnconfigure(1, weight=1)

root = Tk()
root.title("Gridded Widgets Expandable")
app = GUI(root)
Button(root, text="Quit", command=root.quit).grid()
root.mainloop()
=
What am I missing?
Thanks,
Jim

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


Re: encode/decode misunderstanding

2007-07-30 Thread Tim Arnold
"Diez B. Roggisch" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Tim Arnold schrieb:
>> Hi, I'm beginning to understand the encode/decode string methods, but I'd 
>> like confirmation that I'm still thinking in the right direction:
>>
>> I have a file of latin1 encoded text. Let's say I put one line of that 
>> file into a string variable 'tocline', as follows:
>> tocline = 'Ficha Datos de p\xe9rdida AND acci\xf3n'
>>
>> import codecs
>> tocFile = codecs.open('mytoc.htm','wb',encoding='utf8',errors='replace')
>> tocline = tocline.decode('latin1','replace')
>> tocFile.write(tocline)
>> tocFile.close()
>>
>> What I think is that tocFile is wrapped to insure that anything written 
>> to it is in utf8
>> I decode the latin1 string into python's internal unicode encoding and 
>> that gets written out as utf8.
>>
>> Questions:
>> what exactly is the tocline when it's read in with that \xe9 and \xed in 
>> the string? A latin1 encoded string?
>
> Yes. A simple, pure byte-string, that happens to contain bytes which under 
> the latin1-encoding are "correct".
>
>> Is my method the right way to write such a line out to a file with utf8 
>> encoding?
>
> Yes.
>
>> If I read in the latin1 file using
>> codecs.open(filename,encoding='latin1') and write out the utf8 file by 
>> opening with
>> codecs.open(othername,encoding='utf8'), would I no longer have a 
>> problem --  I could just read in latin1 and write out utf8 with no more 
>> worries about encoding?
>
> As long as you don't mix bytestrings and only use unicode-objects, you 
> should be fine, yes.
>
> Diez

wow, I was thinking correctly about encoding! time for a beer!
Diez, thanks very much for confirming my thoughts.

--Tim Arnold 


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


File handle not being released by close

2007-07-30 Thread bg_ie
Hi,

I'm in the process of writing some code and noticed a strange problem
while doing so. I'm working with PythonWin 210 built for Python 2.5. I
noticed the problem for the last py file processed by this script,
where the concerned tmp file is only actually written to when
PythonWin is closed. In other words, after I run this script, one of
the generated tmp files has a size of 0kB. I then close PythonWin and
it is then written to.

I'm guessing the garbage collector is causing the file to be written,
but shouldn't close do this?

/Barry

import os, time, string

dir = 'c:\\temp1'

def listAllFile(fileNames,dir,files):
  def f1(a,dir=dir): return os.path.join(dir,a)
  files2 = map(f1, files)
  fileNames.extend(files2)

fileNames = []
os.path.walk(dir,listAllFile,fileNames)

for fileName in fileNames:
  fileBeginning = os.path.splitext(fileName)[0]
  fileEnd   = os.path.splitext(fileName)[1]

  if fileEnd == ".py":
print fileName
f=open(fileBeginning+".tmp", 'w')
f.write("Hello")
f.close

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


Re: Detecting __future__ features

2007-07-30 Thread Carsten Haese
On Mon, 2007-07-30 at 14:10 +, Neil Cerutti wrote:
> On 2007-07-30, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> > Making the switch between different parser-implementations on
> > the fly isn't technically impossible - but really, really,
> > really complicated. But then, if it's lameness sucks so much,
> > you might wanna take a stab at it?
> 
> I was considering the following specific quote:
> 
>   What if you are designing a module meant to be imported, and
>   used by other programs over which you have no control?   You
>   can't use "from __future__ import" in your module."
> 
> If that were true, I think it would indeed be lame. Of course, it
> isn't true, right?

Correct, the statement you're referring to is not true. See my earlier
reply on this thread for details.

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: making a variable available in a function from decorator

2007-07-30 Thread [EMAIL PROTECTED]
is it possible to do this without passing it as a function argument?

On 30 Jul 2007 06:17:25 GMT, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Sun, 29 Jul 2007 15:22:47 -0700, [EMAIL PROTECTED] wrote:
>
> > I create a variable in a decorator. i want to be able to access that
> > variable in the function to be decorated. How to do this?
>
> Pass it as argument to the function:
>
> def deco(func):
> eggs = 42
> def decorated(*args, **kwargs):
> kwargs['spam'] = eggs
> func(*args, **kwargs)
> return decorated
>
> @deco
> def test(parrot, spam):
> print parrot, spam
>
> Ciao,
> Marc 'BlackJack' Rintsch
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Subprocess and pipe-fork-exec primitive

2007-07-30 Thread Rafael Giannetti Viotti
Hi,

   I am working with the subprocess.py module in Python 2.4.4 and I am 
confused about it's functionality. It uses the standard pipe-fork-exec 
method to start a subprocess:

   # create pipes

   pid = fork()

   if pid == 0:
 # child
 exec(...)

   # parent
   status = waitpid(pid, 0)

   From my experience, this primitive will fail with 'no child 
processes' at the waitpid call if the forked child dies very quickly - 
before the parent is scheduled back for execution. This seems to happen 
because Python has a default SIGCHLD handler that, in this case, will 
reap the process before the parent has the chance to do it.

   I would like to know if this is correct, or am I missing something here?

---
Rafael.

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


Re: File handle not being released by close

2007-07-30 Thread Richard Brodie

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> I'm guessing the garbage collector is causing the file to be written,
> but shouldn't close do this?

Only if you call it ;) 


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


Re: Making Gridded Widgets Expandable

2007-07-30 Thread Eric Brunel
On Mon, 30 Jul 2007 15:59:21 +0200, Jim <[EMAIL PROTECTED]> wrote:

> Hi,
> I'm looking at page 548 of Programming Python (3rd Edition) by Mark
> Lutz.
> The following GUI script works with no problem, i.e., the rows and
> columns expand:
> =
> # Gridded Widgets Expandable page 548
>
> from Tkinter import *
> colors = ["red", "white", "blue"]
>
> def gridbox(root):
> Label(root, text = 'Grid').grid(columnspan = 2)
> r = 1
> for c in colors:
> l = Label(root, text=c, relief=RIDGE, width=25)
> e = Entry(root, bg=c,   relief=SUNKEN, width=50)
> l.grid(row=r, column=0, sticky=NSEW)
> e.grid(row=r, column=1, sticky=NSEW)
> root.rowconfigure(r, weight=1)
> r += 1
> root.columnconfigure(0, weight=1)
> root.columnconfigure(1, weight=1)
>
> root = Tk()
> gridbox(Toplevel(root))
> Button(root, text="Quit", command=root.quit).grid()
> mainloop()
> =
> However, the following GUI script using class does not expand rows and
> columns:
> =
> # Gridded Widgets Expandable 2
>
> from Tkinter import *
> colors = ["red", "white", "blue"]
>
> class GUI(Frame):
> def __init__(self,master):
> Frame.__init__(self,master)
> self.grid()
> self.gridbox()
>
> def gridbox(self):
> Label(self, text = 'Grid').grid(columnspan = 2)
> r = 1
> for c in colors:
> l = Label(self, text=c, relief=RIDGE, width=25)
> e = Entry(self, bg=c,   relief=SUNKEN, width=50)
> l.grid(row=r, column=0, sticky=NSEW)
> e.grid(row=r, column=1, sticky=NSEW)
> self.rowconfigure(r, weight=1)
> r += 1
> self.columnconfigure(0, weight=1)
> self.columnconfigure(1, weight=1)
>
> root = Tk()
> root.title("Gridded Widgets Expandable")
> app = GUI(root)
> Button(root, text="Quit", command=root.quit).grid()
> root.mainloop()
> =
> What am I missing?

Hint: when you get this kind of problem, the problem is usually that an  
intermedaite Frame does not expand as it does. Since you have only one  
Frame here (your GUI instance), you should already have the solution. If  
you don't, or in case you get this kind of problem later with a more  
complex layout, adding a visible border on all Frame's usually helps.  
Here, for example, you can't do:
Frame.__init__(self,master, border=2, bg='green')
in GUI.__init__, and this will definitely show that the Frame does not  
resize itself when you resize the window. So the solution is clear: you  
should add a sticky option to your self.grid in GUI.__init__ and the  
corresponding (row|column)_configure(..., weight=1) on the window.

BTW, why do you create a sub-class of Frame (yes: this is a trick  
question)?

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File handle not being released by close

2007-07-30 Thread Eric Brunel
On Mon, 30 Jul 2007 16:36:00 +0200, <[EMAIL PROTECTED]> wrote:

> Hi,
>
> I'm in the process of writing some code and noticed a strange problem
> while doing so. I'm working with PythonWin 210 built for Python 2.5. I
> noticed the problem for the last py file processed by this script,
> where the concerned tmp file is only actually written to when
> PythonWin is closed. In other words, after I run this script, one of
> the generated tmp files has a size of 0kB. I then close PythonWin and
> it is then written to.
>
> I'm guessing the garbage collector is causing the file to be written,
> but shouldn't close do this?
>
> /Barry
>
> import os, time, string
>
> dir = 'c:\\temp1'
>
> def listAllFile(fileNames,dir,files):
>   def f1(a,dir=dir): return os.path.join(dir,a)
>   files2 = map(f1, files)
>   fileNames.extend(files2)
>
> fileNames = []
> os.path.walk(dir,listAllFile,fileNames)
>
> for fileName in fileNames:
>   fileBeginning = os.path.splitext(fileName)[0]
>   fileEnd   = os.path.splitext(fileName)[1]
>
>   if fileEnd == ".py":
> print fileName
> f=open(fileBeginning+".tmp", 'w')
> f.write("Hello")
> f.close

f.close()

HTH...
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File handle not being released by close

2007-07-30 Thread Peter Otten
 [EMAIL PROTECTED] wrote:

> I'm in the process of writing some code and noticed a strange problem
> while doing so. I'm working with PythonWin 210 built for Python 2.5. I
> noticed the problem for the last py file processed by this script,
> where the concerned tmp file is only actually written to when
> PythonWin is closed. In other words, after I run this script, one of
> the generated tmp files has a size of 0kB. I then close PythonWin and
> it is then written to.
> 
> I'm guessing the garbage collector is causing the file to be written,
> but shouldn't close do this?

Yes.

> f=open(fileBeginning+".tmp", 'w')
> f.write("Hello")
> f.close

In Python () is nessary to call a parameterless function or method:

>>> def f(): print "Hi Barry"
...
>>> f

>>> f()
Hi Barry

This allows it to treat functions as variables consistently:

>>> def f(write):
... write("Hello")
...
>>> def write_upper(s): print s.upper()
...
>>> import sys
>>> write_to_stdout = sys.stdout.write
>>>
>>> f(write_upper)
HELLO
>>> f(write_to_stdout)
Hello>>>

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


Re: Detecting __future__ features

2007-07-30 Thread André
On Jul 30, 11:10 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2007-07-30, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
>
> > Making the switch between different parser-implementations on
> > the fly isn't technically impossible - but really, really,
> > really complicated. But then, if it's lameness sucks so much,
> > you might wanna take a stab at it?
>
> I was considering the following specific quote:
>
>   What if you are designing a module meant to be imported, and
>   used by other programs over which you have no control?   You
>   can't use "from __future__ import" in your module."
>
> If that were true, I think it would indeed be lame. Of course, it
> isn't true, right?
>

Yes, it was my mistake; I replied too quicly from a faulty memory
bank...

(extract foot from mouth ... inhale deeply to resupply oxygen to the
brain ...)
André

> --
> Neil Cerutti


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

Re: File handle not being released by close

2007-07-30 Thread Jean-Paul Calderone
On Mon, 30 Jul 2007 07:36:00 -0700, [EMAIL PROTECTED] wrote:
>Hi,
>
> [snip]
>f=open(fileBeginning+".tmp", 'w')
>f.write("Hello")
>f.close
>

You forgot to call close.  Try this final line, instead:

f.close()

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


Replacing overloaded functions with closures.

2007-07-30 Thread king kikapu
Hi,

i am trying, to no avail yet, to take a C#'s overloaded functions
skeleton and rewrite it in Python by using closures.
I read somewhere on the net (http://dirtsimple.org/2004/12/python-is-
not-java.html) that in Python we can reduce code duplication for
overloaded functions by using closures.

I do not quite understand this. Let's say we have the following simple
C# code:

int func(int i) { return i * 2; }
string func(string s) { return s + s; }
bool func(bool f) { return !f; }

I wasn't able to find a way to express this thing in closures. I even
tried to have the parameters i, s and f as parameters with default
arguments with None value in the inner function and there to check for
the None and do the needed work but i am not sure if this is the
correct solution.

Any help ?


thanks in advance.

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


RE: Making Gridded Widgets Expandable

2007-07-30 Thread Hamilton, William
> From: Jim
> Hi,
> I'm looking at page 548 of Programming Python (3rd Edition) by Mark
> Lutz.
> The following GUI script works with no problem, i.e., the rows and
> columns expand:
> =
> # Gridded Widgets Expandable page 548
> 
> from Tkinter import *
> colors = ["red", "white", "blue"]
> 
> def gridbox(root):
> Label(root, text = 'Grid').grid(columnspan = 2)
> r = 1
> for c in colors:
> l = Label(root, text=c, relief=RIDGE, width=25)
> e = Entry(root, bg=c,   relief=SUNKEN, width=50)
> l.grid(row=r, column=0, sticky=NSEW)
> e.grid(row=r, column=1, sticky=NSEW)
> root.rowconfigure(r, weight=1)
> r += 1
> root.columnconfigure(0, weight=1)
> root.columnconfigure(1, weight=1)
> 
> root = Tk()
> gridbox(Toplevel(root))
> Button(root, text="Quit", command=root.quit).grid()
> mainloop()
> =
> However, the following GUI script using class does not expand rows and
> columns:
> =
> # Gridded Widgets Expandable 2
> 
> from Tkinter import *
> colors = ["red", "white", "blue"]
> 
> class GUI(Frame):
> def __init__(self,master):
> Frame.__init__(self,master)
> self.grid()
> self.gridbox()
> 
> def gridbox(self):
> Label(self, text = 'Grid').grid(columnspan = 2)
> r = 1
> for c in colors:
> l = Label(self, text=c, relief=RIDGE, width=25)
> e = Entry(self, bg=c,   relief=SUNKEN, width=50)
> l.grid(row=r, column=0, sticky=NSEW)
> e.grid(row=r, column=1, sticky=NSEW)
> self.rowconfigure(r, weight=1)
> r += 1
> self.columnconfigure(0, weight=1)
> self.columnconfigure(1, weight=1)
> 
> root = Tk()
> root.title("Gridded Widgets Expandable")
> app = GUI(root)
> Button(root, text="Quit", command=root.quit).grid()
> root.mainloop()
> =
> What am I missing?


In the first, your gridbox has Toplevel(root) as its master, causing it
to be created in a new window.  In the second, it has Frame(root) as its
master, which does not create a new window.  Changing Frame to Toplevel
in the class statement and the call to __init__ causes them to act
identically.


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


Re: Cross platform Python app deployment

2007-07-30 Thread vasudevram
On Jul 30, 4:42 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Will McGugan wrote:
> > Hi,
>
> > Is there some reference regarding how to package a Python application
> > for the various platforms? I'm familiar with Windows deployment - I use
> > Py2Exe & InnoSetup - but I would like more information on deploying on
> > Mac and Linux.
>
> On mac, there is py2app that allows to create application-bundles you can
> then install. Either including a python interpreter, or using an installed
> one.
>
> Diez

You could also try PyInstaller - see 
http://pyinstaller.hpcf.upr.edu/cgi-bin/trac.cgi
The site says it works on Windows, Linux and IRIX, so no Mac ...

Vasudev Ram
Biz site: http://www.dancingbison.com
Blog (on software innovation): http://jugad.livejournal.com
PDF creation/construction toolkit: http://sourceforge.net/projects/xtopdf

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


Re: Process Control Help

2007-07-30 Thread Azazello
On Jul 28, 1:40 am, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
>  <[EMAIL PROTECTED]> wrote:
>
> > I'm attempting to start some process control using Python.  I've have
> > quite a bit of literature on networking, and have made some tinkering
> > servers and clients for different protocols HTTP, FTP, etc... But now
> > it's time for the murky web of industrial protocol.  I'm looking to
> > start with IO and servo controls via  Ethernet.
>
> > Questions:
>
> > Is there an existing forum on this already?
> > What protocols are the most python friendly? i.e. are transparent
> > enough that i can create my own python driver. (or do these drivers
> > exist?)
> > What ethernet accesible servo and IO industrial devices have people
> > had success with?
>
> What is it that you are trying to do?
> Some of the commercial devices come with their own software, and
> you may not need python or anything else.
> A lot of the industrial connectivity is still RS-485 or RS-422 and not
> Ethernet based - although some of the protocols, have, I think, been ported.
>
> If you say more, then someone can maybe help you, as there are quite a few
> people on this group who seem to dabble in process control.
>
> - Hendrik- Hide quoted text -
>
> - Show quoted text


We're looking to run some industrial machinery from a PC.  Starting
with some basic servo controls and IO port reading for something like
an XYZ table (just X would be a good start!).  Now there is some
existing software out there for PC control but this software is, to my
understanding, largely unnecessary and "black box".  This "black box"
creates a problem when trying to e.g. control servos and IO with the
same program.  And if we want to include an HMI like a touchscreen, or
export the machinery's production into a RSS feed, the web of software
becomes messy and slow. If we could consolidate this software into a
single, non "black-box" package, we could see significant improvements
in development time. Having to program 3 different devices with three
different languages to control your PLC, Servos, and module X is the
status quo we face, but it is quite frustrating and limited.  Soo
I need to find some ethernet friendly IO, serial would be fine but but
it's a leash in many instances.  I know some protocols have been
ported to ethernet, but I am having extreme difficulty figuring out
what these protocols entail. ModBus/TCP is the one I'd like to
choose.  I know that people have done this kind of software but it
seems that industrial python remains a bit taboo because of
proprietary issues...

Ty

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


Re: How to write GUI and event separately in wxPython??

2007-07-30 Thread Steve Holden
Marc 'BlackJack' Rintsch wrote:
> On Mon, 30 Jul 2007 06:32:55 -0400, Steve Holden wrote:
> 
>>  >>> [x for x in xrange(0, 101)] == [y for y in xrange(101)]
>> True
> 
> First I thought: Why the unnecessary list comprehension but to my surprise:
> 
> In [33]: xrange(42) == xrange(42)
> Out[33]: False
> 
> That's strange.
> 
Not so strange really. The two xrange objects are different (though I 
confess I haven't looked to see how they implement comparisons), but 
iterating over them produces the same result.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Replacing overloaded functions with closures.

2007-07-30 Thread Neil Cerutti
On 2007-07-30, king kikapu <[EMAIL PROTECTED]> wrote:
> i am trying, to no avail yet, to take a C#'s overloaded
> functions skeleton and rewrite it in Python by using closures.
> I read somewhere on the net
> (http://dirtsimple.org/2004/12/python-is- not-java.html) that
> in Python we can reduce code duplication for overloaded
> functions by using closures.
>
> I do not quite understand this. Let's say we have the following
> simple C# code:
>
> int func(int i) { return i * 2; }
> string func(string s) { return s + s; }
> bool func(bool f) { return !f; }
>
> I wasn't able to find a way to express this thing in closures.

The closures discussed in the article are not a solution for
function overloading. They are a solution for function
composition.

Python generally has no need for function name overloading--if
you really want it you must do it manually using runtime type
checking.

def func(obj):
  if isinstance(obj, bool):
return not obj
  elif isinstance(obj, int):
return obj * 2
  elif isinstance(obj, basestring):
return obj + obj
  else:
raise NotImplementedError('type %r not supported' % type(obj))

The article you linked, when discussing Python closures is really
just advocating the use of higher-order functions. But Java's
verbosity and lack of free functions are the only irritating
obstacle to using them just as you would in Python. I'm not sure
what the author was getting at, exactly.

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


Re: Events: The Python Way

2007-07-30 Thread kyosohma
On Jul 29, 3:14 pm, "Gianmaria" <[EMAIL PROTECTED]> wrote:
> "David Wilson" <[EMAIL PROTECTED]> ha scritto nel messaggionews:[EMAIL 
> PROTECTED]
>
>
>
> > Hi there,
>
> > Python has no built-in way of doing this. You may consider writing
> > your own class if you like this pattern (I personally do):
>
> > class Event(object):
> >def __init__(self):
> >self.subscribers = set()
>
> >def __iadd__(self, subscriber):
> >self.subscribers.add(subscriber)
> >return self
>
> >def __isub__(self, subscriber):
> >self.subscribers.pop(subscriber)
> >return self
>
> >def __call__(self, *args, **kwargs):
> >for subscriber in self.subscribers:
> >subscriber(*args, **kwargs)
>
> > def HandleFoo(strng):
> >print "HandleFoo:", strng
>
> > OnFoo = Event()
> > OnFoo += HandleFoo
>
> > OnFoo("Test.")
>
> > On 29/07/07, Gianmaria <[EMAIL PROTECTED]> wrote:
> >> Hi,
> >> i'm a .net programmer and i'm learnig python, so this question can be
> >> very
> >> stupid or easy for python programmers. I've a doubt about events here
> >> is
> >> what:
>
> >> in c# for example i can write a delegate and an event in this way...
>
> >> public delegate SomethingChangedHandler(string message);
> >> public event SomethingChangedHandler SomethingChanged;
>
> >> and later in the code fire this event in this way...
>
> >> if(SomethingChanged != null)
> >> {
> >> SomethingChanged("Nothing important");
> >> }
>
> >> and the subscription of this event of other objects can be easy as
>
> >> eventGeneratorObject.SomethingChanged += new
> >> SomethingChangedHandler(aFunctionto_takecareof_it);
>
> >> and even the handlig of the event is aesy...
>
> >> void aFunctionto_takecareof_it(string msg)
> >> {
>
> >> }
>
> >> now the question is.. how can i do the same using Python? Every help
> >> is
> >> appreciated
>
> >> Regards,
> >> Gianmaria
>
> >> --
> >>http://mail.python.org/mailman/listinfo/python-list
>
> Txs so much.
> Gianmaria

I think the pubsub module in wxPython does what you are referring to.
Of course, usually you would need to be writing a GUI if you used it.
Here's some links on it:

http://www.wxpython.org/docs/api/wx.lib.pubsub-module.html
http://www.wxpython.org/docs/api/wx.lib.pubsub.PublisherClass-class.html

They also mention it in their wiki / cookbook. Unfortunately, the
wxPython website seems screwed up today. I've never seen it behave
like this. But when it's back up, I'd highly recommend checking it
out. Or just browse Google's cached copies...

Mike

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


Re: Detecting __future__ features

2007-07-30 Thread Steve Holden
Lawrence Oluyede wrote:
> Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>> Is there any general mechanism? 
> 
> I'd just use the expected future feature and if the result is not what I
> expect (or Python raises any kind of exception, like using a keyword not
> present) I'd think I'm in the past :-)
> 
Of course if the use of the feature creates a syntax error in the 
__main__ module (as it might currently for a use of the "with" keyword 
in 2.5, for example) then there is no way to catch the exception and you 
are therefore SOL, no?

[EMAIL PROTECTED] ~/Projects/Python
$ cat test11.py
with open("myfile.txt") as f:
 print l for l in f


[EMAIL PROTECTED] ~/Projects/Python
$ python test11.py
test11.py:1: Warning: 'with' will become a reserved keyword in Python 2.6
   File "test11.py", line 1
 with open("myfile.txt") as f:
 ^
SyntaxError: invalid syntax


regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Bug? exec converts '\n' to newline in docstrings!?

2007-07-30 Thread Edward K Ream
It looks like both exec and execfile are converting "\n" to an actual 
newline
in docstrings!

Start idle:

Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on
win32
[rest of signon deleted]

>>> s = '''\
strings = 'abc'.split("\n")
'''
>>> print s
strings = 'abc'.split("
")

I see this in my own calls to exec and execfile.  Is this a bug or am I
missing something?

Edward
---
Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html





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


Re: How to write GUI and event separately in wxPython??

2007-07-30 Thread Chris Mellon
On 7/30/07, Steve Holden <[EMAIL PROTECTED]> wrote:
> Marc 'BlackJack' Rintsch wrote:
> > On Mon, 30 Jul 2007 06:32:55 -0400, Steve Holden wrote:
> >
> >>  >>> [x for x in xrange(0, 101)] == [y for y in xrange(101)]
> >> True
> >
> > First I thought: Why the unnecessary list comprehension but to my surprise:
> >
> > In [33]: xrange(42) == xrange(42)
> > Out[33]: False
> >
> > That's strange.
> >
> Not so strange really. The two xrange objects are different (though I
> confess I haven't looked to see how they implement comparisons), but
> iterating over them produces the same result.


nitpick: list(xrange(42)) == list(xrange(42)) is slightly more concise
than the list comp..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing overloaded functions with closures.

2007-07-30 Thread king kikapu
> The closures discussed in the article are not a solution for
> function overloading. They are a solution for function
> composition.

Hmmm

>
> Python generally has no need for function name overloading--if
> you really want it you must do it manually using runtime type
> checking.
>
> def func(obj):
>   if isinstance(obj, bool):
> return not obj
>   elif isinstance(obj, int):
> return obj * 2
>   elif isinstance(obj, basestring):
> return obj + obj
>   else:
> raise NotImplementedError('type %r not supported' % type(obj))

I have already come up with that solution but i was a little excited
from that article that i can do the same thing with closures...And get
rid of the isinstance commands.


> I'm not sure what the author was getting at, exactly.

May be that point confused me too!

Thanks Neil!

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


Re: Bug? exec converts '\n' to newline in docstrings!?

2007-07-30 Thread Diez B. Roggisch
Edward K Ream wrote:

> It looks like both exec and execfile are converting "\n" to an actual
> newline
> in docstrings!
> 
> Start idle:
> 
> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)]
> on win32
> [rest of signon deleted]
> 
 s = '''\
> strings = 'abc'.split("\n")
> '''
 print s
> strings = 'abc'.split("
> ")
> 
> I see this in my own calls to exec and execfile.  Is this a bug or am I
> missing something?

AFAIK docstrings are nothing special. So \-escaping is of course available,
as it's an important feature for strings in general.

For the case at hand, 

strings = 'abc'.split("\\n")

might help.

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


Re: Bug? exec converts '\n' to newline in docstrings!?

2007-07-30 Thread Steve Holden
Edward K Ream wrote:
> It looks like both exec and execfile are converting "\n" to an actual 
> newline
> in docstrings!
> 
> Start idle:
> 
> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on
> win32
> [rest of signon deleted]
> 
 s = '''\
> strings = 'abc'.split("\n")
> '''
 print s
> strings = 'abc'.split("
> ")
> 
> I see this in my own calls to exec and execfile.  Is this a bug or am I
> missing something?
> 
Python is doing exactly what you told it to do. You created a string 
with triple single-quote delimiters. Nothing in the string literal 
syntax says that escape sequences will not be actioned, so the literal 
has a value that includes a newline.

This has nothing to do with exec, and I don't believe it will happen 
with execfile should you create a file with a legal Python program 
inside it. The problem is because you are trying to represent a Python 
program as a Python string literal, and doing it incorrectly.

What you did is no different from writing:

 >>> s = '''\
... This is a string with\nan embedded newline'''
 >>> print s
This is a string with
an embedded newline
 >>>

It just doesn't match your expectations, is all.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: How to write GUI and event separately in wxPython??

2007-07-30 Thread Steve Holden
Chris Mellon wrote:
> On 7/30/07, Steve Holden <[EMAIL PROTECTED]> wrote:
>> Marc 'BlackJack' Rintsch wrote:
>>> On Mon, 30 Jul 2007 06:32:55 -0400, Steve Holden wrote:
>>>
  >>> [x for x in xrange(0, 101)] == [y for y in xrange(101)]
 True
>>> First I thought: Why the unnecessary list comprehension but to my surprise:
>>>
>>> In [33]: xrange(42) == xrange(42)
>>> Out[33]: False
>>>
>>> That's strange.
>>>
>> Not so strange really. The two xrange objects are different (though I
>> confess I haven't looked to see how they implement comparisons), but
>> iterating over them produces the same result.
> 
> 
> nitpick: list(xrange(42)) == list(xrange(42)) is slightly more concise
> than the list comp..

Indeed. I wonder if anyone will pick a nit with the nit you picked on my 
nitpick ...

nitty-gritti-ly y'rs  - steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Replacing overloaded functions with closures.

2007-07-30 Thread Bruno Desthuilliers
king kikapu a écrit :
> Hi,
> 
> i am trying, to no avail yet, to take a C#'s overloaded functions
> skeleton and rewrite it in Python by using closures.
> I read somewhere on the net (http://dirtsimple.org/2004/12/python-is-
> not-java.html) that in Python we can reduce code duplication for
> overloaded functions by using closures.

Then you should re-read more carefully this article. While closures are 
effectively a great way to reduce code duplication, they are by no mean 
presented as a way to replace function overloading - or at least not 
directly[1]. The idea presented here is to use closures to write 
functions that will return "parameterized" functions, and (IMHE at 
least) this is mostly useful in frameworks, ORMs and like.

[1] you may want to have a look at another work by the same author:
http://peak.telecommunity.com/DevCenter/VisitorRevisited
which introduces the RuleDispatch generic function package.

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

Re: Bug? exec converts '\n' to newline in docstrings!?

2007-07-30 Thread Edward K Ream
> The problem is because you are trying to represent a Python
program as a Python string literal, and doing it incorrectly.

Yes, that is exactly the problem.  Thanks to all who replied.  Changing 
changing '\n' to '\\n' fixed the problem.

Edward

Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html



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


Re: making a variable available in a function from decorator

2007-07-30 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
(top-post corrected)
> 
> On 30 Jul 2007 06:17:25 GMT, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> 
> wrote:
>> On Sun, 29 Jul 2007 15:22:47 -0700, [EMAIL PROTECTED] wrote:
>>
>>> I create a variable in a decorator. i want to be able to access that
>>> variable in the function to be decorated. How to do this?
 >
>> Pass it as argument to the function:
>>
>> def deco(func):
>> eggs = 42
>> def decorated(*args, **kwargs):
>> kwargs['spam'] = eggs
>> func(*args, **kwargs)
>> return decorated
>>
>> @deco
>> def test(parrot, spam):
>> print parrot, spam

 > is it possible to do this without passing it as a function argument?

What's your use case, exactly ? Having a function depending on a name 
being set by a decorator is not exactly pythonic, and arguments are 
meant to pass variables to functions...


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


Database objects? Persistence? Sql Server woes

2007-07-30 Thread Mike Howarth

I've been having a few problems with connecting to SQL Server, initially I
was using dblib however found some problems with returning text fields
whereby all text fields were ignored and it bawked at multiline sql
statements.

Having found these major stumbling blocks I've started using pymssql which
seems less flaky. One problem I've stumbled across is that I seem to reach
my max connections  on the database fairly easily (given how my script was
written) and therefore have used the singleton pattern on my database
object.

Great problem solved, or so I thought.

Using the following code I'm finding that the Set is now also being enforced
as a singleton as well.

class Set(Database,Product):

 def __init__(self, *args, **kw): 
 
 Database.__init__(self)
 Product.__init__(self)

 def dosomething(self):
 cu = self.c.cursor()

Having sat back and thought about it, its easy to understand why this is
occurring given I'm indicating that Set belongs to Database and therefore
this is a singleton as well.

Being relatively new to Python I'm unsure on how to then go about using a
database object between each class. Can anyone advise me on how they
approach this, and whether there is a common approach to this?

-- 
View this message in context: 
http://www.nabble.com/Database-objects--Persistence--Sql-Server-woes-tf4171199.html#a11866779
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: pythonic parsing of URL

2007-07-30 Thread GreenH
On Jul 27, 10:04 pm, Steven D'Aprano
<[EMAIL PROTECTED]> wrote:
> On Sat, 28 Jul 2007 03:10:32 +, GreenH wrote:
> > I get some string as below from a library method (qt3
> > QDropEvent.data()) I use.
> > file:///C:/Documents%20and%20Settings/Username/My%20Documents/45-61-Abc%20fold-%20den.vru
>
> > I need file path on my system, for the above example:
> > C:/Documents and Settings/Username/My Documents/45-61-Abc fold-
> > den.vru
>
> > I am doing the below, it doesn't look pythonic,
> > can someone suggest any elegant solution, which is not too cryptic to
> > understand? yep, I do care about readability of the code to average
> > python user :)
>
> Try this:
>
> import urlparse, sys
> fileURLname = ("file:///C:/Documents%20and%20Settings/Username/"
> "My%20Documents/45-61-Abc%20fold-%20den.vru")
> pathname = urlparse.urlparse(fileURLname)[2]
> if sys.platform == "win32":
> import nturl2path
> clean = nturl2path.url2pathname(pathname)
> else:
> import urllib
> clean = urllib.unquote(pathname)
> print clean
>
> > 
> >  tmpTuple = urlparse.urlparse(fileURLname)
>
> > tmpString = tmpTuple[2].strip('/\\')
>
> > fileName = urllib.unquote(tmpString)
>
> > #For some reason the string contained in 'fileName' has some
> > unprintable trailing characters, Any ideas on that?
>
> It works for me: No trailing characters at all, printable or otherwise.
>
> >>> len(fileName.split('.vru', 1)[1])
>
> 0
>
> --
> Steven.

Hi!
Thanks for the reply. The unprintable character was null byte.

-Greene.

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


Re: TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why?

2007-07-30 Thread Gilbert Fine
Thanks. I think I have some direction to do logging, to get more
information about this problem.

It seems that I don't get used to dynamic language yet.

--
Gilbert

On Jul 30, 7:20 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>
> > On Mon, 30 Jul 2007 03:36:33 -0700, Gilbert Fine wrote:
>
> >> This is a very strange exception raised from somewhere in our
> >> program. I have no idea how this happen. And don't know how to
> >> reproduce. It just occurs from time to time.
>
> > Maybe different `Decimal`\s?  Here's how to reproduce such a
> > traceback:
>
> 
>
> Or even just one Decimal type but not one which supports subtraction:
>
> >>> class Decimal(object):
>
>  pass
>
> >>> a = Decimal()
> >>> b = Decimal()
> >>> a-b
>
> Traceback (most recent call last):
>   File "", line 1, in 
> a-b
> TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'
>
> Another option of course is that Decimal() did support substraction but
> someone deleted it:
>
> >>> from decimal import Decimal
> >>> del Decimal.__sub__
> >>> Decimal()-Decimal()
>
> Traceback (most recent call last):
>   File "", line 1, in 
> Decimal()-Decimal()
> TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'


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


Re: making a variable available in a function from decorator

2007-07-30 Thread Evan Klitzke
On 7/30/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> is it possible to do this without passing it as a function argument?
>

Sort of. Functions are objects in python, so you can set attribute on them. E.g.

def foo():
return foo.c

foo.c = 1
print foo()

Which will print 1. Of course, it would generally be better to write
your own class for this sort of thing, so that you can set the
variable in the instance scope.

-- 
Evan Klitzke <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making Gridded Widgets Expandable

2007-07-30 Thread Jim
On Jul 30, 8:24 am, "Hamilton, William " <[EMAIL PROTECTED]> wrote:
> > From: Jim
> > Hi,
> > I'm looking at page 548 of Programming Python (3rd Edition) by Mark
> > Lutz.
> > The following GUI script works with no problem, i.e., the rows and
> > columns expand:
> > =
> > # Gridded Widgets Expandable page 548
>
> > from Tkinter import *
> > colors = ["red", "white", "blue"]
>
> > def gridbox(root):
> > Label(root, text = 'Grid').grid(columnspan = 2)
> > r = 1
> > for c in colors:
> > l = Label(root, text=c, relief=RIDGE, width=25)
> > e = Entry(root, bg=c,   relief=SUNKEN, width=50)
> > l.grid(row=r, column=0, sticky=NSEW)
> > e.grid(row=r, column=1, sticky=NSEW)
> > root.rowconfigure(r, weight=1)
> > r += 1
> > root.columnconfigure(0, weight=1)
> > root.columnconfigure(1, weight=1)
>
> > root = Tk()
> > gridbox(Toplevel(root))
> > Button(root, text="Quit", command=root.quit).grid()
> > mainloop()
> > =
> > However, the following GUI script using class does not expand rows and
> > columns:
> > =
> > # Gridded Widgets Expandable 2
>
> > from Tkinter import *
> > colors = ["red", "white", "blue"]
>
> > class GUI(Frame):
> > def __init__(self,master):
> > Frame.__init__(self,master)
> > self.grid()
> > self.gridbox()
>
> > def gridbox(self):
> > Label(self, text = 'Grid').grid(columnspan = 2)
> > r = 1
> > for c in colors:
> > l = Label(self, text=c, relief=RIDGE, width=25)
> > e = Entry(self, bg=c,   relief=SUNKEN, width=50)
> > l.grid(row=r, column=0, sticky=NSEW)
> > e.grid(row=r, column=1, sticky=NSEW)
> > self.rowconfigure(r, weight=1)
> > r += 1
> > self.columnconfigure(0, weight=1)
> > self.columnconfigure(1, weight=1)
>
> > root = Tk()
> > root.title("Gridded Widgets Expandable")
> > app = GUI(root)
> > Button(root, text="Quit", command=root.quit).grid()
> > root.mainloop()
> > =
> > What am I missing?
>
> In the first, your gridbox has Toplevel(root) as its master, causing it
> to be created in a new window.  In the second, it has Frame(root) as its
> master, which does not create a new window.  Changing Frame to Toplevel
> in the class statement and the call to __init__ causes them to act
> identically.
>
> --
> -Bill Hamilton- Hide quoted text -
>
> - Show quoted text -

Thank you Bill Hamilton.

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


Re: Replacing overloaded functions with closures.

2007-07-30 Thread Terry Reedy

"king kikapu" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| > def func(obj):
| >   if isinstance(obj, bool):
| > return not obj
| >   elif isinstance(obj, int):
| > return obj * 2
| >   elif isinstance(obj, basestring):
| > return obj + obj
| >   else:
| > raise NotImplementedError('type %r not supported' % type(obj))
|
| I have already come up with that solution but
|...And get rid of the isinstance commands.

A sometimes alternative is a dict (untested):

func_switch = {
  bool: lambda o: not o,
  int: lambda i: i*2,
  str: lambda s: s+s,
  unicode: lambda s: s+s
}

def func(o):
  try: return func_switch[type(o)]
  except IndexError:
 raise NotImplementedError('type %r not supported' % type(obj))

but this does not work for instances of subclasses the way isinstance does.

tjr




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


Python-URL! - weekly Python news and links (Jul 30)

2007-07-30 Thread Gabriel Genellina
QOTW:  "If you really want to learn hard-core Python, probably your best bet
is:
* read everything Tim Peters has ever written in comp.lang.python
 (this will take a few months), start with "import this"
* read everything the PyPy guys have ever written (particularly
  Christian and Armin)
* read and try to beat the more exotic recipes in the Python cookbook
* read the papers from the various PyCons on metaclasses and the
  like, build a couple of dozen metaclasses and descriptors." - Mike C.
Fletcher

"Why would you want to become a programmer?  Programmers smell bad, they have
no social life, they get treated like crap by everyone.  They can get paid
pretty well but then they spend all the money on useless electronic junk so
they still live like bums.  There is only one reason to be a programmer,
which is that the drive to program burns in you like a fire.  But in that
case don't ask how to become a programmer, because you are already one, so
welcome to the ranks ;-)." - Paul Rubin


Moving from .net to Python: How to implement Events
and Delegates (Observer pattern)

http://groups.google.com/group/comp.lang.python/browse_thread/thread/c6808e6362996834/

How to efficiently access the first, second, etc. lines of a text file

http://groups.google.com/group/comp.lang.python/browse_thread/thread/800e92738e0a23b/

Borrowing from the D language: 123 456 789 == 123456789, and
other suggestions.

http://groups.google.com/group/comp.lang.python/browse_thread/thread/93dc57f9190b93bc/

Ways to write an "is_iterable" function, and why there can't
be an universal version:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/c37eea080073729f/

Using ClientForm and mechanize to automate web form submissions

http://groups.google.com/group/comp.lang.python/browse_thread/thread/d544e5a719692775/

Started as: Where do they teach Python officially?,
later discussing what's good for a programmer to know:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/fafd2b5042ab2453/

math.pow(3,50)!=3**50 -or- Don't use floating point exponentiation
when you actually want an integer operation

http://groups.google.com/group/comp.lang.python/browse_thread/thread/b2155e82b23e1bea/

Closures/Blocks in Python: what is good Ruby code
style is not necesarily good for Python.

http://groups.google.com/group/comp.lang.python/browse_thread/thread/7e3ee98e03731ecb/

How get "next month's" name: the orthodox ways, and a
tricky one by Carsten Haese:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/1baa0d207ca55662/



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

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

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

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

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

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

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

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

Steve Bethard continues the marvelous tradition early borne by
Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim
Lesher of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

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

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

Much of Python's real work takes place on Special-Interest Group
ma

Re: Database objects? Persistence? Sql Server woes

2007-07-30 Thread Steve Holden
Mike Howarth wrote:
> I've been having a few problems with connecting to SQL Server, initially I
> was using dblib however found some problems with returning text fields
> whereby all text fields were ignored and it bawked at multiline sql
> statements.
> 
> Having found these major stumbling blocks I've started using pymssql which
> seems less flaky. One problem I've stumbled across is that I seem to reach
> my max connections  on the database fairly easily (given how my script was
> written) and therefore have used the singleton pattern on my database
> object.
> 
> Great problem solved, or so I thought.
> 
> Using the following code I'm finding that the Set is now also being enforced
> as a singleton as well.
> 
> class Set(Database,Product):
> 
>  def __init__(self, *args, **kw): 
>  
>  Database.__init__(self)
>  Product.__init__(self)
> 
>  def dosomething(self):
>  cu = self.c.cursor()
> 
> Having sat back and thought about it, its easy to understand why this is
> occurring given I'm indicating that Set belongs to Database and therefore
> this is a singleton as well.
> 
> Being relatively new to Python I'm unsure on how to then go about using a
> database object between each class. Can anyone advise me on how they
> approach this, and whether there is a common approach to this?
> 
If you want to share a database object between (instances of) several 
classes there are two easy ways. The absolute easiest is to create a 
database connection that's global to the module. References to the 
connection inside you other objects will then reference the global 
database connection. e.g.:

conn = pymssql.connect(...)

class Set:

   ...

   def dosomething(self):
 self.cu = conn.cursor()

The other way is to pass the connection in to the object's __init__() 
method and save it as an instance variable so it can be used inside the 
instance's methods. e.g.:

conn = pymssql.connect(...)

class Set:

   def __init__(self, conn, ...):
 self.conn = conn
 ...

   def dosomething(self):
 self.cu = self.conn.cursor()

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


RE: Free support for Python developers

2007-07-30 Thread Carroll, Barry
Viktor:

This is a great idea.  Thank you

I don't currently have a voice setup on my machine, but will try to get
one as soon as possible.  I would be pleased to trade English practice
for Python support.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed

> -Original Message-
> From: Ferenczi Viktor [mailto:[EMAIL PROTECTED]
> Sent: Sunday, July 29, 2007 5:29 PM
> To: [EMAIL PROTECTED]
> Subject: Free support for Python developers
> 
> I am pleased to announce the availability of python support for
English
> speaking developers. The service is free of charge. More information:
> 
> http://python.cx.hu/support/


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


Re: Bug? exec converts '\n' to newline in docstrings!?

2007-07-30 Thread Stargaming
On Mon, 30 Jul 2007 11:00:14 -0500, Edward K Ream wrote:

>> The problem is because you are trying to represent a Python
> program as a Python string literal, and doing it incorrectly.
> 
> Yes, that is exactly the problem.  Thanks to all who replied.  Changing
> changing '\n' to '\\n' fixed the problem.

Raw strings (r'this \n will stay') might help, too. See http://
docs.python.org/ref/strings.html#l2h-14
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Database objects? Persistence? Sql Server woes

2007-07-30 Thread Diez B. Roggisch
Mike Howarth schrieb:
> I've been having a few problems with connecting to SQL Server, initially I
> was using dblib however found some problems with returning text fields
> whereby all text fields were ignored and it bawked at multiline sql
> statements.
> 
> Having found these major stumbling blocks I've started using pymssql which
> seems less flaky. One problem I've stumbled across is that I seem to reach
> my max connections  on the database fairly easily (given how my script was
> written) and therefore have used the singleton pattern on my database
> object.
> 
> Great problem solved, or so I thought.
> 
> Using the following code I'm finding that the Set is now also being enforced
> as a singleton as well.
> 
> class Set(Database,Product):
> 
>  def __init__(self, *args, **kw): 
>  
>  Database.__init__(self)
>  Product.__init__(self)
> 
>  def dosomething(self):
>  cu = self.c.cursor()
> 
> Having sat back and thought about it, its easy to understand why this is
> occurring given I'm indicating that Set belongs to Database and therefore
> this is a singleton as well.
> 
> Being relatively new to Python I'm unsure on how to then go about using a
> database object between each class. Can anyone advise me on how they
> approach this, and whether there is a common approach to this?

You might consider using a ORM mapper, like SQLObject or SQLAlchemy. If 
they support your backend, that is.

Apart from that, this might help:

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

Store a connection per thread.

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


Re: problems with logging module

2007-07-30 Thread Gabriel Genellina
En Mon, 30 Jul 2007 03:50:52 -0300, Alia Khouri <[EMAIL PROTECTED]>  
escribió:

> But I'm not letting the logging module off, it's still not the easiest
> or most intuitive module to work with.
>
> For example: a basic Log class that can be programatically configured
> would be quicker to work with then messing around with three different
> classes types if you want to get beyond basicConfig functionality:
> (Logger, handlers, formatters) To be able to do this would be nice:
>
> from logging import Log
>
> class MyClass:
> def __init__(self, x):
> self.x = x
> self.log = Log(
> level=logging.DEBUG,
> format="%(asctime)s %(levelname)s: %(message)s",
> datefmt = '%H:%M:%S',
> filename='app.log',
> filemode='a'
> )

You are not going beyond basicConfig - I'd write the above as:

logging.basicConfig(...)

def __init__(self, x):
 self.x = x
 self.log = logging.getLogger("a.nice.name")

If you *do* need more than a handler, or different formatters for  
different loggers, then you must write your own setup anyway; perhaps  
using logging.config files, or perhaps writing your own code. I can't  
think of a simple and generic approach (beyond what basicConfig provides)  
but if you can write something that other people find useful, feel free to  
submit a patch.

-- 
Gabriel Genellina

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


Re: How to write GUI and event separately in wxPython??

2007-07-30 Thread Marc 'BlackJack' Rintsch
On Mon, 30 Jul 2007 11:16:01 -0400, Steve Holden wrote:

> Marc 'BlackJack' Rintsch wrote:
>> First I thought: Why the unnecessary list comprehension but to my surprise:
>> 
>> In [33]: xrange(42) == xrange(42)
>> Out[33]: False
>> 
>> That's strange.
>> 
> Not so strange really. The two xrange objects are different (though I 
> confess I haven't looked to see how they implement comparisons), but 
> iterating over them produces the same result.

They are different objects, so are range(23) and another range(23) but
those compare equal.  Somehow I expected two seemingly equal `xrange`
objects compare equal too.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: Re: Comparing Dictionaries

2007-07-30 Thread Kenneth Love

>From: "Steven D'Aprano" <[EMAIL PROTECTED]>
>Newsgroups: comp.lang.python
>Subject: Re: Comparing Dictionaries
>Date: Sat, 28 Jul 2007 10:21:14 +1000
>To: python-list@python.org
>
>On Fri, 27 Jul 2007 14:11:02 -0500, Kenneth Love wrote:
>
> > The published recipe (based on ConfigParser) did not handle my INI
> > files.  I have periods in both the section names and the key names.
> > The INI files contents were developed according to an internally
> > defined process that other non-Python programs rely on.  The published
> > recipe *did not work* with this scenario.
>
>I think you have made a mistake. ConfigParser as published certainly DOES
>accept periods in section and option names. It just *works*.

The recipe I'm using is based upon ConfigParser and creates a dictionary
that is based on the contents of the INI file.  The dictionary's key is
based on the section name and the key name from the INI file.  The two
are concatenated with a separator.

In the original recipe, the separator is a period.  To use your example
(deleted as an attempt at brevity), the dictionary would be:

{ "SECTION.FRED.option.wilma" : "45" }

As originally written, the section name is now "SECTION" when you write
the INI file back out.  The key is "FRED.option.wilma".

Here is the original recipe:

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

My version replaces the period with a dollar sign giving:

{ "SECTION.FRED$option.wilma" : "45" }

I also removed the "import string" and put both the load() and save()
functions in a file with proper comments and the Python equivalent of
Javadoc comments.

>Even if the existing ConfigParser doesn't do what you want, the right way
>to fix the problem is not to recreate the entire module from scratch, but
>to subclass it:
>[snip]

In no way did I rewrite ConfigParser.  I have a real job with time
pressures and I'm not so arrogant as to think I could whip something
up in an hour that would be anywhere close to correct.

I see that I wasn't as clear as I thought I was in my original post
as you are second person to think I was developing my own INI solution.

All I wanted to know was "How do I compare two dictionaries to see if
they are equal?".  It turns out that this functionality is built-in
and it is my own stupid fault that my unit test was failing (modifying
working code and writing a unit test at the same time is a recipe for
failure).

Oh well.  Next time I'll spend two hours trying to figure it out instead
of one before I post.  :-\

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

-- 
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Kenneth Love   | Oklahoma Tax Commission
DP Programmer/Analyst  | Information Technology
(405) 522 - 5864   | http://www.tax.ok.gov/
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 


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


Re: Comparing Dictionaries

2007-07-30 Thread Kenneth Love
At 03:23 AM 7/28/2007, you wrote:
>Hi Kenneth,  being new to Python i wondered if you at least considered
>Doctests as part of your testing solution.
>Other languages don't have Doctest.
>
>- Paddy.

Until I read your post, I had never even heard of Doctest.  I will look
into it.

Here is the list of online sources I've found:

http://www.ibiblio.org/obp/thinkCSpy/index.html
http://www.diveintopython.org/toc/index.html
http://aspn.activestate.com/ASPN/Cookbook/Python


Here are the O'Reilly books I purchased from Barnes & Noble:

Python in a Nutshell (2nd ed.)
Python Cookbook (2nd ed.)
Programming Python (3rd ed.)

I am a slow reader.  So, if Doctests are mentioned in any of the above,
I haven't encountered it yet.

Specifically, my information on unit testing comes from reading about
half of this online chapter:

http://www.diveintopython.org/unit_testing/index.html

I will search on Google for more info on Doctest.

Thanks!

Sincerely,
Kenneth Love


-- 
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Kenneth Love   | Oklahoma Tax Commission
DP Programmer/Analyst  | Information Technology
(405) 522 - 5864   | http://www.tax.ok.gov/
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- 


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


►Watch Satellite Channels on your PC - FREE!◄

2007-07-30 Thread Camron S
Finally Available!  Who Else Wants to Watch Satellite TV On Your
Computer Without Paying Monthly Fees... FOR FREE?

For the very first time, Satellite TV is available on your computer
with our "Cutting-Edge" Software!

It's as Easy as 1...2...3...


1. Download our TVonPCPro software

2. Click on the channel you want to watch

3. Enjoy Satellite TV on your PC


It's That Simple!!

For More Details:http://tvfun.xt.cx

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


►Watch Satellite Channels on your PC - FREE!◄

2007-07-30 Thread Camron S
Finally Available!  Who Else Wants to Watch Satellite TV On Your
Computer Without Paying Monthly Fees... FOR FREE?

For the very first time, Satellite TV is available on your computer
with our "Cutting-Edge" Software!

It's as Easy as 1...2...3...


1. Download our TVonPCPro software

2. Click on the channel you want to watch

3. Enjoy Satellite TV on your PC


It's That Simple!!

For More Details:http://tvfun.xt.cx

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


Re: How to write GUI and event separately in wxPython??

2007-07-30 Thread star . public
On Jul 30, 11:42 am, "Chris Mellon" <[EMAIL PROTECTED]> wrote:

> > > On Mon, 30 Jul 2007 06:32:55 -0400, Steve Holden wrote:
>
> > >>  >>> [x for x in xrange(0, 101)] == [y for y in xrange(101)]
> > >> True

> nitpick: list(xrange(42)) == list(xrange(42)) is slightly more concise
> than the list comp..

Not that it has anything to do with this topic anymore, but I find the
list comp a bit clearer for expressing the thought 'each element in
one is the same as the coresponding element in the other, or: the
sequences are identical' -- the list() version would proabably have
had me going 'huh?' even longer ^_^.
--
[star for star in weaver]



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


Re: How to write GUI and event separately in wxPython??

2007-07-30 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> On Jul 30, 11:42 am, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
> 
 On Mon, 30 Jul 2007 06:32:55 -0400, Steve Holden wrote:
>  >>> [x for x in xrange(0, 101)] == [y for y in xrange(101)]
> True
> 
>> nitpick: list(xrange(42)) == list(xrange(42)) is slightly more concise
>> than the list comp..
> 
> Not that it has anything to do with this topic anymore, but I find the
> list comp a bit clearer for expressing the thought 'each element in
> one is the same as the coresponding element in the other, or: the
> sequences are identical' -- the list() version would proabably have
> had me going 'huh?' even longer ^_^.
> --
> [star for star in weaver]

Here's another one, a little more obscure still, but only valid in 2.5 
because of all():

 >>> all(x==y for (x, y) in zip(xrange(0, 101), xrange(101)))
True
 >>>

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OOP in Python book?

2007-07-30 Thread James Stroud
Dick Moores wrote:
> At 01:27 PM 7/28/2007, Dennis Lee Bieber wrote:
> 
>> On Fri, 27 Jul 2007 16:27:57 -0700, Dick Moores <[EMAIL PROTECTED]>
>> declaimed the following in comp.lang.python:
>>
>>
>> > Well, the publisher is Prentice Hall, "The world's leading
>> > educational publisher". Textbooks are typically expensive.
>> >
>>
>> Yeah... But at that price it should have hard-covers!
> 
> 
> Should have, but look at this popular Cultural Anthropology text 
> (paperback): . List price is $120.95 USD. 
> (BTW I just bought the 6th edition online for about $10.)
> 
> Then there's Calculus: Single Variable (Paperback) 
>  List price $123.95 USD.
> 
> And so it goes.
> 
> Dick
> 
> 

Balme your professors. They are not paying for the books. Of course most 
will be give a lot of lip-service to educational access for 
disadvantaged groups but thier choice of books usually suggests 
otherwise. The high price of textbooks and the tendency for professors 
to overlook alternatives is helping to keep the rich educated and the 
poor, well, poor.

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


win32 question in Python

2007-07-30 Thread Huang, Shun-Hsien
Hi, 

 

I am new in Python. I have one question in the database application in
python.

I have one excel file that I want to save in the database table. In the
Microsoft access, I can easy do this one by using Docmd ..

How do I use this one in Python? I already know how to connect to a
database through Python, but how do I copy a excel file into database
table by using Python?

 

Best Regards.

 

Shun-Hsien Huang (Fred)

 

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

yield keyword usage

2007-07-30 Thread Ehsan
hi
coulde any one show me the usage of  "yield" keyword specially in this
example:


"""Fibonacci sequences using generators

This program is part of "Dive Into Python", a free Python book for
experienced programmers.  Visit http://diveintopython.org/ for the
latest version.
"""

__author__ = "Mark Pilgrim ([EMAIL PROTECTED])"
__version__ = "$Revision: 1.2 $"
__date__ = "$Date: 2004/05/05 21:57:19 $"
__copyright__ = "Copyright (c) 2004 Mark Pilgrim"
__license__ = "Python"

def fibonacci(max):
a, b = 0, 1
while a < max:
yield a
a, b = b, a+b

for n in fibonacci(1000):
print n,

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


Re: Comparing Dictionaries

2007-07-30 Thread Paddy
On Jul 30, 8:30 pm, Kenneth Love <[EMAIL PROTECTED]> wrote:
> At 03:23 AM 7/28/2007, you wrote:
>
> >Hi Kenneth,  being new to Python i wondered if you at least considered
> >Doctests as part of your testing solution.
> >Other languages don't have Doctest.
>
> >- Paddy.
>
> Until I read your post, I had never even heard of Doctest.  I will look
> into it.
>
> Here is the list of online sources I've found:
>
> http://www.ibiblio.org/obp/thinkCSpy/index.htmlhttp://www.diveintopython.org/toc/index.htmlhttp://aspn.activestate.com/ASPN/Cookbook/Python
>
> Here are the O'Reilly books I purchased from Barnes & Noble:
>
> Python in a Nutshell (2nd ed.)
> Python Cookbook (2nd ed.)
> Programming Python (3rd ed.)
>
> I am a slow reader.  So, if Doctests are mentioned in any of the above,
> I haven't encountered it yet.
>
> Specifically, my information on unit testing comes from reading about
> half of this online chapter:
>
> http://www.diveintopython.org/unit_testing/index.html
>
> I will search on Google for more info on Doctest.
>
> Thanks!
>
> Sincerely,
> Kenneth Love

Add to your list:
  
http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-2-doctest.html
  http://en.wikipedia.org/wiki/Doctest

Have fun.

- Paddy.

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


Re: yield keyword usage

2007-07-30 Thread Erik Jones
On Jul 30, 2007, at 4:13 PM, Ehsan wrote:

> hi
> coulde any one show me the usage of  "yield" keyword specially in this
> example:
>
>
> """Fibonacci sequences using generators
>
> This program is part of "Dive Into Python", a free Python book for
> experienced programmers.  Visit http://diveintopython.org/ for the
> latest version.
> """
>
> __author__ = "Mark Pilgrim ([EMAIL PROTECTED])"
> __version__ = "$Revision: 1.2 $"
> __date__ = "$Date: 2004/05/05 21:57:19 $"
> __copyright__ = "Copyright (c) 2004 Mark Pilgrim"
> __license__ = "Python"
>
> def fibonacci(max):
> a, b = 0, 1
> while a < max:
> yield a
> a, b = b, a+b
>
> for n in fibonacci(1000):
> print n,

As in how it works?  Sure, when you use the yield statement in a  
function or method you turn it into a generator method that can then  
be used for iteration.  What happens is that when fibonacci(1000) is  
called in the for loop statement it executes up to the yield  
statement where it "yields" the then current value of a to the  
calling context at which point n in the for loop is bound to that  
value and the for loop executes one iteration.  Upon the beginning of  
the for loop's next iteration the fibonacci function continues  
execution from the yield statment until it either reaches another  
yield statement or ends.  In this case, since the yield occured in a  
loop, it will be the same yield statement at which point it will  
"yield" the new value of a.  It should be obvious now that this whole  
process will repeat until the condition a < max is not longer true in  
the fibonacci function at which point the function will return  
without yielding a value and the main loop (for n in ...) will  
terminate.



Erik Jones

Software Developer | Emma®
[EMAIL PROTECTED]
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate & market in style.
Visit us online at http://www.myemma.com


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


Directory

2007-07-30 Thread Rohan

I would like to get a list of sub directories in a directory.
If I use os.listdir i get a list of directories and files in that .
i only want the list of directories in a directory and not the files
in it.
anyone has an idea regarding this.

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


Re: Directory

2007-07-30 Thread Irmen de Jong
Rohan wrote:
> I would like to get a list of sub directories in a directory.
> If I use os.listdir i get a list of directories and files in that .
> i only want the list of directories in a directory and not the files
> in it.
> anyone has an idea regarding this.
> 

Look up os.walk (allows you to selectively walk over files and directories)
and/or os.path.isdir (allows you to test if a given path is a directory)

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


Re: yield keyword usage

2007-07-30 Thread [EMAIL PROTECTED]
On Jul 30, 4:40 pm, Erik Jones <[EMAIL PROTECTED]> wrote:
> On Jul 30, 2007, at 4:13 PM, Ehsan wrote:
>
>
>
>
>
> > hi
> > coulde any one show me the usage of  "yield" keyword specially in this
> > example:
>
> > """Fibonacci sequences using generators
>
> > This program is part of "Dive Into Python", a free Python book for
> > experienced programmers.  Visithttp://diveintopython.org/for the
> > latest version.
> > """
>
> > __author__ = "Mark Pilgrim ([EMAIL PROTECTED])"
> > __version__ = "$Revision: 1.2 $"
> > __date__ = "$Date: 2004/05/05 21:57:19 $"
> > __copyright__ = "Copyright (c) 2004 Mark Pilgrim"
> > __license__ = "Python"
>
> > def fibonacci(max):
> > a, b = 0, 1
> > while a < max:
> > yield a
> > a, b = b, a+b
>
> > for n in fibonacci(1000):
> > print n,
>
> As in how it works?  Sure, when you use the yield statement in a  
> function or method you turn it into a generator method that can then  
> be used for iteration.  What happens is that when fibonacci(1000) is  
> called in the for loop statement it executes up to the yield  
> statement where it "yields" the then current value of a to the  
> calling context at which point n in the for loop is bound to that  
> value and the for loop executes one iteration.  Upon the beginning of  
> the for loop's next iteration the fibonacci function continues  
> execution from the yield statment until it either reaches another  
> yield statement or ends.  In this case, since the yield occured in a  
> loop, it will be the same yield statement at which point it will  
> "yield" the new value of a.  It should be obvious now that this whole  
> process will repeat until the condition a < max is not longer true in  
> the fibonacci function at which point the function will return  
> without yielding a value and the main loop (for n in ...) will  
> terminate.

Also note that the function could terminate without ever executing
a yield statement (if max<0). In which case nothing would get printed
just like in

for n in []: print n,

You could also force the generator to abort rather than relying
on the while loop not executing by using a return instead of a yield
statement. This can be useful if the while executes even when given
bad arguments.

def fibonacci(max):
if max < 0:  # test for invalid argument
  print 'max must be >0' # diagnostic message
  return # kill generator
a, b = 0, 1
while a < max:
yield a
a, b = b, a+b

for n in fibonacci(1000):
print n,

print
print

for n in fibonacci(-1000):
print n,


## 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
##
## max must be >0


>
> Erik Jones
>
> Software Developer | Emma®
> [EMAIL PROTECTED]
> 800.595.4401 or 615.292.5888
> 615.292.0777 (fax)
>
> Emma helps organizations everywhere communicate & market in style.
> Visit us online athttp://www.myemma.com

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

Utilizing a raw IDispatch Pointer from Python

2007-07-30 Thread Brad Johnson
I have a C++ application that creates a collection of COM objects.

I would like to give the Python interpreter access to these interfaces that were
created in C++ land.

Stated another way, how can I have Python consume a IDispatch pointer from C++
and wrap it with one of those nice Python classes automatically?

Thanks in advance.

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


What is the "functional" way of doing this?

2007-07-30 Thread beginner
Hi,

If I have a number n and want to generate a list based on like the
following:

def f(n):
 l=[]
 while n>0:
 l.append(n%26)
 n /=26
return l

I am wondering what is the 'functional' way to do the same.

Thanks,
beginner

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


Re: win32 question in Python

2007-07-30 Thread Brad Johnson
Huang, Shun-Hsien  ercot.com> writes:

> 
but how do I copy a excel file into
> database table by using Python?
> 

I'm not sure if this helps, but you can access the Excel Automation model very
easily with:

import win32com.client

x1 = client.Dispatch("Excel.Application")

Now you can use the x1 object to access any of the properties and methods in the
Excel Automation model.

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


Re: win32 question in Python

2007-07-30 Thread Cappy2112

Hello Brad,

If you don't get a reply here, there is a win32 specific Python list
on ActiveState.com wher ethey do talk about excel & other Win32 python
issues.

On Jul 30, 3:49 pm, Brad Johnson <[EMAIL PROTECTED]> wrote:
> Huang, Shun-Hsien  ercot.com> writes:
>
>
>
> but how do I copy a excel file into
>
> > database table by using Python?
>
> I'm not sure if this helps, but you can access the Excel Automation model very
> easily with:
>
> import win32com.client
>
> x1 = client.Dispatch("Excel.Application")
>
> Now you can use the x1 object to access any of the properties and methods in 
> the
> Excel Automation model.


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


Re: 128 or 96 bit integer types?

2007-07-30 Thread [EMAIL PROTECTED]
On Jul 29, 11:35 pm, Tim Roberts <[EMAIL PROTECTED]> wrote:
> John DeRosa <[EMAIL PROTECTED]> wrote:
> >On Sat, 28 Jul 2007 00:19:02 -0700, "[EMAIL PROTECTED]"
> ><[EMAIL PROTECTED]> wrote:
>
> >>For example, how many ways can you put 492 marbles into
> >>264 ordered bins such that each bin has at least 1 marble?
>
> >>The answer
>
> >>66189415264331559482776409694993032407028709677550
> >>59629130019289014193777349831417543311612293951363
> >>4124491233746912456893016976209252459301489030
>
> >You missed that blue one in the corner...

Actually, the blue one in the corner wasn't missed, it was
deliberately omitted. When you add the restriction that each
bin must contain at least one marble, the number of partitions
of depth items into width bins is comb(depth-1,width-1).

So comb(491,263) IS, in fact, the correct answer even though
the marble count seems to be wanting.

>
> He lost that one to a talented 12-year-old with a keen eye and a
> well-balanced steelie...
> --
> Tim Roberts, [EMAIL PROTECTED]
> Providenza & Boekelheide, Inc.


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


Re: win32 question in Python

2007-07-30 Thread Brad Johnson
Cappy2112  gmail.com> writes:

> 
> 
> Hello Brad,
> 
> If you don't get a reply here, there is a win32 specific Python list
> on ActiveState.com wher ethey do talk about excel & other Win32 python
> issues.
> 

Thanks, but I believe this you meant to address the OP Shun-Hsien, not me. Just
wanted to clarify in case that confused anyone.

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


Re: Comparing Dictionaries

2007-07-30 Thread Paul Rubin
Kenneth Love <[EMAIL PROTECTED]> writes:
> I will search on Google for more info on Doctest.

Doctest is recent.  Try:

http://python.org/doc/lib/module-doctest.html

Diveintopython should probably be updated to use doctest instead
of unittest.  unittest is Java-descended and doesn't fit into Python
as well as doctest does.
-- 
http://mail.python.org/mailman/listinfo/python-list


Help text embedding in C code?

2007-07-30 Thread James Stroud
Hello All,

I have a python module I wrote in C some time ago and I have since 
forgotten how to use my functions and so I wanted to add some 
doc-strings such that "help(function_name)" would give some help in the 
interactive interpreter. In the cPython source, it seems like python 
wrapper functions provide this documentation in doc-strings. Is this the 
advisable way? It seems silly to have to write a python wrapper around a 
python extension just to have doc-strings available. Is it possible to 
embed this information in the C source directly or is that too much 
trouble and I should just start typing HTML.reStructuredText for this 
sort of thing?

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


Re: What is the "functional" way of doing this?

2007-07-30 Thread Paul Rubin
beginner <[EMAIL PROTECTED]> writes:
> def f(n):
>  l=[]
>  while n>0:
>  l.append(n%26)
>  n /=26
> return l
> 
> I am wondering what is the 'functional' way to do the same.

If you're trying to learn functional programming, maybe you should use
a functional language like Haskell or Scheme.  But anyway you might be
thinking of something like:

def f(n):
   def mseq(n):
  while n > 0:
 n,a = divmod(n, 26)
 yield a
   return list(mseq(n))

The above is not really "functional", but it's a reasonably natural
Python style, at least for me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why?

2007-07-30 Thread Zentrader
> from decimal import Decimal
>
> In [21]: a = Decimal()
>
> In [22]: class Decimal(object):
>: pass
>:
>
> In [23]: b = Decimal()
>
> In [24]: a - b

Perhaps I don't understand what you are doing here, but on line 22 you
overload Decimal.  If you just have
a = Decimal()
b = Decimal()
print a-b yields 0.  decimal.Decimal() can be subtracted from
decimal.Decimal().  decimal.Decimal() can not be subtracted from class
Decimal(object).  I would assume that they are different types.  Using
the original code, print type(a), type(b).

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


Re: What is the "functional" way of doing this?

2007-07-30 Thread [EMAIL PROTECTED]
On Jul 30, 3:48 pm, beginner <[EMAIL PROTECTED]> wrote:
> Hi,
>
> If I have a number n and want to generate a list based on like the
> following:
>
> def f(n):
>  l=[]
>  while n>0:
>  l.append(n%26)
>  n /=26
> return l
>
> I am wondering what is the 'functional' way to do the same.
>


Recursion is common in functional programming:

def f(n, l=None):
if l == None:
l = []
if n > 0:
return f(n/26, l + [n%26])
else:
return l

print f(1000)

--
Hope this helps,
Steven



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


Re: What is the "functional" way of doing this?

2007-07-30 Thread Steven D'Aprano
On Mon, 30 Jul 2007 22:48:10 +, beginner wrote:

> Hi,
> 
> If I have a number n and want to generate a list based on like the
> following:
> 
> def f(n):
>  l=[]
>  while n>0:
>  l.append(n%26)
>  n /=26
> return l
> 
> I am wondering what is the 'functional' way to do the same.


Seems like a perfectly good function to me :)


I don't know about "functional", but that's crying out to be written as a
generator:

def f(n):
while n > 0:
n, x = divmod(n, 26)
yield x



And in use:
>>> for x in f(1000):
... print x
...
12 
12 
1
>>> list(f(1000))
[12, 12, 1]


-- 
Steven.

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


Re: What is the "functional" way of doing this?

2007-07-30 Thread Paul Rubin
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> Recursion is common in functional programming:
> 
> def f(n, l=None):
> if l == None:
> l = []
> if n > 0:
> return f(n/26, l + [n%26])
> else:
> return l
> 
> print f(1000)

Right, this is functional style, but quite painful in Python (no tail
recursion, and look at all that list copying).
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >