Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-14 Thread Carl Banks
On Thursday, October 13, 2011 7:16:37 PM UTC-7, Steven D'Aprano wrote:
> > What I would expect to happen that all statements within the ooo block
> > may be executed out
> > of order. The block itself waits till all statements are returned before
> > continuing.
> 
> Why do you think this needs to be a language statement?
> 
> You can have that functionality *right now*, without waiting for a syntax
> update, by use of the multiprocessing module, or a third party module.
> 
> http://docs.python.org/library/multiprocessing.html
> http://wiki.python.org/moin/ParallelProcessing
> 
> There's no need for forcing language changes on everyone, whether they need
> it or not, for features that can easily be implemented as library code.

This goes a little beyond a simple threading mechanism, though.  It's more like 
guidance to the compiler that you don't care what order these are executed in; 
the compiler is then free to take advantage of this advice however it like.  
That could be to spawn threads, but it could also compile instructions to 
optimize pipelining and cacheing.  The compiler could also ignore it.  But you 
can see that, fully realized, syntax like that can do much more than can be 
done with library code.

Obviously that extra capability is a very long way off for being useful in 
CPython.


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


Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-14 Thread Carl Banks
On Thursday, October 13, 2011 5:35:30 AM UTC-7, Martin P. Hellwig wrote:
> What I would expect to happen that all statements within the ooo block 
> may be executed out
> of order. The block itself waits till all statements are returned before 
> continuing.
> 
> What do you think?

The statement is kind of limiting as a unit of uncaring.  What if you have two 
statements that you do want to be executed in order, but still don't care what 
order they are executed in relative to other sets of two statements?  Better 
would be to have a set of blocks that the compiler is free to execute 
asynchronously relative to each other (I'll call it async).

async:
a += 1
f *= a
async:
b += 1
e *= b
async:
c += 1
d *= c


There is utterly no chance of this syntax entering Python.


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


Re: argparse zero-length switch

2011-10-14 Thread Peter Otten
Carl Banks wrote:

> Is it possible to specify a zero-length switch?  Here's what I mean.
> 
> I have a use case where some users would have to enter a section name on
> the command line almost every time, whereas other users (the ones using
> only one section) will never have to enter the section name.  I don't want
> to burden users with only one "section" to always enter the section name
> as a required argument, but I also want to make it as convenient as
> possible to enter the section name for those who need to.
> 
> My thought, on the thinking that practicality beats purity, was to create
> a zero-length switch using a different prefix character (say, @) to
> indicate the section name.  So instead of typing this:
> 
>sp subcommand -s abc foo bar
> 
> they could type this:
> 
>sp subcommand @abc foo bar
> 
> Admittedly a small benefit.  I tried the following but argparse doesn't
> seem to do what I'd hoped:
> 
>p = argparse.ArgumentParser(prefix_chars='-@')
>p.add_argument('@',type=str,dest='section')
>ar = p.parse_args(['@abc'])
> 
> This throws an exception claiming unrecognized arguments.
> 
> Is there a way (that's not a hack) to do this?  Since the current behavior
> of the above code seems to do nothing useful, it could be added to
> argparse with very low risk of backwards incompatibility.

If the number of positional arguments is otherwise fixed you could make 
section a positional argument with nargs="?"

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> _ = parser.add_argument("section", nargs="?")
>>> _ = parser.add_argument("foo")
>>> _ = parser.add_argument("bar")
>>> parser.parse_args(["alpha", "beta"])
Namespace(bar='beta', foo='alpha', section=None)
>>> parser.parse_args(["alpha", "beta", "gamma"])
Namespace(bar='gamma', foo='beta', section='alpha')


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


Graph editor

2011-10-14 Thread Libra
Hi,
I would like to build a simple graph editor, allowing me to add nodes
and edges via the mouse, along with the possibility to edit it (delete/
move nodes and edges, double click on object to pop-up a form where I
can insert object related info, and so forth) and bind edges to nodes
(that is, when I move a node, the attached edges move accordingly). I
should also put an image (a bitmap of png) in the background of the
graph.

I've seen many GUI libraries (from TkInter to wxPython) but I was
wondering if there is a specific graphic library (with good
documentation and maybe examples) simplifying the rapid development of
such an application.

Thanks
Libra

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


Fwd: os.statvfs bug or my incompetence ?

2011-10-14 Thread Peter G. Marczis

  
  
 Hi list,
I'm happy to join to this nice mail list. At my company we use
python to handle system administration tasks.
I found the next problem during my work:

test.py:
# cat test.py 
  #!/usr/bin/python
  
  import os
  os.statvfs('/')

result:
# python -m trace -t test.py 
   --- modulename: threading, funcname: settrace
  threading.py(90): _trace_hook = func
   --- modulename: trace, funcname: 
  (1):   --- modulename: trace, funcname:
  
  test.py(3): import os
  test.py(6): os.statvfs('/')
  Traceback (most recent call last):
    File "/usr/lib64/python2.6/runpy.py", line 122, in
  _run_module_as_main
      "__main__", fname, loader, pkg_name)
    File "/usr/lib64/python2.6/runpy.py", line 34, in _run_code
      exec code in run_globals
    File "/mnt/sysimg/usr/lib64/python2.6/trace.py", line 813, in
  
      main()
    File "/mnt/sysimg/usr/lib64/python2.6/trace.py", line 801, in
  main
      t.run('execfile(%r)' % (progname,))
    File "/mnt/sysimg/usr/lib64/python2.6/trace.py", line 498, in
  run
      exec cmd in dict, dict
    File "", line 1, in 
    File "test.py", line 6, in 
      os.statvfs('/')
  OSError: [Errno 0] Error: '/'

# python --version
Python 2.6.2

# arch
mips64

os.stat works fine.

I would be very happy with any kind of help. I don't have any idea
why this one fails. 
Thanks in advance.
Br,
    Peter.

  

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


Re: argparse zero-length switch

2011-10-14 Thread Ben Finney
Carl Banks  writes:

> I have a use case where some users would have to enter a section name
> on the command line almost every time, whereas other users (the ones
> using only one section) will never have to enter the section name.

Sounds like a typical case where you want an option that takes an
argument, with a default for when the option is not specified. As you
probably know, ‘argparse’ already handles this fine.

> I don't want to burden users with only one "section" to always enter
> the section name as a required argument, but I also want to make it as
> convenient as possible to enter the section name for those who need
> to.

Yes. The latter need only specify the section explicitly, with ‘-s foo’
or whatever.

> My thought, on the thinking that practicality beats purity, was to
> create a zero-length switch using a different prefix character (say,
> @) to indicate the section name. So instead of typing this:
>
>sp subcommand -s abc foo bar

What's wrong with that? That's a normal way to do it, consistent with
other command-line interfaces. Why deviate from that?

> they could type this:
>
>sp subcommand @abc foo bar
>
> Admittedly a small benefit.

I don't see the benefit of that which would be worth teaching that
unconventional command-line syntax.

-- 
 \ “Two paradoxes are better than one; they may even suggest a |
  `\ solution.” —Edward Teller |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Something works in Python but not in cgi.

2011-10-14 Thread atalu...@gmail.com
Hi,
I need to make work a programm on the Web. I make tests like Hello
World and also with GET  and it works good. The problem comes in the
line gas = importPhase("gri30.cti") The computer don´t find the file
"gri30.cti"(this file was not in workspace), then I put it in the same
folder and the program crash.

Knows someone where is the problem???


#!D:\Python25\python.exe
print "Content-Type: text/html\n"
import cgitb; cgitb.enable()
import cgi
from workplace import *

gas = importPhase("gri30.cti")

print "Cantera"

  print ''
  print ''
print ""
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Something works in Python but not in cgi.

2011-10-14 Thread Miki Tebeka
The working directory of the webserver is probably not the one of the script. 
You should specify full path to the file. One way to do it is:

from os.path import dirname, join
filename = join(dirname(__file__), 'gri30.cti')

HTH
--
Miki Tebeka 
http://pythonwise.blogspot.com

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


Re: Fwd: os.statvfs bug or my incompetence ?

2011-10-14 Thread Terry Reedy

On 10/14/2011 4:19 AM, Peter G. Marczis wrote:


import os
os.statvfs('/')

...

os.statvfs('/')
*OSError: [Errno 0] Error: '/'*

# python --version
Python 2.6.2

# arch
mips64

os.stat works fine.


2.6.2 is a few years old. If there is a bug, it might have been fixed by 
2.6.6 released a year ago, or 2.7.2 just a few months ago.


--
Terry Jan Reedy

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


Re: Graph editor

2011-10-14 Thread duncan smith

On 14/10/11 08:45, Libra wrote:

Hi,
I would like to build a simple graph editor, allowing me to add nodes
and edges via the mouse, along with the possibility to edit it (delete/
move nodes and edges, double click on object to pop-up a form where I
can insert object related info, and so forth) and bind edges to nodes
(that is, when I move a node, the attached edges move accordingly). I
should also put an image (a bitmap of png) in the background of the
graph.

I've seen many GUI libraries (from TkInter to wxPython) but I was
wondering if there is a specific graphic library (with good
documentation and maybe examples) simplifying the rapid development of
such an application.



I've used wxPython and ogl 
(http://www.wxpython.org/docs/api/wx.lib.ogl-module.html) for my graph 
editors; in conjunction with graphviz for the layout. There are ogl 
examples in the wxPython demo.


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


RE: Opportunity missed by Python ?

2011-10-14 Thread Prasad, Ramit
>As long as there are tools to translate scripts or source code between the two 
>languages. More new evolved powerful programming  >languages arenot problems 
>at all for experienced programmers.

More often than not, these conversion utilities are a source of terrible code. 
They are good for getting a quick job done, but not for code that has long term 
use.

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 1/2 evaluates to 0

2011-10-14 Thread 88888 dihedral
How about fractions to be  computed in hundreds or even thousands of  digits in 
precision? 
   
OK, just write programs to compute PI and the Euler number in  hundreds or even 
thousands of digits to test various kind of programming languages. 

This is a sophomore  school home work for gifted kids to play with 
programmings. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implement comparison operators for range objects

2011-10-14 Thread Mark Dickinson
On Oct 12, 8:24 pm, Ian Kelly  wrote:
> On Wed, Oct 12, 2011 at 11:51 AM, MRAB  wrote:
> >> Aside:
>
> >> I'm astonished to see that range objects have a count method! What's the
> >> purpose of that? Any value's count will either be 0 or 1, and a more
> >> appropriate test would be `value in range`:
>
> >>  >>> 17 in range(2, 30, 3) # like r.count(17) => 1
> >> True
> >>  >>> 18 in range(2, 30, 3) # like r.count(18) => 0
> >> False
>
> > In Python 2, range returns a list, and lists have a .count method.
> > Could that be the reason?
>
> Python 2 xrange objects do not have a .count method.  Python 3 range
> objects do have a .count method.  The addition is curious, to say the
> least.

See http://bugs.python.org/issue9213

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


Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-14 Thread Steven D'Aprano
Carl Banks wrote:

> On Thursday, October 13, 2011 7:16:37 PM UTC-7, Steven D'Aprano wrote:
>> > What I would expect to happen that all statements within the ooo block
>> > may be executed out
>> > of order. The block itself waits till all statements are returned
>> > before continuing.
>> 
>> Why do you think this needs to be a language statement?
>> 
>> You can have that functionality *right now*, without waiting for a syntax
>> update, by use of the multiprocessing module, or a third party module.
>> 
>> http://docs.python.org/library/multiprocessing.html
>> http://wiki.python.org/moin/ParallelProcessing
>> 
>> There's no need for forcing language changes on everyone, whether they
>> need it or not, for features that can easily be implemented as library
>> code.
> 
> This goes a little beyond a simple threading mechanism, though.

The multiprocessing module is not a simple threading mechanism, and neither
are the libraries listed in the ParallelProcessing page.




-- 
Steven

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


.py and .pyc files in read-only directory

2011-10-14 Thread Terry
I'm having a problem with my iPhone/iPad app, Python Math, a Python
2.7 interpreter. All the Python modules are delivered in what Apple
calls the app bundle. They are in a read-only directory. This means
that Python cannot write .pyc files to that directory. (I get a deny
write error when doing this.) I tried using compileall to precompile
all the modules, but now I get an unlink error because Python
apparently wants to rebuild the .pyc files.

I've considered two solutions:
1) Delete all the .py files, delivering only the .pyc, or
2) Redirecting the .pyc files into a separate, writable directory.

Will solution 1) work? I don't know how to do 2) and the only
reference I can find to that are a withdrawn PEP, 304.

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


Re: Fwd: os.statvfs bug or my incompetence ?

2011-10-14 Thread Paul Rubin
Terry Reedy  writes:
>> os.statvfs('/')
>> *OSError: [Errno 0] Error: '/'*
>>
>> # python --version
>> Python 2.6.2
>
> 2.6.2 is a few years old. If there is a bug, it might have been fixed
> by 2.6.6 released a year ago, or 2.7.2 just a few months ago.

os.statvfs('/') works fine or me on

Python 2.6.2 (r262:71600, Jun  4 2010, 18:28:58) 
[GCC 4.4.3 20100127 (Red Hat 4.4.3-4)] on linux2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-14 Thread Westley Martínez
On Thu, Oct 13, 2011 at 11:56:20PM -0700, Carl Banks wrote:
> On Thursday, October 13, 2011 7:16:37 PM UTC-7, Steven D'Aprano wrote:
> > > What I would expect to happen that all statements within the ooo block
> > > may be executed out
> > > of order. The block itself waits till all statements are returned before
> > > continuing.
> > 
> > Why do you think this needs to be a language statement?
> > 
> > You can have that functionality *right now*, without waiting for a syntax
> > update, by use of the multiprocessing module, or a third party module.
> > 
> > http://docs.python.org/library/multiprocessing.html
> > http://wiki.python.org/moin/ParallelProcessing
> > 
> > There's no need for forcing language changes on everyone, whether they need
> > it or not, for features that can easily be implemented as library code.
> 
> This goes a little beyond a simple threading mechanism, though.  It's more 
> like guidance to the compiler that you don't care what order these are 
> executed in; the compiler is then free to take advantage of this advice 
> however it like.  That could be to spawn threads, but it could also compile 
> instructions to optimize pipelining and cacheing.  The compiler could also 
> ignore it.  But you can see that, fully realized, syntax like that can do 
> much more than can be done with library code.
> 
> Obviously that extra capability is a very long way off for being useful in 
> CPython.
> 
> 

While we're at it, let's throw in the register keyword.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: .py and .pyc files in read-only directory

2011-10-14 Thread Chris Rebert
On Fri, Oct 14, 2011 at 11:04 AM, Terry  wrote:
> I'm having a problem with my iPhone/iPad app, Python Math, a Python
> 2.7 interpreter. All the Python modules are delivered in what Apple
> calls the app bundle. They are in a read-only directory. This means
> that Python cannot write .pyc files to that directory. (I get a deny
> write error when doing this.) I tried using compileall to precompile
> all the modules, but now I get an unlink error because Python
> apparently wants to rebuild the .pyc files.

You can stop Python from trying to write .pyc files by using the
environment variable PYTHONDONTWRITEBYTECODE, the interpreter's -B
command line option, or by setting sys.dont_write_bytecode to True.

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


Re: .py and .pyc files in read-only directory

2011-10-14 Thread Ian Kelly
On Fri, Oct 14, 2011 at 1:31 PM, Chris Rebert  wrote:
> On Fri, Oct 14, 2011 at 11:04 AM, Terry  wrote:
>> I'm having a problem with my iPhone/iPad app, Python Math, a Python
>> 2.7 interpreter. All the Python modules are delivered in what Apple
>> calls the app bundle. They are in a read-only directory. This means
>> that Python cannot write .pyc files to that directory. (I get a deny
>> write error when doing this.) I tried using compileall to precompile
>> all the modules, but now I get an unlink error because Python
>> apparently wants to rebuild the .pyc files.
>
> You can stop Python from trying to write .pyc files by using the
> environment variable PYTHONDONTWRITEBYTECODE, the interpreter's -B
> command line option, or by setting sys.dont_write_bytecode to True.

This won't make Python use the .pyc files provided, though.  It will
just recompile the .py files and then not try to write out the
bytecode.  If you really want to force it to use the .pyc's, then
don't include the .py files.  Note that if you do this, you'll need to
make sure that the version of Python used to compile the .pyc files is
the same minor release as the version used to run them (more
specifically, the two versions must return the same string from
imp.get_magic()).

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


Re: .py and .pyc files in read-only directory

2011-10-14 Thread Terry
Thanks, that's very useful. And it explains why Python Math wants to rewrite 
the .pyc files: imp.get_magic() returns (null) whereas on my Mac where I 
compiled them, get_magic() returns '\x03\xf3\r\n'.

Now I just have to figure out why I'm getting nothing useful from get_magic().

I assume this would have to be fixed to try solution 1), i.e., leaving out the 
.py files and delivering only the .pyc.

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


Re: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows

2011-10-14 Thread Paolo Zaffino
Nobody can help me?



2011/10/12 Paolo Zaffino 

> I wrote a function thaht works on a 3D matrix.
> As first thing I have an array and I want reshape it into a 3D matrix (for
> further manipulations).
> For this reason I wrote in a row:
>
> matrix=matrix.reshape(a, b, c).T
>
> It work fine on GNU/Linux and Mac OS but not on Windows.
> In Windows I get this error:
>
> matrix=matrix.reshape(a, b, c).T
>
> ValueError: total size of new array must be unchanged
>
> Thank you.
>
>
>
>
> 2011/10/11 David Robinow 
>
>> 2011/10/11 Paolo Zaffino :
>> > Nobody can help me?
>>  Nope, not unless you post some code. Your problem description is too
>> vague.
>>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


How to generate error when argument are not supplied and there is no explicit defults (in optparse)?

2011-10-14 Thread Peng Yu
Hi,

The following code doesn't give me error, even I don't specify the
value of filename from the command line arguments. filename gets
'None'. I checked the manual, but I don't see a way to let
OptionParser fail if an argument's value (which has no default
explicitly specified) is not specified. I may miss some thing in the
manual. Could any expert let me know if there is a way to do so?
Thanks!

#!/usr/bin/env python

from optparse import OptionParser

usage = 'usage: %prog [options] arg1 arg2'
parser = OptionParser(usage=usage)
parser.set_defaults(verbose=True)
parser.add_option('-f', '--filename')

#(options, args) = parser.parse_args(['-f', 'file.txt'])
(options, args) = parser.parse_args()

print options.filename



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


RE: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows

2011-10-14 Thread Prasad, Ramit
From: python-list-bounces+ramit.prasad=jpmorgan@python.org 
[mailto:python-list-bounces+ramit.prasad=jpmorgan@python.org] On Behalf Of 
Paolo Zaffino
Sent: Friday, October 14, 2011 3:55 PM
To: python-list@python.org
Subject: Re: [NUMPY] "ValueError: total size of new array must be unchanged" 
just on Windows

Nobody can help me?


2011/10/12 Paolo Zaffino 
I wrote a function thaht works on a 3D matrix.
As first thing I have an array and I want reshape it into a 3D matrix (for 
further manipulations).
For this reason I wrote in a row:

matrix=matrix.reshape(a, b, c).T

It work fine on GNU/Linux and Mac OS but not on Windows.
In Windows I get this error:

matrix=matrix.reshape(a, b, c).T

ValueError: total size of new array must be unchanged
Thank you.



2011/10/11 David Robinow 
2011/10/11 Paolo Zaffino :
> Nobody can help me?
 Nope, not unless you post some code. Your problem description is too vague.
==

You can do this by converting to an array.

>>> mat = numpy.matrix( [[1,2,],[3,4],[5,6],[7,8]] )
>>> numpy.array( mat )
array([[1, 2],
   [3, 4],
   [5, 6],
   [7, 8]])
>>> a = _
>>> numpy.reshape( a, (2,2,2))
array([[[1, 2],
[3, 4]],

   [[5, 6],
[7, 8]]])


Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows

2011-10-14 Thread MRAB

On 14/10/2011 21:55, Paolo Zaffino wrote:

Nobody can help me?


Others have already tried to help you.

What is the shape and size of 'matrix' before, and what are the values
of 'a', 'b' and 'c'?

Print them in the ones which work (GNU/Linux and Mac OS) and the one
which doesn't (Windows). Do they print the same values?

Do not assume that they are the same. Print them to make sure.


2011/10/12 Paolo Zaffino mailto:zaffin...@gmail.com>>

I wrote a function thaht works on a 3D matrix.
As first thing I have an array and I want reshape it into a 3D
matrix (for further manipulations).
For this reason I wrote in a row:

matrix=matrix.reshape(a, b, c).T

It work fine on GNU/Linux and Mac OS but not on Windows.
In Windows I get this error:

matrix=matrix.reshape(a, b, c).T

ValueError: total size of new array must be unchanged

Thank you.

2011/10/11 David Robinow mailto:drobi...@gmail.com>>

2011/10/11 Paolo Zaffino mailto:zaffin...@gmail.com>>:
 > Nobody can help me?
  Nope, not unless you post some code. Your problem description
is too vague.


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


Re-raise different exception with original stack trace

2011-10-14 Thread Prasad, Ramit
Hi all,
Hopefully you guys can help me with my problem.

Basically I have a UI program that can "save" information. The UI passes the 
save to the controller and the controller saves a file and does some post 
processing. If saving the file fails, I want to handle the error differently 
than if the error was in post processing. In both cases the possible exceptions 
are varied and unknown so I cannot pick and choose certain exception. The 
problem with the sample program below is that the stack trace is replaced by 
the re-raise. What would be the best way(s) to get the original stack trace in 
save_from_UI if the exception occurs in post_process? Using Python 2.6 and 
Windows(XP and 7) / Linux.

Def save_from_model():
save() # do not catch exception (could be any exception)
try:
post_process()
except Exception as e: 
#do something
raise CustomException() # "wrap" exception so bar knows to handle it 
differently

def save_from_UI():
try:
foo()
except CustomException() as e:
# How do I get the original stacktrace instead of the reraise?
except Exception as e:
# do something else with this exception


Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
-- 
http://mail.python.org/mailman/listinfo/python-list


Can I search a list for a range of values?

2011-10-14 Thread MrPink
I have a list like so:

a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14]

I would like to get a subset from the list with value between 10 and
20 (inclusive).

b = [10,13,15,14,20]

Is there a way to do this with a list or other data type?

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


Re: Can I search a list for a range of values?

2011-10-14 Thread Chris Angelico
On Sat, Oct 15, 2011 at 9:10 AM, MrPink  wrote:
> I have a list like so:
>
> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14]
>
> I would like to get a subset from the list with value between 10 and
> 20 (inclusive).
>
> b = [10,13,15,14,20]
>
> Is there a way to do this with a list or other data type?

Try a list comprehension:

>>> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14]
>>> [i for i in a if i>=10 if i<=20]
[10, 20, 15, 13, 14]

This preserves order from the original list. I don't know what order
your result list is in, but you can always rejig things after.

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


Re: Can I search a list for a range of values?

2011-10-14 Thread Ian Kelly
On Fri, Oct 14, 2011 at 4:10 PM, MrPink  wrote:
> I have a list like so:
>
> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14]
>
> I would like to get a subset from the list with value between 10 and
> 20 (inclusive).
>
> b = [10,13,15,14,20]
>
> Is there a way to do this with a list or other data type?

Use a list comprehension:

b = [x for x in a if 10 <= x <= 20]

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


Re: Can I search a list for a range of values?

2011-10-14 Thread Tim Chase

On 10/14/11 17:20, Chris Angelico wrote:

Try a list comprehension:


a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14]
[i for i in a if i>=10 if i<=20]

[10, 20, 15, 13, 14]


The double-if is new to me.  I thought it was an error when I 
first saw it, but it seems to be legit syntax (or at least one 
that 2.7 tolerates, intentionally or otherwise...).  I think I'd 
make it clearer with either


  [i for i in a if i>=10 and i<=20]

or even more clearly:

  [i for i in a if 10 <= i <= 20]

-tkc



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


Re: Can I search a list for a range of values?

2011-10-14 Thread Chris Angelico
On Sat, Oct 15, 2011 at 9:30 AM, Tim Chase
 wrote:
> The double-if is new to me.  I thought it was an error when I first saw it,
> but it seems to be legit syntax (or at least one that 2.7 tolerates,
> intentionally or otherwise...).  I think I'd make it clearer with either
>
>

Yeah, it's legal because you can nest fors and ifs in a list comp.
Stylistic difference, I used "if" instead of "and" because there's no
way that it could be a bitwise and. (It's a cross-language safety net
that I sometimes use.) Although the 10<=i<=20 option is definitely
superior to both.

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


Re: Re-raise different exception with original stack trace

2011-10-14 Thread MRAB

On 14/10/2011 22:30, Prasad, Ramit wrote:

Hi all,
Hopefully you guys can help me with my problem.

Basically I have a UI program that can "save" information. The UI passes the 
save to the controller and the controller saves a file and does some post processing. If 
saving the file fails, I want to handle the error differently than if the error was in 
post processing. In both cases the possible exceptions are varied and unknown so I cannot 
pick and choose certain exception. The problem with the sample program below is that the 
stack trace is replaced by the re-raise. What would be the best way(s) to get the 
original stack trace in save_from_UI if the exception occurs in post_process? Using 
Python 2.6 and Windows(XP and 7) / Linux.

Def save_from_model():
 save() # do not catch exception (could be any exception)
 try:
 post_process()
 except Exception as e:
 #do something
 raise CustomException() # "wrap" exception so bar knows to handle it 
differently

def save_from_UI():
 try:
 foo()
 except CustomException() as e:
 # How do I get the original stacktrace instead of the reraise?
 except Exception as e:
 # do something else with this exception


You could save a reference to the exception in the custom exception:

class CustomException(Exception):
def __init__(self, e):
Exception.__init__(self)
self.exc = e

def save_from_model():
save() # do not catch exception (could be any exception)
try:
post_process()
except Exception as e:
#do something
raise CustomException(e)

def save_from_UI():
try:
foo()
except CustomException as e:
# Original exception is e.exc
except Exception as e:
# do something else with this exception
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can I search a list for a range of values?

2011-10-14 Thread Ian Kelly
On Fri, Oct 14, 2011 at 4:48 PM, Chris Angelico  wrote:
> On Sat, Oct 15, 2011 at 9:30 AM, Tim Chase
>  wrote:
>> The double-if is new to me.  I thought it was an error when I first saw it,
>> but it seems to be legit syntax (or at least one that 2.7 tolerates,
>> intentionally or otherwise...).  I think I'd make it clearer with either
>>
>>
>
> Yeah, it's legal because you can nest fors and ifs in a list comp.
> Stylistic difference, I used "if" instead of "and" because there's no
> way that it could be a bitwise and. (It's a cross-language safety net
> that I sometimes use.) Although the 10<=i<=20 option is definitely
> superior to both.

At least in Python, there is no way that "and" could be a bitwise and
either, since it cannot be overloaded.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I search a list for a range of values?

2011-10-14 Thread Ian Kelly
On Fri, Oct 14, 2011 at 4:30 PM, Tim Chase
 wrote:
> On 10/14/11 17:20, Chris Angelico wrote:
>>
>> Try a list comprehension:
>>
> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14]
> [i for i in a if i>=10 if i<=20]
>>
>> [10, 20, 15, 13, 14]
>
> The double-if is new to me.  I thought it was an error when I first saw it,
> but it seems to be legit syntax (or at least one that 2.7 tolerates,
> intentionally or otherwise...).  I think I'd make it clearer with either
>
>  [i for i in a if i>=10 and i<=20]
>
> or even more clearly:
>
>  [i for i in a if 10 <= i <= 20]

As long as we're nitpicking, I'll point out that "i" is an
inappropriate variable name here, since it is normally used to denote
indices, not data.  That's why I used "x" in my response instead. ;-)

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


Re: Can I search a list for a range of values?

2011-10-14 Thread Tim Chase

On 10/14/11 18:01, Ian Kelly wrote:

On Fri, Oct 14, 2011 at 4:30 PM, Tim Chase

or even more clearly:

[i for i in a if 10<= i<= 20]


As long as we're nitpicking, I'll point out that "i" is an
inappropriate variable name here, since it is normally used to
denote indices, not data.  That's why I used "x" in my
response instead. ;-)


Depending on your historical programming-language baggage, "i" is 
usually either an index or integer data, and since the source was 
a list of integers, "i" didn't seem inappropriate.  Same for 
other common data-types:


  [f for f in (1.1, 2.2, 3.3) if 2.0 <= f < 3.0]
  [s for s in ("cat", "hat", "mat") if "bat" < s < "fat"]
  [c for c in "hello, world!" if 'a' <= c <= 'z']

-tkc



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


Re: Can I search a list for a range of values?

2011-10-14 Thread Ian Kelly
On Fri, Oct 14, 2011 at 5:24 PM, Tim Chase
 wrote:
> Depending on your historical programming-language baggage, "i" is usually
> either an index or integer data, and since the source was a list of
> integers, "i" didn't seem inappropriate.  Same for other common data-types:
>
>  [f for f in (1.1, 2.2, 3.3) if 2.0 <= f < 3.0]
>  [s for s in ("cat", "hat", "mat") if "bat" < s < "fat"]
>  [c for c in "hello, world!" if 'a' <= c <= 'z']

"f" makes me think "function", not "float".  As a general rule,
though, I prefer to name variables for what they represent, not for
their type.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I search a list for a range of values?

2011-10-14 Thread Troy S
Can something like this be done with dictionarys?

For example, these are the keys in the dictionary from the call: dict.keys()

['20110601', '20110604', '20110608', '20110611', '20110615',
'20110618', '20110622', '20110625', '20110629', '20110702',
'20110706','20110709', '20110713', '20110716', '20110720', '20110723',
'20110727', '20110730', '20110803', '20110806', '20110810','20110813',
'20110817', '20110820', '20110824', '20110827', '20110831',
'20110903', '20110907', '20110910', '20110914','20110917', '20110921',
'20110924', '20110928', '20111001', '20111005', '20111008']

Is there a way to find all items between '20110809' and '20110911'?
So the subset would be:
['20110810','20110813', '20110817', '20110820', '20110824',
'20110827', '20110831', '20110903', '20110907', '20110910']

The keys are strings that represent a date in the format: 'MMDD'.

Thanks,

On Fri, Oct 14, 2011 at 6:24 PM, Ian Kelly  wrote:
> On Fri, Oct 14, 2011 at 4:10 PM, MrPink  wrote:
>> I have a list like so:
>>
>> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14]
>>
>> I would like to get a subset from the list with value between 10 and
>> 20 (inclusive).
>>
>> b = [10,13,15,14,20]
>>
>> Is there a way to do this with a list or other data type?
>
> Use a list comprehension:
>
> b = [x for x in a if 10 <= x <= 20]
>
> Cheers,
> Ian
>



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


Re: Can I search a list for a range of values?

2011-10-14 Thread Tim Chase

On 10/14/11 18:36, Troy S wrote:

Can something like this be done with dictionarys?

For example, these are the keys in the dictionary from the call: dict.keys()

['20110601', '20110604', '20110608', '20110611', '20110615',
'20110618', '20110622', '20110625', '20110629', '20110702',
'20110706','20110709', '20110713', '20110716', '20110720', '20110723',
'20110727', '20110730', '20110803', '20110806', '20110810','20110813',
'20110817', '20110820', '20110824', '20110827', '20110831',
'20110903', '20110907', '20110910', '20110914','20110917', '20110921',
'20110924', '20110928', '20111001', '20111005', '20111008']

Is there a way to find all items between '20110809' and '20110911'?
So the subset would be:
['20110810','20110813', '20110817', '20110820', '20110824',
'20110827', '20110831', '20110903', '20110907', '20110910']

The keys are strings that represent a date in the format: 'MMDD'.


Since strings are comparable, you certainly can:

  keys = [k for k in d.keys() if '20110809' < k < '20110911']

-tkc



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


Re: Can I search a list for a range of values?

2011-10-14 Thread Ian Kelly
On Fri, Oct 14, 2011 at 5:36 PM, Troy S  wrote:
> Can something like this be done with dictionarys?
>
> For example, these are the keys in the dictionary from the call: dict.keys()
>
> ['20110601', '20110604', '20110608', '20110611', '20110615',
> '20110618', '20110622', '20110625', '20110629', '20110702',
> '20110706','20110709', '20110713', '20110716', '20110720', '20110723',
> '20110727', '20110730', '20110803', '20110806', '20110810','20110813',
> '20110817', '20110820', '20110824', '20110827', '20110831',
> '20110903', '20110907', '20110910', '20110914','20110917', '20110921',
> '20110924', '20110928', '20111001', '20111005', '20111008']
>
> Is there a way to find all items between '20110809' and '20110911'?
> So the subset would be:
> ['20110810','20110813', '20110817', '20110820', '20110824',
> '20110827', '20110831', '20110903', '20110907', '20110910']

Sure, dictionaries also support iteration.

date_range = [d for d in source_dict if '20110809' <= d <= '20110911']

Or if you want the result to also be a dictionary:

(Python 3)
date_range = {d:v for d, v in source_dict.items() if '20110809' <= d
<= '20110911'}

(Python 2)
date_range = dict((d,v) for d, v in source_dict.iteritems() if
'20110809' <= d <= '20110911')

You might also want to consider storing your dates as datetime.date
objects rather than strings, but since you already have them formatted
for lexicographical sorting it's not important for this.

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


Re: Can I search a list for a range of values?

2011-10-14 Thread Chris Angelico
On Sat, Oct 15, 2011 at 9:58 AM, Ian Kelly  wrote:
> At least in Python, there is no way that "and" could be a bitwise and
> either, since it cannot be overloaded.

Like I said, cross-language safety-net. Sure it's not an issue here,
but when I write code in multiple languages, it's less embarrassing to
use an odd construct like that than to post code that outright doesn't
work. :)

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


How to test if object is an integer?

2011-10-14 Thread MrPink

Is there a function in Python that can be used to test if the value in
a string is an integer?  I had to make one up for myself and it looks
like this:

def isInt(s):
try:
i = int(s)
return True
except ValueError:
return False
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if object is an integer?

2011-10-14 Thread Chris Angelico
On Sat, Oct 15, 2011 at 10:44 AM, MrPink  wrote:
> Is there a function in Python that can be used to test if the value in
> a string is an integer?  I had to make one up for myself and it looks
> like this:
>
> def isInt(s):
>    try:
>        i = int(s)
>        return True
>    except ValueError:
>        return False

There's some ambiguity in the definition of "is an integer". For
instance, is "0x100" an integer? Is "0800"? If your definition of "is
an integer" is "can be passed to int() without triggering an
exception" (which is probably the most useful), then your above code
is about perfect. The only change I'd make is to not have an isInt
function at all, but simply to try/except at the point where you need
to make the conversion.

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


Re: Opportunity missed by Python ?

2011-10-14 Thread alex23
On Oct 13, 8:07 pm, Chris Angelico  wrote:
> Python, as I found out to my detriment, is practically impossible to
> sandbox effectively.

The latest version of PyPy introduces a prototype sandbox:

http://pypy.org/features.html#sandboxing

It'll be interesting to see how effective this is.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if object is an integer?

2011-10-14 Thread 惜悯
retrun True if type(i) is int else False
 
 
-- Original --
From:  "Chris Angelico";
Date:  Sat, Oct 15, 2011 08:55 AM
To:  "python-list"; 

Subject:  Re: How to test if object is an integer?

 
On Sat, Oct 15, 2011 at 10:44 AM, MrPink  wrote:
> Is there a function in Python that can be used to test if the value in
> a string is an integer?  I had to make one up for myself and it looks
> like this:
>
> def isInt(s):
>try:
>i = int(s)
>return True
>except ValueError:
>return False

There's some ambiguity in the definition of "is an integer". For
instance, is "0x100" an integer? Is "0800"? If your definition of "is
an integer" is "can be passed to int() without triggering an
exception" (which is probably the most useful), then your above code
is about perfect. The only change I'd make is to not have an isInt
function at all, but simply to try/except at the point where you need
to make the conversion.

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


Re: How to test if object is an integer?

2011-10-14 Thread Chris Angelico
2011/10/15 惜悯 :
> retrun True if type(i) is int else False

That tests if the object is already an int; the OP asked if a string
contains an integer.

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


Re: How to test if object is an integer?

2011-10-14 Thread Chris Rebert
On Fri, Oct 14, 2011 at 6:05 PM, Chris Angelico  wrote:
> 2011/10/15 惜悯 :
>> retrun True if type(i) is int else False
>
> That tests if the object is already an int; the OP asked if a string
> contains an integer.

Additionally:
* the if-then-else there is unnecessary since `type(i) is int` already
returns a bool
* such a type test is normally and better written `isinstance(i, int)`

Cheers,
Chris R.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if object is an integer?

2011-10-14 Thread Terry Reedy

On 10/14/2011 9:05 PM, Chris Angelico wrote:

2011/10/15 惜悯:

retrun True if type(i) is int else False


That tests if the object is already an int; the OP asked if a string
contains an integer.


The misleading subject line did not. It should have been
"How to test if a string contains an integer?"

--
Terry Jan Reedy


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


Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-14 Thread alex23
On Oct 14, 4:56 pm, Carl Banks  wrote:
> But you can see that, fully realized, syntax like that can do much more
> than can be done with library code.

Well sure, but imaginary syntax can do _anything_. That doesn't mean
it's possible within CPython.

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


Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-14 Thread Ben Finney
alex23  writes:

> On Oct 14, 4:56 pm, Carl Banks  wrote:
> > But you can see that, fully realized, syntax like that can do much more
> > than can be done with library code.
>
> Well sure, but imaginary syntax can do _anything_. That doesn't mean
> it's possible within CPython.

+1 QotW

-- 
 \  “The opposite of a correct statement is a false statement. But |
  `\ the opposite of a profound truth may well be another profound |
_o__)  truth.” —Niels Bohr |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if object is an integer?

2011-10-14 Thread Ben Finney
Terry Reedy  writes:

> On 10/14/2011 9:05 PM, Chris Angelico wrote:

> > That tests if the object is already an int; the OP asked if a string
> > contains an integer.
>
> The misleading subject line did not. It should have been "How to test
> if a string contains an integer?"

Which would still be misleading :-)

Even better is “How to test whether a string is a valid representation
of an integer?”

I say that's better because it gets to the relevant point of asking
*which* representations you want to test for – what qualifies as valid
for your particular use case, and what does not. There's no single right
answer; the programmer must choose exactly what they want to test for.

-- 
 \  “When I was a little kid we had a sand box. It was a quicksand |
  `\   box. I was an only child... eventually.” —Steven Wright |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-14 Thread Chris Rebert
On Fri, Oct 14, 2011 at 6:23 PM, alex23  wrote:
> On Oct 14, 4:56 pm, Carl Banks  wrote:
>> But you can see that, fully realized, syntax like that can do much more
>> than can be done with library code.
>
> Well sure, but imaginary syntax can do _anything_. That doesn't mean
> it's possible within CPython.

But it's The Future now! Where are my jetpack and `dwim` statement,
dammit?!  :-)

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


Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-14 Thread alex23
On Oct 13, 10:35 pm, "Martin P. Hellwig" 
wrote:
> def do_something():
>      a = 4
>      b = 2
>      c = 1
>      ooo:
>          a += 1
>          b += 2
>          c += 3
>      print(a, b, c)
>
> What I would expect to happen that all statements within the ooo block
> may be executed out
> of order. The block itself waits till all statements are returned before
> continuing.
>
> What do you think?

You can do this right now with Python 3.2+ and concurrent.futures:

from concurrent.futures import ThreadPoolExecutor
from functools import partial
import time

class DoSomething:
a = 4
b = 2
c = 1

def add(self, prop, val):
cur = getattr(self, prop)
time.sleep(cur)
print('Adding %d to %s' % (val, prop))
setattr(self, prop, cur + val)

def __init__(self):
with ThreadPoolExecutor(max_workers=3) as pool:
pool.submit(self.add, 'a', 1)
pool.submit(self.add, 'b', 2)
pool.submit(self.add, 'c', 3)
print(self.a, self.b, self.c)

DoSomething()

Here we call 'ooo' the ThreadPoolExecutor context manager :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-14 Thread alex23
On Oct 15, 12:32 pm, alex23  wrote:
> from functools import partial

You can ignore this, sorry, leftover from earlier code :)


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


Re: Python library for generating SQL queries [selects, alters, inserts and commits]

2011-10-14 Thread alex23
Tim Chase  wrote:
> I'm not sure it can entirely be chalked up to not looking hard
> enough.

It's explicitly cited in the feature list:

Raw SQL statement mapping
SQLA's object relational query facilities can accommodate raw SQL
statements as well as plain result sets, and object instances can
be generated from these results in the same manner as any other
ORM operation. Any hyper-optimized query that you or your DBA can
cook up, you can run in SQLAlchemy

http://www.sqlalchemy.org/features.html

That it's expression language translates down to pure SQL is also
shown within the first few sections of the tutorial too:

http://www.sqlalchemy.org/docs/core/tutorial.html

I'm not sure how they could make it more obvious.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading a file into a data structure....

2011-10-14 Thread MrPink
This is what I have been able to accomplish:

def isInt(s):
try:
i = int(s)
return True
except ValueError:
return False

f = open("powerball.txt", "r")
lines = f.readlines()
f.close()

dDrawings = {}
for line in lines:
if isInt(line[0]):
t = line.split()
d = t[0]
month,day,year = t[0].split("/")
i = int(year + month + day)
wb = t[1:6]
wb.sort()
pb = t[6]
r = {'d':d,'wb':wb,'pb':pb}
dDrawings[i] = r

The dictionary dDrawings contains records like this:
dDrawings[19971101]
{'pb': '20', 'd': '11/01/1997', 'wb': ['22', '25', '28', '33', '37']}

I am now able to search for ticket in a date range.
keys = dDrawings.keys()
b = [key for key in keys if 20110909 <= key <= 20111212]

How would I search for matching wb (White Balls) in the drawings?

Is there a better way to organize the data so that it will be flexible
enough for different types of searches?
Search by date range, search by pb, search by wb matches, etc.

I hope this all makes sense.

Thanks,

On Oct 13, 7:42 pm, Jon Clements  wrote:
> On Oct 13, 10:59 pm,MrPink wrote:
>
>
>
>
>
>
>
>
>
> > This is a continuing to a post I made in 
> > August:http://groups.google.com/group/comp.lang.python/browse_thread/thread/...
>
> > I got some free time to work with Python again and have some followup
> > questions.
>
> > For example, I have a list in a text file like this:
> > Example list of lottery drawings:
> > date,wb,wb,wb,wb,wb,bb
> > 4/1/2011,5,1,45,23,27,27
> > 5/1/2011,15,23,8,48,22,32
> > 6/1/2011,33,49,21,16,34,1
> > 7/1/2011,9,3,13,22,45,41
> > 8/1/2011,54,1,24,39,35,18
> > 
>
> > Ticket:
> > startdate,enddate,wb,wb,wb,wb,wb,bb
> > 4/1/2011,8/1/2011,5,23,32,21,3,27
>
> > I am trying to determine the optimal way to organize the data
> > structure of the drawing list, search the drawing list, and mark the
> > matches in the drawing list.
>
> > f = open("C:\temp\drawinglist.txt", "r")
> > lines = f.readlines()
> > f.close()
> > drawing = lines[1].split()
>
> > The results in drawing is this:
> > drawing[0] = '4/1/2011'
> > drawing[1] = '5'
> > drawing[2] = '1'
> > drawing[3] = '45'
> > drawing[4] = '23'
> > drawing[5] = '27'
> > drawing[6] = '27'
>
> > I need to convert drawing[0] to a date datatype.  This works, but I'm
> > sure there is a better way.
> > from datetime import date
> > month, day, year = drawing[0].split('/')
> > drawing[0] = date(int(year), int(month), int(day))
>
> > For searching, I need to determine if the date of the drawing is
> > within the date range of the ticket.  If yes, then mark which numbers
> > in the drawing match the numbers in the ticket.
>
> > ticket[0] = '4/1/2011'
> > ticket[0] = '8/1/2011'
> > ticket[0] = '5'
> > ticket[0] = '23'
> > ticket[0] = '32'
> > ticket[0] = '21'
> > ticket[0] = '3'
> > ticket[0] = 27'
>
> > drawing[0] = '4/1/2011' (match)
> > drawing[1] = '5' (match)
> > drawing[2] = '1'
> > drawing[3] = '45'
> > drawing[4] = '23' (match)
> > drawing[5] = '27'
> > drawing[6] = '27' (match)
>
> > I'm debating on structuring the drawing list like this:
> > drawing[0] = '4/1/2011'
> > drawing[1][0] = '5'
> > drawing[1][1] = '1'
> > drawing[1][2] = '45'
> > drawing[1][3] = '23'
> > drawing[1][4] = '27'
> > drawing[2] = '27'
>
> > Sort drawing[1] from low to high
> > drawing[1][0] = '1'
> > drawing[1][1] = '5'
> > drawing[1][2] = '23'
> > drawing[1][3] = '27'
> > drawing[1][4] = '45'
>
> > I want to keep the drawing list in memory for reuse.
>
> > Any guidance would be most helpful and appreciated.
> > BTW, I want to learn, so be careful not to do too much of the work for
> > me.
> > I'm using WingIDE to do my work.
>
> > Thanks,
>
> - Use the csv module to read the file
> - Use strptime to process the date field
> - Use a set for draw numbers (you'd have to do pure equality on the
> bb)
> - Look at persisting in a sqlite3 DB (maybe with a custom convertor)
>
> hth,
>
> Jon.

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


Re: Language Enhancement Idea to help with multi-processing (your opinions please)

2011-10-14 Thread Chris Angelico
On Sat, Oct 15, 2011 at 1:15 PM, Chris Rebert  wrote:
> On Fri, Oct 14, 2011 at 6:23 PM, alex23  wrote:
>> Well sure, but imaginary syntax can do _anything_. That doesn't mean
>> it's possible within CPython.
>
> But it's The Future now! Where are my jetpack and `dwim` statement,
> dammit?!  :-)

If you can imagine something your language can't do, you're not using
enough preprocessors.

ChrisA
who, frustrated by Java about ten years ago, started running his .java
files through the C preprocessor... and it can get a lot worse than
that
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reading a file into a data structure....

2011-10-14 Thread Chris Angelico
On Sat, Oct 15, 2011 at 1:59 PM, MrPink  wrote:
> def isInt(s):
>    try:
>        i = int(s)
>        return True
>    except ValueError:
>        return False
>
> f = open("powerball.txt", "r")
> lines = f.readlines()
> f.close()
>
> dDrawings = {}
> for line in lines:
>    if isInt(line[0]):
>        t = line.split()
>        d = t[0]
>        month,day,year = t[0].split("/")
>        i = int(year + month + day)
>        wb = t[1:6]
>        wb.sort()
>        pb = t[6]
>        r = {'d':d,'wb':wb,'pb':pb}
>        dDrawings[i] = r
>

Here's a quick rejig:

dDrawings = {}
for line in open("powerball.txt"):
   try:
   t = line.split()
   d = t[0]
   month,day,year = t[0].split("/")
   i = int(year + month + day)
   wb = t[1:6]
   wb.sort()
   pb = t[6]
   r = {'d':d,'wb':wb,'pb':pb}
   dDrawings[i] = r
   except ValueError:
   pass

There are two significant differences. One is that the file is kept
open until processing is complete, rather than reading the file into a
list and then iterating over the list. Your processing is pretty
simple, so it's unlikely to make a difference, but if you're doing a
lengthy operation on the lines of text, or conversely if you're
reading in gigs and gigs of file, you may want to take that into
consideration. The other change is that a ValueError _anywhere_ in
processing will cause the line to be silently ignored. If this isn't
what you want, then shorten the try/except block and make it use
'continue' instead of 'pass' (which will then silently ignore that
line, but leave the rest of processing unguarded by try/except).

The most likely cause of another ValueError is this line:
   month,day,year = t[0].split("/")
If there are not precisely two slashes, this will:

>>> a,b,c="asdf/qwer".split("/")
Traceback (most recent call last):
  File "", line 1, in 
a,b,c="asdf/qwer".split("/")
ValueError: need more than 2 values to unpack

Do you want this to cause the line to be ignored, or to noisily abort
the whole script?

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


Re: Reading a file into a data structure....

2011-10-14 Thread Chris Rebert
On Fri, Oct 14, 2011 at 7:59 PM, MrPink  wrote:
> This is what I have been able to accomplish:
>
> def isInt(s):
>    try:
>        i = int(s)
>        return True
>    except ValueError:
>        return False
>
> f = open("powerball.txt", "r")
> lines = f.readlines()
> f.close()
>
> dDrawings = {}
> for line in lines:
>    if isInt(line[0]):
>        t = line.split()
>        d = t[0]
>        month,day,year = t[0].split("/")
>        i = int(year + month + day)
>        wb = t[1:6]
>        wb.sort()
>        pb = t[6]
>        r = {'d':d,'wb':wb,'pb':pb}
>        dDrawings[i] = r
>
> The dictionary dDrawings contains records like this:
> dDrawings[19971101]
> {'pb': '20', 'd': '11/01/1997', 'wb': ['22', '25', '28', '33', '37']}
>
> I am now able to search for ticket in a date range.
> keys = dDrawings.keys()
> b = [key for key in keys if 20110909 <= key <= 20111212]
>
> How would I search for matching wb (White Balls) in the drawings?
>
> Is there a better way to organize the data so that it will be flexible
> enough for different types of searches?
> Search by date range, search by pb, search by wb matches, etc.
>
> I hope this all makes sense.

from datetime import datetime
from collections import namedtuple, defaultdict
# for efficient searching by date: import bisect

DATE_FORMAT = "%m/%d/%Y"
Ticket = namedtuple('Ticket', "white_balls powerball date".split())

powerball2ticket = defaultdict(set)
whiteball2ticket = defaultdict(set)
tickets_by_date = []

with open("powerball.txt", "r") as f:
for line in f:
if not line[0].isdigit():
# what are these other lines anyway?
continue # skip such lines

fields = line.split()

date = datetime.strptime(fields[0], DATE_FORMAT).date()
white_balls = frozenset(int(num_str) for num_str in fields[1:6])
powerball = int(fields[6])
ticket = Ticket(white_balls, powerball, date)

powerball2ticket[powerball].add(ticket)
for ball in white_balls:
whiteball2ticket[ball].add(ticket)
tickets_by_date.append(ticket)

tickets_by_date.sort(key=lambda ticket: ticket.date)

print(powerball2ticket[7]) # all tickets with a 7 powerball
print(whiteball2ticket[3]) # all tickets with a non-power 3 ball


Cheers,
Chris
--
http://rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to generate error when argument are not supplied and there is no explicit defults (in optparse)?

2011-10-14 Thread Miki Tebeka
Don't specify it as an option, but as an argument.
If you're on a new version of python, you should probably use argparse.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to test if object is an integer?

2011-10-14 Thread Terry Reedy

On 10/14/2011 9:51 PM, Ben Finney wrote:

Terry Reedy  writes:


On 10/14/2011 9:05 PM, Chris Angelico wrote:



That tests if the object is already an int; the OP asked if a string
contains an integer.


The misleading subject line did not. It should have been "How to test
if a string contains an integer?"



Which would still be misleading :-)

Even better is “How to test whether a string is a valid representation
of an integer?”


I agree, but that is more than I would ask of a newbie, whereas asking 
people to ask the same question in subject line and text, even if the 
question is inadequate, is reasonable.



I say that's better because it gets to the relevant point of asking
*which* representations you want to test for – what qualifies as valid
for your particular use case, and what does not. There's no single right
answer; the programmer must choose exactly what they want to test for.


Yes. Even the wrong subject line question is ambiguous, as any of int, 
bool, float, complex, decimal.Decimal, and fractions.Fraction can have 
an integer value, as might user class instances, and, of course, 
depending on context, bytes and strings.


--
Terry Jan Reedy


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


Re: Can I search a list for a range of values?

2011-10-14 Thread Westley Martínez
On Fri, Oct 14, 2011 at 05:01:04PM -0600, Ian Kelly wrote:
> On Fri, Oct 14, 2011 at 4:30 PM, Tim Chase
>  wrote:
> > On 10/14/11 17:20, Chris Angelico wrote:
> >>
> >> Try a list comprehension:
> >>
> > a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14]
> > [i for i in a if i>=10 if i<=20]
> >>
> >> [10, 20, 15, 13, 14]
> >
> > The double-if is new to me.  I thought it was an error when I first saw it,
> > but it seems to be legit syntax (or at least one that 2.7 tolerates,
> > intentionally or otherwise...).  I think I'd make it clearer with either
> >
> >  [i for i in a if i>=10 and i<=20]
> >
> > or even more clearly:
> >
> >  [i for i in a if 10 <= i <= 20]
> 
> As long as we're nitpicking, I'll point out that "i" is an
> inappropriate variable name here, since it is normally used to denote
> indices, not data.  That's why I used "x" in my response instead. ;-)
> 

O that's what i stands for.  I always thought it was integer o_O
-- 
http://mail.python.org/mailman/listinfo/python-list


I am a newbie for python and try to understand class Inheritance.

2011-10-14 Thread aaabbb16
Test.py
#!/usr/bin/python
from my_lib import my_function
class my_class(my_function.name):
def __initial__(self, name);
 pass
def test():
   print "this is a test"

If __name__ == '__maim__':
my_class.main()
---
my_lib.py
class my_function()
...


Can anyone finish above code and let me try to understand
Class inheritance?
TIA.
-david

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