[ANN] RedNotebook 0.9.1

2010-01-06 Thread Jendrik Seipp

Version 0.9.1 of RedNotebook has just been released.

You can get it at http://rednotebook.sourceforge.net


What is RedNotebook?

RedNotebook is a graphical diary and journal helping you keep track of
notes and thoughts. It includes a calendar navigation, customizable
templates, export functionality and word clouds. You can also format,
tag and search your entries. Packages are available for common Linux 
distributions and Windows.



What's new?
---
* Markup highlighting is now much faster
* Webkit can now be used for previews (in the config file, set useWebkit
  to 1).
* Make welcome text translatable
* Add comments for translators
* Make help available online


Cheers,
Jendrik



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

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


cx_Freeze 4.1.2

2010-01-06 Thread Anthony Tuininga
What is cx_Freeze?

cx_Freeze is a set of scripts and modules for freezing Python scripts
into executables in much the same way that py2exe and py2app do. It
requires Python 2.3 or higher since it makes use of the zip import
facility which was introduced in that version.


Where do I get it?

http://cx-freeze.sourceforge.net


What's new?

Changes from 4.1.1 to 4.1.2

1) Fix bug that caused the util extension to be named improperly.

2) Fix bug that prevented freezing from taking place if a packaged
submodule was missing.

3) Fix bug that prevented freezing from taking place in Python 3.x if
the encoding of the source file wasn't compatible with the encoding of
the terminal performing the freeze.

4) Fix bug that caused the base modules to be included in the
library.zip as well as the base executables.
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

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


Galway Python Meetup - Wed, Feb 3rd, 2010 - 19:00

2010-01-06 Thread Vicky Lee
Hi All,

When - Wed Feb 3rd 2010, 19:00
Where - Westwood Bar, Westwood House Hotel, Dangan, Newcastle, Galway
Contact - Michael Kerrin

Details up at
http://www.python.ie/meetup/2010/galway_python_meetup_-_feb_2010/

Thanks again to Michael for arranging this event. Here's hoping for more
Python meetups outside of Dublin. ;)

Cheers,

/// Vicky

~~
~~ http://irishbornchinese.com   ~~
~~   http://www.python.ie   ~~
~~
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

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


Re: Object Relational Mappers are evil (a meditation)

2010-01-06 Thread Ethan Furman

J Kenneth King wrote:


In many contexts I'm sure there is reason to use Perl instead of Python
just as there are situations where C is more appropriate than either.

However, the mark of a poor programmer in my line of reasoning is one
who cannot recognize such distinctions.

One must be aware of the benefits and short-comings of their tools.  If
your tools influence the way you think then you are being ignorant of
this principle.  And I would suggest that makes you a poor programmer.


Perhaps influence the way you think is not the right way to phrase 
it... how about be the tool  ;)


We have all seen the struggles that newcomers to a language go through 
as they try (or don't try) to adjust their thinking to the tool at hand 
-- programming Java, BASIC, FORTRAN, or xyz in Python.  Even now Phlip 
is raging against exceptions and the very Zen of Python.


Converting FoxPro to Python is an interesting excercise for me -- 
version 6 at least doesn't have many of the cool things that Python 
does, and consequently thinking in Python while writing FoxPro (when I 
have to) is extremely frustrating; going the other way is a bit of a 
challenge also, although much more rewarding.


For a more concrete example, take sail-boats and speed-boats:  you get 
used to the speed boat, it's quick handling and sharp turns... then you 
take a sail boat out for a cruise -- if you don't adjust your thinking 
from speed to sail, you could very well end up in the rocks.


To sum up:  I agree with your poor programmer line of reasoning in the 
second paragraph above, but not with the tools influencing the way we 
think line of reasoning -- while I am cognizant of Python's 
shortcomings, I am very much enjoying the changes in my thinking the 
more I use it.


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


RE: lxml 2.2.4 on python3.1, Windows XP gives importerror

2010-01-06 Thread VYAS ASHISH M-NTB837
Posting again as I did not get any response:

Dear All
 
I have Python 3.1 installed on Windows XP and Works nice.
I downloaded lxml 2.2.4 (lxml-2.2.4.win32-py3.1.exe) from pypi.
 
 
When I try:
from lxml import etree
I get:
ImportError: DLL load failed: This application has failed to start
because the application configuration is incorrect. Reinstalling the
application may fix this problem.
 
For information: 'import lxml' works fine.
 
After reinstalling python3.1 also the error message is the same. Any
help is appreciated!
 
 
Regards,
Ashish Vyas
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unittest inconsistent

2010-01-06 Thread Peter Otten
André wrote:

 On Jan 5, 8:14 pm, Matt Haggard haggar...@gmail.com wrote:
 Can anyone tell me why this test fails?

 http://pastebin.com/f20039b17

 This is a minimal example of a much more complex thing I'm trying to
 do.  I'm trying to hijack a function and inspect the args passed to it
 by another function.

 The reason the 'Tester' object has no attribute 'arg1' is because
 self still refers to the object made for testA.
 
 Quick answer: change faketest.py as follows:
 
 #--
 # faketest.py
 #--
 
 #from importme import render
 import importme
 
 def run(somearg):
 return importme.render(somearg)
 
 =
 A long answer, with explanation, will cost you twice as much ;-)
 (but will have to wait)
 
 André

Or you figure it out yourself staring at

 import os
 from os import rename
 os.rename = 42
 rename
built-in function rename
 os.rename
42

from module import name

binds the object referred to by module.name to the name variable in the 
current module. You can think of it as a shortcut for

import module
name = module.name
del module

When you later rebind

import module
module.name = something_else

the reference in the current module isn't magically updated to point to 
something_else.

Peter

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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Ben Finney
r0g aioe@technicalbloke.com writes:

 NO! It's a rude way to start a sentence don't you think?

Shouting is usually rude, yes.

 Just because you're correcting someone doesn't mean you have to be
 combative and try and make them feel small.

Again, you're reading something that isn't there. I utterly deny the
motives you're imputing.

 I can't imagine why I expect good manners on usenet though, AFAICT
 it's never been like that (well not since I got on it anyway).

I'll reiterate that you can address this by paying more attention to
what is actually written, and endeavouring to avoid finding emotions or
motives that are likely not in the message.

-- 
 \“The greatest tragedy in mankind's entire history may be the |
  `\   hijacking of morality by religion.” —Arthur C. Clarke, 1991 |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: chown'ing by script

2010-01-06 Thread Victor Subervi
On Wed, Jan 6, 2010 at 2:12 AM, alex23 wuwe...@gmail.com wrote:

 Carsten Haese carsten.ha...@gmail.com wrote:
  What is the underlying problem you're trying to solve with this
  approach?

 To be paid for developing a web site shopping cart without actually
 having to learn Python.


LOL! I've written about 12,000 lines of code in this, BTW. Crawl back into
your cave :)
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Need help to pass self.count to other classes.

2010-01-06 Thread Bill
After a year with Python 2.5 on my Windows box, I still have trouble
understanding classes.

Below, see the batch file and the configuration script for
my Python interactive prompt.

The widths of the secondary prompts increase when  the self.count of
SysPrompt1 exceeds 99.

I am using a global variable zxc to share self.count, which is not
Pythonic.

How can I pass in self.count without a global?
I did RTFM, aka Google, but to no avail.

echo py.bat
set PYTHONSTARTUP=c:\scripts\startup.py
python
^Z

# startup.py
# inspired by:
# http://www.doughellmann.com/PyMOTW/sys/interpreter.html

import sys

class SysPrompt1(object):
def __init__(self):
self.count = 0
def __str__(self):
self.count += 1
global zxc
zxc = self.count
return '[%2d] ' % self.count

class SysPrompt2(object):
def __str__(self):
global zxc
if zxc  99: return '.. '
else: return '. '

class DisplayHook(object):
def __call__(self, value):
if value is None: return
global zxc
if zxc  99: print '[ out]', value, '\n'
else: print '[out]', value, '\n'

class ExceptHook(object):
def __call__(self, type, value, trace):
global zxc
if zxc  99: print '[ err]', value, '\n'
else: print '[err]', value, '\n'

sys.ps1 = SysPrompt1()
sys.ps2 = SysPrompt2()
sys.displayhook = DisplayHook()
sys.excepthook = ExceptHook()

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


Re: Need help to pass self.count to other classes.

2010-01-06 Thread Francesco Bochicchio
On 6 Gen, 11:11, Bill bsag...@gmail.com wrote:
 After a year with Python 2.5 on my Windows box, I still have trouble
 understanding classes.

 Below, see the batch file and the configuration script for
 my Python interactive prompt.

 The widths of the secondary prompts increase when  the self.count of
 SysPrompt1 exceeds 99.

 I am using a global variable zxc to share self.count, which is not
 Pythonic.

 How can I pass in self.count without a global?
 I did RTFM, aka Google, but to no avail.

 echo py.bat
 set PYTHONSTARTUP=c:\scripts\startup.py
 python
 ^Z

 # startup.py
 # inspired by:
 #http://www.doughellmann.com/PyMOTW/sys/interpreter.html

 import sys

 class SysPrompt1(object):
     def __init__(self):
         self.count = 0
     def __str__(self):
         self.count += 1
         global zxc
         zxc = self.count
         return '[%2d] ' % self.count

 class SysPrompt2(object):
     def __str__(self):
         global zxc
         if zxc  99: return '.. '
         else: return '. '

 class DisplayHook(object):
     def __call__(self, value):
         if value is None: return
         global zxc
         if zxc  99: print '[ out]', value, '\n'
         else: print '[out]', value, '\n'

 class ExceptHook(object):
     def __call__(self, type, value, trace):
         global zxc
         if zxc  99: print '[ err]', value, '\n'
         else: print '[err]', value, '\n'

 sys.ps1 = SysPrompt1()
 sys.ps2 = SysPrompt2()
 sys.displayhook = DisplayHook()
 sys.excepthook = ExceptHook()

First of all, you shouldn't do OOP if you don't feel it. Python,
unlike Java and like C++, supports also procedural programming, so you
can write your scripts without writing classes (but still using
objects, since all in python is an object).
If you have classes with no data and a single __call_ method, then
they are no classes, they are functions (or methods) in disguise.
So, one solution could be to use plain functions and use global as you
already do. 'global' is pythonic if you are not doing OOP, although I
don't like it.

If you want to stick to OOP, then I suggest to have a make
display_hook and except_hook methods of your class SysPrompt1; This
way all your code can access to self.count without needing globals.
As for  your class SysPrompt2,  I don't understand enough your code to
know what you are trying to do. maybe make it a sunclass of
SysPrompt1 ?

HTH

Ciao

FB

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


Convert month name to month number faster

2010-01-06 Thread wiso
I'm optimizing the inner most loop of my script. I need to convert month 
name to month number. I'm using python 2.6 on linux x64.


month_dict = {Jan:1,Feb:2,Mar:3,Apr:4, May:5, Jun:6,
   Jul:7,Aug:8,Sep:9,Oct:10,Nov:11,Dec:12}

def to_dict(name):
  return month_dict[name]

def to_if(name):
if name == Jan: return 1
elif name == Feb: return 2
elif name == Mar: return 3
elif name == Apr: return 4
elif name == May: return 5
elif name == Jun: return 6
elif name == Jul: return 7
elif name == Aug: return 8
elif name == Sep: return 9
elif name == Oct: return 10
elif name == Nov: return 11
elif name == Dec: return 12
else: raise ValueError

import random
l = [random.choice(month_dict.keys()) for _ in range(100)]

from time import time
t = time(); xxx=map(to_dict,l); print time() - t # 0.5
t = time(); xxx=map(to_if,l); print time() - t   # 1.0


is there a faster solution? Maybe something with str.translate?

The problem is a little different because I don't read random data, but 
sorted data. For example:

l = [x for x in 
(Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec) 
for _ in range(1000)] # [Jan,Jan, ..., Feb, Feb, ...]

so maybe the to_if approach will be faster if I write the case in the best 
order. Look:

l = [Jan] * 100 # to_if is in the best order for Jan
t = time(); xxx=map(to_dict,l); print time() - t # 0.5
t = time(); xxx=map(to_if,l); print time() - t # 0.5


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


RE: Convert month name to month number faster

2010-01-06 Thread VYAS ASHISH M-NTB837
 
How about using list.index() and storing month names in a list? You may
want to measure performance your self and conclude.

Regards,
Ashish Vyas

-Original Message-
From: python-list-bounces+ntb837=motorola@python.org
[mailto:python-list-bounces+ntb837=motorola@python.org] On Behalf Of
wiso
Sent: Wednesday, January 06, 2010 4:34 PM
To: python-list@python.org
Subject: Convert month name to month number faster

I'm optimizing the inner most loop of my script. I need to convert month
name to month number. I'm using python 2.6 on linux x64.


month_dict = {Jan:1,Feb:2,Mar:3,Apr:4, May:5, Jun:6,
   Jul:7,Aug:8,Sep:9,Oct:10,Nov:11,Dec:12}

def to_dict(name):
  return month_dict[name]

def to_if(name):
if name == Jan: return 1
elif name == Feb: return 2
elif name == Mar: return 3
elif name == Apr: return 4
elif name == May: return 5
elif name == Jun: return 6
elif name == Jul: return 7
elif name == Aug: return 8
elif name == Sep: return 9
elif name == Oct: return 10
elif name == Nov: return 11
elif name == Dec: return 12
else: raise ValueError

import random
l = [random.choice(month_dict.keys()) for _ in range(100)]

from time import time
t = time(); xxx=map(to_dict,l); print time() - t # 0.5
t = time(); xxx=map(to_if,l); print time() - t   # 1.0


is there a faster solution? Maybe something with str.translate?

The problem is a little different because I don't read random data, but 
sorted data. For example:

l = [x for x in 
(Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
) 
for _ in range(1000)] # [Jan,Jan, ..., Feb, Feb, ...]

so maybe the to_if approach will be faster if I write the case in the
best 
order. Look:

l = [Jan] * 100 # to_if is in the best order for Jan
t = time(); xxx=map(to_dict,l); print time() - t # 0.5
t = time(); xxx=map(to_if,l); print time() - t # 0.5


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


Re: Convert month name to month number faster

2010-01-06 Thread Antoine Pitrou
Le Wed, 06 Jan 2010 12:03:36 +0100, wiso a écrit :


 from time import time
 t = time(); xxx=map(to_dict,l); print time() - t # 0.5 t = time();
 xxx=map(to_if,l); print time() - t   # 1.0

Don't define your own function just for attribute access. Instead just 
write:

xxx = map(month_dict.__getitem__, l)


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


[no subject]

2010-01-06 Thread Krzysztof Kobus
Hi,


 Well, it seems that one of your files is a different architecture than
 the others. Based on the location, I'd say it's i386 while the rest of
 it would be PowerPC. You can cross-compile but you can't link an i386
 library to a PowerPC library.
Thank you for the hint. I have checked with file command the format of the 
libraries on mac and got following result:

one of my application's libraries:
libkkbase.dylib: Mach-O dynamically linked shared library i386

my python module that has been built using standard python distutils:
j3k.so: Mach-O bundle i386

I am not actually sure what's the difference between bundle and dynamically 
linked shared library on mac and if they can be linked together? Perhaps I 
should configure distutils on mac somehow specially to make the module ready 
for embedding?

Thanks,

KK


On Tue, Jan 5, 2010 at 7:33 AM, Krzysztof Kobus kk720...@yahoo.com wrote:
 Hi,


I have a problem with linking python module with my application on mac
in order to make the module available in embedded python.

 My python module is contained in  j3kmodule.cxx file and module 
 initialization function is exported in j3kmodule.h

 j3kmodule.h:
 
 PyMODINIT_FUNC PyInit_j3k(void);


 j3kmodule.cxx:
 --
 PyMODINIT_FUNC
 PyInit_j3k(void)
  {
  PyObject *m = NULL;

  if ((m = PyModule_Create(j3k_module)) == NULL)
return NULL;

  return m;
  }


 Then in my application in KkPython.cxx file I have:

 KkPython.cxx:
 -

 #include j3kmodule.h

 /* Add a builtin module, before Py_Initialize */
 PyImport_AppendInittab(j3k, PyInit_j3k);



I link my application with the module and get following linking error
on mac although on open suse linux exactly the same procedure works
fine:

 g++ -headerpad_max_install_names -o
../../bin/render.app/Contents/MacOS/render main.o KkPython.o -lkkbase
-L/Users/kk/dev/J3K/trunk/j3ksrc/examples/render/../../lib/
-lQtSolutions_PropertyBrowser-2.5 -lpython3.1
/Users/kk/dev/J3K/trunk/j3ksrc/python/modules/build/lib.macosx-10.3-i386-3.1/j3k.so
-framework OpenGL -framework AGL
 ld: warning in
/Users/kk/dev/J3K/trunk/j3ksrc/python/modules/build/lib.macosx-10.3-i386-3.1/j3k.so,
file is not of required architecture
 Undefined symbols:
  _PyInit_j3k, referenced from:
  _PyInit_j3k$non_lazy_ptr in KkPython.o
 ld: symbol(s) not found
 collect2: ld returned 1 exit status
 make: *** [../../bin/render.app/Contents/MacOS/render] Error 1


 I appreciate any hints,

 best greetings,

 Krzysztof Kobus



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


how to change when the logging module creates the log file?

2010-01-06 Thread Chris Colbert
I have an application the writes to a log file when specific exceptions are
handled. However, if no exceptions are encountered, I don't want to create a
log at all.

The problem I am running into is that the stdlib logging module creates the
log file immediately upon logger instantiation.

Thus:
 logger = logging.basicConifg('testlog.txt')

already creates the file 'testlog.txt'.

So, at program close, I am reading the size of the log file, and if it is
empty I remove it with os.remove(). This works fine on Linux, but throws a
permission denied exception on Windows.

There has to be a better way to do this than using a hack like that. Is
there a way to make the logging module hold-off on file creation until the
first log is generated? I could do it by wrapping logger in a class, but
that would remove the beauty of having any module import logging from the
stdlib and being able to write to the log.

Thanks for any pointers!

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


Re: embedded python on mac - linking problem

2010-01-06 Thread Krzysztof Kobus
Hi,

 
  Well, it seems that one of your files is a different architecture than
  the others. Based on the location, I'd say it's i386 while the rest of
  it would be PowerPC. You can cross-compile but you can't link an i386
  library to a PowerPC library.

Thank you for the hint. I have checked with file command the format of the 
libraries on mac and got following result:

one of my application's libraries:
libkkbase.dylib: Mach-O dynamically linked shared library i386

my python module that has been built using standard python distutils:
j3k.so: Mach-O bundle i386

I am not actually sure what's the difference between bundle and dynamically 
linked shared library on mac and if they can be linked together? Perhaps I 
should configure distutils on mac somehow specially to make the module ready 
for 
embedding?

Thanks,

KK


 On Tue, Jan 5, 2010 at 7:33 AM, Krzysztof Kobus wrote:
  Hi,
 
 
 I have a problem with linking python module with my application on mac
 in order to make the module available in embedded python.
 
  My python module is contained in  j3kmodule.cxx file and module 
  initialization 
 function is exported in j3kmodule.h
 
  j3kmodule.h:
  
  PyMODINIT_FUNC PyInit_j3k(void);
 
 
  j3kmodule.cxx:
  --
  PyMODINIT_FUNC
  PyInit_j3k(void)
   {
   PyObject *m = NULL;
 
   if ((m = PyModule_Create(j3k_module)) == NULL)
 return NULL;
 
   return m;
   }
 
 
  Then in my application in KkPython.cxx file I have:
 
  KkPython.cxx:
  -
 
  #include j3kmodule.h
 
  /* Add a builtin module, before Py_Initialize */
  PyImport_AppendInittab(j3k, PyInit_j3k);
 
 
 
 I link my application with the module and get following linking error
 on mac although on open suse linux exactly the same procedure works
 fine:
 
  g++ -headerpad_max_install_names -o
 ../../bin/render.app/Contents/MacOS/render main.o KkPython.o -lkkbase
 -L/Users/kk/dev/J3K/trunk/j3ksrc/examples/render/../../lib/
 -lQtSolutions_PropertyBrowser-2.5 -lpython3.1
 /Users/kk/dev/J3K/trunk/j3ksrc/python/modules/build/lib.macosx-10.3-i386-3.1/j3k.so
 -framework OpenGL -framework AGL
  ld: warning in
 /Users/kk/dev/J3K/trunk/j3ksrc/python/modules/build/lib.macosx-10.3-i386-3.1/j3k.so,
 file is not of required architecture
  Undefined symbols:
   _PyInit_j3k, referenced from:
   _PyInit_j3k$non_lazy_ptr in KkPython.o
  ld: symbol(s) not found
  collect2: ld returned 1 exit status
  make: *** [../../bin/render.app/Contents/MacOS/render] Error 1
 
 
  I appreciate any hints,
 
  best greetings,
 
  Krzysztof Kobus
 



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


Re: Convert month name to month number faster

2010-01-06 Thread alex23
On Jan 6, 9:03 pm, wiso gtu2...@alice.it wrote:
 I'm optimizing the inner most loop of my script. I need to convert month
 name to month number. I'm using python 2.6 on linux x64.

 month_dict = {Jan:1,Feb:2,Mar:3,Apr:4, May:5, Jun:6,
            Jul:7,Aug:8,Sep:9,Oct:10,Nov:11,Dec:12}

 def to_dict(name):
   return month_dict[name]

Try replacing the to_dict function with:

   to_dict = month_dict.get

That removes one extra function call per lookup. On my computer, this
reduces the time for your test from 0.26 to 0.09.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert month name to month number faster

2010-01-06 Thread wiso
Antoine Pitrou wrote:

 Le Wed, 06 Jan 2010 12:03:36 +0100, wiso a écrit :
 
 
 from time import time
 t = time(); xxx=map(to_dict,l); print time() - t # 0.5 t = time();
 xxx=map(to_if,l); print time() - t   # 1.0
 
 Don't define your own function just for attribute access. Instead just
 write:
 
 xxx = map(month_dict.__getitem__, l)

t = time(); xxx=map(month_dict.__getitem__,l); print time() - t # 0.2

month_list = 
(,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec)

t = time(); xxx=map(month_list.index,l); time() - t # 0.6
-- 
http://mail.python.org/mailman/listinfo/python-list


creating tar file and streaming it over HTTP?

2010-01-06 Thread pbienst
I would like to bundle up a number of files in a tar file and send it
over a HTTP connection, but I would like to do this without creating
the tar file on disk first.

I know I can get tarfile to output to a stream by doing something like

tar_pipe = tarfile.open(mode=w|, fileobj=my_file_obj)

However, I can't figure out which file object to use to send this over
a HTTP connection.

I tried

conn = httplib.HTTPConnection(hostname, port)
conn.putrequest(PUT, /client/files)
conn.endheaders()
tar_pipe = tarfile.open(mode=w|, fileobj=conn.sock.makefile())
for filename in filenames:
tar_pipe.add(filename)
tar_pipe.close()
conn.getresponse()

but that does not send any data...

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


Re: Convert month name to month number faster

2010-01-06 Thread Steven D'Aprano
On Wed, 06 Jan 2010 12:03:36 +0100, wiso wrote:

 I'm optimizing the inner most loop of my script. I need to convert month
 name to month number. I'm using python 2.6 on linux x64.

According to your own figures below, it takes less than a nanosecond per 
lookup, at worst, even using a remarkably inefficient technique. Are you 
trying to tell us that this is the bottleneck in your script? I'm sorry, 
I find that implausible. I think you're wasting your time trying to 
optimise something that doesn't need optimizing.

Even if you halve the time, and deal with a million data points each time 
you run your script, you will only save half a second per run. I can see 
from the times you posted that you've spent at least an hour trying to 
optimise this. To make up for that one hour, you will need to run your 
script 7200 times, before you see *any* time savings at all.


 month_dict = {Jan:1,Feb:2,Mar:3,Apr:4, May:5, Jun:6,
  Jul:7,Aug:8,Sep:9,Oct:10,Nov:11,Dec:12}
 
 def to_dict(name):
   return month_dict[name]

This leads to a pointless function call. Just call month_dict[name] 
instead of calling a function that calls it.



 def to_if(name):
 if name == Jan: return 1
 elif name == Feb: return 2
 elif name == Mar: return 3
 elif name == Apr: return 4
 elif name == May: return 5
 elif name == Jun: return 6
 elif name == Jul: return 7
 elif name == Aug: return 8
 elif name == Sep: return 9
 elif name == Oct: return 10
 elif name == Nov: return 11
 elif name == Dec: return 12
 else: raise ValueError

That is remarkably awful.

 
 import random
 l = [random.choice(month_dict.keys()) for _ in range(100)]
 
 from time import time
 t = time(); xxx=map(to_dict,l); print time() - t # 0.5 
 t = time(); xxx=map(to_if,l); print time() - t   # 1.0

This is not a reliable way to do timings. You should use the timeit 
module.



 is there a faster solution? Maybe something with str.translate?

What makes you think str.translate is even remotely useful for this?




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


Re: fsync() doesn't work as advertised?

2010-01-06 Thread Brian D
On Jan 5, 1:08 pm, Nobody nob...@nowhere.com wrote:
 On Mon, 04 Jan 2010 08:09:56 -0800, Brian D wrote:
  If I'm running a process in a loop that runs for a long time, I
  occasionally would like to look at a log to see how it's going.

  I know about the logging module, and may yet decide to use that.

  Still, I'm troubled by howfsync() doesn't seem to work as advertised:

 http://docs.python.org/library/os.html

  If you’re starting with a Python file object f, first do f.flush(),
  and then do os.fsync(f.fileno())

 The .flush() method (and the C fflush() function) causes the
 contents of application buffers to be sent to the OS, which basically
 copies the data into the OS-level buffers.

 fsync() causes the OS-level buffers to be written to the physical drive.

 File operations normally use the OS-level buffers; e.g. if one process
 write()s to a file and another process read()s it, the latter will see
 what the former has written regardless of whether the data has been
 written to the drive.

 The main reason for usingfsync() is to prevent important data from being
 lost in the event of an unexpected reboot or power-cycle (an expected
 reboot via the shutdown or halt commands will flush all OS-level
 buffers to the drive first). Other than that,fsync() is almost invisible
 (I say almost, as there are mechanisms to bypass the OS-level buffers,
 e.g. the O_DIRECT open() flag).

An excellent explanation of the process. I've seen this in other
programming environments, so I could visualize something to that
effect, but couldn't have verbalized it. I certainly have a better
idea what's happening. Thanks for the contribution.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help to pass self.count to other classes.

2010-01-06 Thread Bruno Desthuilliers

Bill a écrit :

After a year with Python 2.5 on my Windows box, I still have trouble
understanding classes.

Below, see the batch file and the configuration script for
my Python interactive prompt.

The widths of the secondary prompts increase when  the self.count of
SysPrompt1 exceeds 99.

I am using a global variable zxc to share self.count, which is not
Pythonic.


It's not unpythonic - but it's not good OO style neither !-)


How can I pass in self.count without a global?


(snip)


sys.ps1 = SysPrompt1()
sys.ps2 = SysPrompt2()
sys.displayhook = DisplayHook()
sys.excepthook = ExceptHook()



hint #1: a bound method is also a callable.
hint #2: an object can be an attribute of another object.


Possible OO solution:

class Counter(object):
def __init__(self):
self._count = 0
   def inc(self):
self._count += 1
   value = property(fget=lambda s: s._count)

class Prompt1(object):
def __init__(self, counter):
self._counter = counter
def _str_(self):
self._counter.inc()
return '[%2d] ' % self._counter.value

class Prompt2(object):
def __init__(self, counter):
self._counter = counter
def _str_(self):
if self._counter.value  99: # XXX magic number
return '.. '
else:
return '. '

class MySysHookHandler(object):
def __init__(self):
self._counter = Counter()
self.ps1 = Prompt1(self._counter)
self.ps2 = Prompt2(self._counter)

 def displayhook(self, value):
 if value is None:
 return
 if self._counter.value  99: # XXX magic number
 print '[ out]', value, '\n'
 else:
print '[out]', value, '\n'

 def excepthook(self, type, value, trace):
 if self._counter.value  99: # XXX magic number
 print '[ err]', value, '\n'
 else:
 print '[err]', value, '\n'


handler = MySysHook()
sys.ps1 = handler.ps1
sys.ps2 = handler.ps2
sys.displayhook = handler.displayhook
sys.excepthook = handler.excepthook

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


Re: Do I have to use threads?

2010-01-06 Thread Philip Semanchuk


On Jan 6, 2010, at 12:45 AM, Brian J Mingus wrote:

On Tue, Jan 5, 2010 at 9:36 PM, Philip Semanchuk  
phi...@semanchuk.comwrote:




On Jan 5, 2010, at 11:26 PM, aditya shukla wrote:

Hello people,


I have 5 directories corresponding 5  different urls .I want to  
download
images from those urls and place them in the respective  
directories.I have
to extract the contents and download them simultaneously.I can  
extract the

contents and do then one by one. My questions is for doing it
simultaneously
do I have to use threads?



No. You could spawn 5 copies of wget (or curl or a Python program  
that
you've written). Whether or not that will perform better or be  
easier to
code, debug and maintain depends on the other aspects of your  
program(s).


bye
Philip



Obviously, spawning 5 copies of wget is equivalent to starting 5  
threads.

The answer is 'yes'.


???

Process != thread


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


Re: creating tar file and streaming it over HTTP?

2010-01-06 Thread Steve Holden
pbienst wrote:
 I would like to bundle up a number of files in a tar file and send it
 over a HTTP connection, but I would like to do this without creating
 the tar file on disk first.
 
 I know I can get tarfile to output to a stream by doing something like
 
 tar_pipe = tarfile.open(mode=w|, fileobj=my_file_obj)
 
 However, I can't figure out which file object to use to send this over
 a HTTP connection.
 
 I tried
 
 conn = httplib.HTTPConnection(hostname, port)
 conn.putrequest(PUT, /client/files)
 conn.endheaders()
 tar_pipe = tarfile.open(mode=w|, fileobj=conn.sock.makefile())
 for filename in filenames:
 tar_pipe.add(filename)
 tar_pipe.close()
 conn.getresponse()
 
 but that does not send any data...
 
I haven't used socket.makefile() in a blue age so this is untested, but
I'm guessing you need a *write* file (remember, sockets have two
directions). So try

   fileobj=conn.sock.makefile(w)...

and let me know if that helps.

regards
 Steve

-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Do I have to use threads?

2010-01-06 Thread Brian J Mingus
On Wed, Jan 6, 2010 at 6:24 AM, Philip Semanchuk phi...@semanchuk.comwrote:


 On Jan 6, 2010, at 12:45 AM, Brian J Mingus wrote:

  On Tue, Jan 5, 2010 at 9:36 PM, Philip Semanchuk phi...@semanchuk.com
 wrote:


 On Jan 5, 2010, at 11:26 PM, aditya shukla wrote:

 Hello people,


 I have 5 directories corresponding 5  different urls .I want to download
 images from those urls and place them in the respective directories.I
 have
 to extract the contents and download them simultaneously.I can extract
 the
 contents and do then one by one. My questions is for doing it
 simultaneously
 do I have to use threads?


 No. You could spawn 5 copies of wget (or curl or a Python program that
 you've written). Whether or not that will perform better or be easier to
 code, debug and maintain depends on the other aspects of your program(s).

 bye
 Philip



 Obviously, spawning 5 copies of wget is equivalent to starting 5 threads.
 The answer is 'yes'.


 ???

 Process != thread


Just like the other nitpicker it is up to you to explain why the
differences, and not he similarities, are relevant to this problem.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help to pass self.count to other classes.

2010-01-06 Thread Steve Holden
Bill wrote:
 After a year with Python 2.5 on my Windows box, I still have trouble
 understanding classes.
 
 Below, see the batch file and the configuration script for
 my Python interactive prompt.
 
 The widths of the secondary prompts increase when  the self.count of
 SysPrompt1 exceeds 99.
 
 I am using a global variable zxc to share self.count, which is not
 Pythonic.
 
 How can I pass in self.count without a global?
 I did RTFM, aka Google, but to no avail.
 
 echo py.bat
 set PYTHONSTARTUP=c:\scripts\startup.py
 python
 ^Z
 
 # startup.py
 # inspired by:
 # http://www.doughellmann.com/PyMOTW/sys/interpreter.html
 
 import sys
 
 class SysPrompt1(object):
 def __init__(self):
 self.count = 0
 def __str__(self):
 self.count += 1
 global zxc
 zxc = self.count
 return '[%2d] ' % self.count
 
 class SysPrompt2(object):
 def __str__(self):
 global zxc
 if zxc  99: return '.. '
 else: return '. '
 
 class DisplayHook(object):
 def __call__(self, value):
 if value is None: return
 global zxc
 if zxc  99: print '[ out]', value, '\n'
 else: print '[out]', value, '\n'
 
 class ExceptHook(object):
 def __call__(self, type, value, trace):
 global zxc
 if zxc  99: print '[ err]', value, '\n'
 else: print '[err]', value, '\n'
 
 sys.ps1 = SysPrompt1()
 sys.ps2 = SysPrompt2()
 sys.displayhook = DisplayHook()
 sys.excepthook = ExceptHook()
 
As Francesco points out, OO programming isn't *mandatory* in Python.

However, if you used a single class instead of multiples then you could
use an instance variable for zxc, and have each of the  functions be
bound methods (i.e. methods of the instance, not the class).

This is untested code (some days I don't seem to write any other kind
...) but it should give you the flavor:

class kbInterface(object):
def __init__(self):
self.zxc = 0
def prompt1(self):
self.count += 1
return [%d] 
def prompt2(self):
l = len(str(self.count))+1
return %s  % .*l
def dhook(self, value):
print [%d out] % self.count
def ehook(self, type, value, trace):
print [%d err]\n % value

kbi = kbInterface()
sys.ps1 = kbi.prompt1
sys.ps2 = kbi.prompt2
sys.displayhook = kbi.dhook
sys.excepthook = kbi.ehook

Do you get the idea? Now the count is shared between all the methods,
and it's available in the instance's namespace.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: chown'ing by script

2010-01-06 Thread Steve Holden
Victor Subervi wrote:
 On Wed, Jan 6, 2010 at 2:12 AM, alex23 wuwe...@gmail.com
 mailto:wuwe...@gmail.com wrote:
 
 Carsten Haese carsten.ha...@gmail.com
 mailto:carsten.ha...@gmail.com wrote:
  What is the underlying problem you're trying to solve with this
  approach?
 
 To be paid for developing a web site shopping cart without actually
 having to learn Python.
 
 
 LOL! I've written about 12,000 lines of code in this, BTW. Crawl back
 into your cave :)
 beno
 
Which, I don't doubt, could have been 2,000 lines had you bothered to
take the excellent advice you've been offered on learning Python. Still,
the better the advice the worse it's wasted ...

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: [Python] Re: Printing plain text with exact positioning on Windows

2010-01-06 Thread Chris Gonnerman

KvS wrote:

Ok, actually I quite like being able to print straightforward through
your code, i.e. without any extra modules installed. I understand that
sending text to the printer is in principle as simple as

dc.TextOut(scale_factor * 72,
-1 * scale_factor * 72,
Testing...)

I didn't see you do anything with adjusting margins in the code. Does
that mean that if I would e.g. do

dc.TextOut(0,
0,
Testing...)

the printout would appear in the upper left corner of the paper, as
close to the edges as the printer is capable of? (Sorry, but I only
have Ubuntu available at the moment, no Windows).
  
Actually, as I understand it (and I'll admit my understanding is a bit 
flawed in some areas), when you tell MSWinPrint.py to print at (0, 0), 
you are telling it to print at the actual paper edge; if that's outside 
the printable area (and it probably is for most printers), your printing 
will be cut off.


Best thing to do is to try it.

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


Re: Do I have to use threads?

2010-01-06 Thread exarkun

On 04:26 am, adityashukla1...@gmail.com wrote:

Hello people,

I have 5 directories corresponding 5  different urls .I want to 
download
images from those urls and place them in the respective directories.I 
have
to extract the contents and download them simultaneously.I can extract 
the
contents and do then one by one. My questions is for doing it 
simultaneously

do I have to use threads?

Please point me in the right direction.


See Twisted,

 http://twistedmatrix.com/

in particular, Twisted Web's asynchronous HTTP client,

 http://twistedmatrix.com/documents/current/web/howto/client.html
 http://twistedmatrix.com/documents/current/api/twisted.web.client.html

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


Re: Dynamic text color

2010-01-06 Thread Neil Cerutti
On 2010-01-05, John Posner jjpos...@optimum.net wrote:
 2. It's probably not the best idea to use a single variable
 (you use  file) to do double-duty: to hold the name of a
 file, and to hold the  open-file object returned by the open()
 function. It's perfectly legal,  but it hides information that
 might be useful when you're debugging a  program. This is
 better:

fname = 'red.txt'
inpf = open(fname, r)

Alternatively:

 infile = open(red.txt, r)
 infile.name
'red.txt'

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


Re: embedded python on mac - linking problem

2010-01-06 Thread Diez B. Roggisch

Krzysztof Kobus schrieb:

Hi,

I have a problem with linking python module with my application on mac in order to make 
the module available in embedded python.

My python module is contained in  j3kmodule.cxx file and module initialization 
function is exported in j3kmodule.h

j3kmodule.h:

PyMODINIT_FUNC PyInit_j3k(void);


j3kmodule.cxx:
--
PyMODINIT_FUNC
PyInit_j3k(void)
  {
  PyObject *m = NULL;

  if ((m = PyModule_Create(j3k_module)) == NULL)
return NULL;

  return m;
  }


Then in my application in KkPython.cxx file I have:

KkPython.cxx:
-

#include j3kmodule.h

/* Add a builtin module, before Py_Initialize */
PyImport_AppendInittab(j3k, PyInit_j3k);


I link my application with the module and get following linking error on mac 
although on open suse linux exactly the same procedure works fine:

g++ -headerpad_max_install_names -o ../../bin/render.app/Contents/MacOS/render 
main.o KkPython.o -lkkbase 
-L/Users/kk/dev/J3K/trunk/j3ksrc/examples/render/../../lib/ 
-lQtSolutions_PropertyBrowser-2.5 -lpython3.1 
/Users/kk/dev/J3K/trunk/j3ksrc/python/modules/build/lib.macosx-10.3-i386-3.1/j3k.so
 -framework OpenGL -framework AGL
ld: warning in 
/Users/kk/dev/J3K/trunk/j3ksrc/python/modules/build/lib.macosx-10.3-i386-3.1/j3k.so,
 file is not of required architecture
Undefined symbols:
  _PyInit_j3k, referenced from:
  _PyInit_j3k$non_lazy_ptr in KkPython.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make: *** [../../bin/render.app/Contents/MacOS/render] Error 1


I appreciate any hints,


The missing symbol looks like a C++-symbol - but Python is C. Do you 
maybe miss the


  extern C

declaration.

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


Python books, literature etc

2010-01-06 Thread Stuart Murray-Smith
Greetings list

I can code in Python (strong beginner), and would like to read more
books and/or online resources.

Could someone please point out any good books, websites, tutorials etc
to help me get to the next level.

Your help  insight highly appreciated :)

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


Re: Printing plain text with exact positioning on Windows

2010-01-06 Thread KvS
On Jan 5, 7:16 pm, Nobody nob...@nowhere.com wrote:
 On Tue, 05 Jan 2010 04:40:14 -0800, KvS wrote:
  Did you mean borderless printing?
  Every printer needs his margins, some more some less. Some printers have 
  the
  ability to do borderless printing but usualy they can do it only on special
  or photo paper. So you can adjust the pdf as you wish, even with no 
  margins,
  and then try to find under printer options borderless printing. That is
  why I didn't understand :-)) it is a printer thing not pdf!

  As much as possible borderless, yes. Of course the printer will
  still apply some small margin, but that's ok. A margin of say 0.5 cm.
  is fine. So it's not a printer thing, I accept the (physical)
  limitations of the printer, but I want to avoid any extra margins due
  to software settings.

 Hardcopy document formats such as PostScript and PDF use positions
 relative to the edges of the page, not the margins.

Right. Still, Acrobat Reader by default scales the contents to fit on
a page and creates some margins by doing so, no? So if my text is
close to the left and right edges, as I want, it will get scaled and
extra margins will occur. Avoiding this still requires me to be able
to turn off this scaling in the printing preferences somehow
programmatically, so it doesn't seem to make the problem easier?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing plain text with exact positioning on Windows

2010-01-06 Thread Sean DiZazzo
On Jan 5, 11:40 am, KvS keesvansch...@gmail.com wrote:
 On Jan 5, 7:16 pm, Nobody nob...@nowhere.com wrote:



  On Tue, 05 Jan 2010 04:40:14 -0800, KvS wrote:
   Did you mean borderless printing?
   Every printer needs his margins, some more some less. Some printers have 
   the
   ability to do borderless printing but usualy they can do it only on 
   special
   or photo paper. So you can adjust the pdf as you wish, even with no 
   margins,
   and then try to find under printer options borderless printing. That is
   why I didn't understand :-)) it is a printer thing not pdf!

   As much as possible borderless, yes. Of course the printer will
   still apply some small margin, but that's ok. A margin of say 0.5 cm.
   is fine. So it's not a printer thing, I accept the (physical)
   limitations of the printer, but I want to avoid any extra margins due
   to software settings.

  Hardcopy document formats such as PostScript and PDF use positions
  relative to the edges of the page, not the margins.

 Right. Still, Acrobat Reader by default scales the contents to fit on
 a page and creates some margins by doing so, no? So if my text is
 close to the left and right edges, as I want, it will get scaled and
 extra margins will occur. Avoiding this still requires me to be able
 to turn off this scaling in the printing preferences somehow
 programmatically, so it doesn't seem to make the problem easier?

Maybe you could have the user print your data on a larger sheet of
paper;one that is sure to include all of the data, and include crop
marks on the printout.  The user then cuts along the crop marks to
leave a perfectly sized, marginless page. This is how printers do
bleeds.
-- 
http://mail.python.org/mailman/listinfo/python-list


Online math-coding contest

2010-01-06 Thread dhashrath govindarajan
Hi , we gladly invite you to take part in Athena - the Online Math
Coding Contest of Kurukshetra 2010 , the International
Techo-Management Fest organised by College  Of Engineering Guindy ,
India under the patronage of UNESCO .

Here's your chance to lock horns against the best minds across the
globe and showcase your algorithmic prowess and mathematical acumen !!
Participants from 20+  countries already registered!!

catch the action at  www.athena.kurukshetra.org.in   Exciting
prizes to be won !!

For queries please contact   ath...@kurukshetra.org.in

Dates :
Practice contest  : 6th January 5.00 P.M Indian Standard Time
Main  contest  : 8th January - 15th January

awaiting your presence ,
Team Athena
-- 
http://mail.python.org/mailman/listinfo/python-list


unittest inconsistent

2010-01-06 Thread Matt Haggard
Can anyone tell me why this test fails?

http://pastebin.com/f20039b17

This is a minimal example of a much more complex thing I'm trying to
do.  I'm trying to hijack a function and inspect the args passed to it
by another function.

The reason the 'Tester' object has no attribute 'arg1' is because
self still refers to the object made for testA.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing plain text with exact positioning on Windows

2010-01-06 Thread Gerry
If this is, by any chance, an HP printer, the printer may support PCL
5 (or a similar language).  I've written PCL scripts (in Pascal, so a
while ago) to precisely print points at the printer resolution (i.e.,
I picked which six-hundredth of an inch in height and width dimensions
to print a dot. PCL 5 absolutely would let you put text anywhere you
wanted, including the absolute limits on margins that the hardware
supports.  (PCL is printer control language).

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


Re: Python books, literature etc

2010-01-06 Thread Shawn Milochik
Search Google. You'll find it all.

Search this list's archives. This kind of thing has been discussed a thousand 
times.

It also wouldn't hurt to brush up on this:
http://catb.org/~esr/faqs/smart-questions.html

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


Re: chown'ing by script

2010-01-06 Thread D'Arcy J.M. Cain
On Wed, 06 Jan 2010 08:58:13 -0500
Steve Holden st...@holdenweb.com wrote:
 Victor Subervi wrote:
[Usual nonsense removed]

 Which, I don't doubt, could have been 2,000 lines had you bothered to

Steve - any chance that you could stop replying to this idiot or at
least do it privately.  There's not much point to kill-filing someone
if someone else is just going to repeat his posts.

-- 
D'Arcy J.M. Cain da...@druid.net |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Convert month name to month number faster

2010-01-06 Thread jfabiani
VYAS ASHISH M-NTB837 wrote:

  
 How about using list.index() and storing month names in a list? You may
 want to measure performance your self and conclude.
 
 Regards,
 Ashish Vyas
 
 -Original Message-
 From: python-list-bounces+ntb837=motorola@python.org
 [mailto:python-list-bounces+ntb837=motorola@python.org] On Behalf Of
 wiso
 Sent: Wednesday, January 06, 2010 4:34 PM
 To: python-list@python.org
 Subject: Convert month name to month number faster
 
 I'm optimizing the inner most loop of my script. I need to convert month
 name to month number. I'm using python 2.6 on linux x64.
 
 
 month_dict = {Jan:1,Feb:2,Mar:3,Apr:4, May:5, Jun:6,
 Jul:7,Aug:8,Sep:9,Oct:10,Nov:11,Dec:12}
 
 def to_dict(name):
   return month_dict[name]
 
 def to_if(name):
 if name == Jan: return 1
 elif name == Feb: return 2
 elif name == Mar: return 3
 elif name == Apr: return 4
 elif name == May: return 5
 elif name == Jun: return 6
 elif name == Jul: return 7
 elif name == Aug: return 8
 elif name == Sep: return 9
 elif name == Oct: return 10
 elif name == Nov: return 11
 elif name == Dec: return 12
 else: raise ValueError
 
 import random
 l = [random.choice(month_dict.keys()) for _ in range(100)]
 
 from time import time
 t = time(); xxx=map(to_dict,l); print time() - t # 0.5
 t = time(); xxx=map(to_if,l); print time() - t   # 1.0
 
 
 is there a faster solution? Maybe something with str.translate?
 
 The problem is a little different because I don't read random data, but
 sorted data. For example:
 
 l = [x for x in
 (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
 )
 for _ in range(1000)] # [Jan,Jan, ..., Feb, Feb, ...]
 
 so maybe the to_if approach will be faster if I write the case in the
 best
 order. Look:
 
 l = [Jan] * 100 # to_if is in the best order for Jan
 t = time(); xxx=map(to_dict,l); print time() - t # 0.5
 t = time(); xxx=map(to_if,l); print time() - t # 0.5
 
 
what just using 
get(key[, default])¶
Return the value for key if key is in the dictionary, else default. If
default is not given, it defaults to None, so that this method never raises
a KeyError.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedded python on mac - linking problem

2010-01-06 Thread Krzysztof Kobus
Hi,

The missing symbol looks like a C++-symbol - but Python is C. Do you maybe 
miss the
 extern C


 declaration.

I have not specified extern C as I assume it is a part of 
PyMODINIT_FUNC define. At least documentation says so:

Note that PyMODINIT_FUNC declares the function as PyObject * return type,
declares any special linkage declarations required by the platform, and for C++
declares the function as extern C.

Regards,

KK


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


Introspection

2010-01-06 Thread m...@infoserv.dk
I'm looking for a way to make a list of string literals in a class.

Example:

class A:
   def method(self):
   print 'A','BC'

 ExtractLiterals(A)
['A','BC']

Is this possible? Can anyone point me in the right direction?

Thanks.

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


Re: chown'ing by script

2010-01-06 Thread Steve Holden
D'Arcy J.M. Cain wrote:
 On Wed, 06 Jan 2010 08:58:13 -0500
 Steve Holden st...@holdenweb.com wrote:
 Victor Subervi wrote:
 [Usual nonsense removed]
 
 Which, I don't doubt, could have been 2,000 lines had you bothered to
 
 Steve - any chance that you could stop replying to this idiot or at
 least do it privately.  There's not much point to kill-filing someone
 if someone else is just going to repeat his posts.
 
I think idiot's a *bit* strong, but I have to confess that even my
tireless wish to evangelize Python has in Victor's case become a bit
tired, so I will be happy to oblige.

Victor, please refer to python-tutor for further (and more appropriate)
assistance.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Phlip
On Jan 5, 8:49 pm, Steven D'Aprano
ste...@remove.this.cybersource.com.au wrote:

  (A related question - why can't I just go 'if record = method():  use
  (record)'. Why extra lines just to trap and assign the variable before
  using it?)

 Because that idiom is responsible for probably the most common error in C
 of all, at least one of the most common errors. Thank goodness Python
 forbids such a dangerous construct.

switching = for == is the most common error in C?

I can't tell if you are joking.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Phlip
On Jan 5, 10:54 pm, Benjamin Kaplan benjamin.kap...@case.edu wrote:

 {41: None}[41] ?

 In cases where None is a valid result, you can't use it to signal failure.

Asked and answered. You change the sentinel in .fetch to something
else.

But y'all keep on defending the language making your programming
decisions for you!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python books, literature etc

2010-01-06 Thread J
On Wed, Jan 6, 2010 at 09:35, Shawn Milochik sh...@milochik.com wrote:
 Search Google. You'll find it all.

 Search this list's archives. This kind of thing has been discussed a thousand 
 times.

 It also wouldn't hurt to brush up on this:
 http://catb.org/~esr/faqs/smart-questions.html

Heh... I've seen that link mentioned many many times on some other
lists I belong to :)  But I agree.  HOWEVER, that is a valid question.

BUT, the answer is really up to the person asking it.

For example, I too am a relative beginner with Python.  Luckily I DO
have at least an educational background in OOP, and at least a
professional background in basic coding (some perl, BASH, etc).  So I
do tend to rely a lot on google when I run into a snag, THEN if that
doesn't work, I come here with specific questions.

FWIW, my Google searches always look something like python what I'm
searching for and 99% of the time, that gives me the answers I seek.

That being said, however, I also am somewhat old school and prefer to
have hard copy at hand too.  Sometimes, it's just that much more
satisfying to have a physical book handy to look things up in.  Maybe
it's a comfort thing, I don't know...

So in that vein, while I can't suggest any specific books, I can say
this... right now, I have a copy of O'Reilly's Learning Python that I
use as a reference, as well as a much older copy of the Python 2.1
Bible that I picked up almost a decade ago now the first time I messed
around with Python.

My personal preference, while searching Google and asking on lists
like this is quick and invaluable for the real world knowledge that
is shared, is to also have A: something along the lines of the
Learning Foo books from O'Reilly because they tend to have lengthy
explanations that I usually can understand on my own, and B: some sort
of Cookbook on the topic at hand.  I haven't found a Python cookbook
that I like enough to buy yet, but I'm still looking.  Those come in
handy for simple snippets and examples when doing specific tasks.

So yeah, Google and this list are certainly invaluable, but some of us
actually like having the heft of a lofty tome to peruse for the
answers to the mysteries of the universe.

Cheers
Jeff



-- 

Charles de Gaulle  - The better I get to know men, the more I find
myself loving dogs. -
http://www.brainyquote.com/quotes/authors/c/charles_de_gaulle.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Steve Holden
Phlip wrote:
[...]
 Don't prevent me from using a technique just because others had
 trouble with it.
 
I presume you also campaign against anti-lock braking systems (or at
least don't use cars which have them - after all, anyone who knows how
to drive should be able to brake properly, right? And even if they
don't, *you* can, so you shouldn't have to pay the extra. Of course, if
someone else happens to hit you because they *couldn't* drive safely you
will happily give up your life).

 And if bar() == foo is the superior technique anyway, because the ==
 happens in chronological and lexical order after the bar() call.

That's about the most specious piece of hogwash I've seen this week.
Python doesn't make any guarantees about the evaluation order of =='s
operands (unlike and and or). That's cargo cult programming right
there. Readability is surely the only reason to decide how to write that
if, and I suspect most people would choose if foo == bar() for that
reason, though the difference is slight.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Grant Edwards
On 2010-01-06, r0g aioe@technicalbloke.com wrote:

 NO! It's a rude way to start a sentence don't you think?

No.  When somebody asks a yes/no question, answering yes or no
seems quite polite to me.  Following the yes/no answer with an
explanation of the answer is always nice, and I've little doubt
that's what happened.

 Just because you're correcting someone doesn't mean you have
 to be combative and try and make them feel small.

Answering a yes/no question with no doesn't seem to me to be
combative if the correct answer is indeed no.  But I've lost
track of the post you found objectionable...

-- 
Grant Edwards   grante Yow! And then we could sit
  at   on the hoods of cars at
   visi.comstop lights!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help to pass self.count to other classes.

2010-01-06 Thread Bruno Desthuilliers

Steve Holden a écrit :
(snip)

This is untested code


indeed !-)


class kbInterface(object):
def __init__(self):
self.zxc = 0
def prompt1(self):
self.count += 1


Ahem...

(snip)


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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Steve Holden
Phlip wrote:
 On Jan 5, 8:49 pm, Steven D'Aprano
 ste...@remove.this.cybersource.com.au wrote:
 
 (A related question - why can't I just go 'if record = method():  use
 (record)'. Why extra lines just to trap and assign the variable before
 using it?)
 Because that idiom is responsible for probably the most common error in C
 of all, at least one of the most common errors. Thank goodness Python
 forbids such a dangerous construct.
 
 switching = for == is the most common error in C?
 
 I can't tell if you are joking.

Well, there's also the indenting code without surrounding it by braces
error, but y'all just keep defending the approach to programming that
*you* think is best. Just don't expect others to agree. The FAQ clearly
documents why Python is a statement-based, and not an expression-based,
language.

Me, I think Guido is a pretty good language designer, and while we've
had our differences I think that Python is a *much* better language than
C and most others.

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: Introspection

2010-01-06 Thread Miki
Hello Martin,

 I'm looking for a way to make a list of string literals in a class.
from inspect import getsourcelines
from tokenize import generate_tokens, STRING, NUMBER

def is_literal(t):
return t[0] in (STRING, NUMBER)

def get_lieterals(obj):
lines, _ = getsourcelines(obj)
readline = iter(lines).next
return [t[1] for t in generate_tokens(readline) if is_literal(t)]

if __name__ == __main__:
class A:
def f(self):
print A, B

print get_lieterals(A)

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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Bruno Desthuilliers

Phlip a écrit :

On Jan 5, 8:49 pm, Steven D'Aprano
ste...@remove.this.cybersource.com.au wrote:


(A related question - why can't I just go 'if record = method():  use
(record)'. Why extra lines just to trap and assign the variable before
using it?)

Because that idiom is responsible for probably the most common error in C
of all, at least one of the most common errors. Thank goodness Python
forbids such a dangerous construct.


switching = for == is the most common error in C?

I can't tell if you are joking.


It's at least a _very_ common error in all languages that allow this 
construct. In C, it's common enough to gave birth to the BestPractice 
you described, ie swapping operand orders in equality test to have the 
compiler detect the problem - at least when one of the operand is a 
function call expression or constant (it obviously won't 'work' when 
both operands are variables).


Anyway: in Python, assignment is not an expression, and this isn't going 
to change anytime soon.

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


Re: Dynamic text color

2010-01-06 Thread John Posner
On Tue, 05 Jan 2010 16:54:44 -0500, Dave McCormick mackrac...@gmail.com  
wrote:


But it is not what I am wanting. I first thought to make it look for a  
space but that would not work when a single character like # is to be  
colored if there is a string of them.  Or if all of the characters  
between quotes are to be colored.


Regular expressions are good at handling searches like:

* all the characters between quotes
* the two-character string do, but only if it's a complete word

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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Ben Kaplan

On 1/6/10 10:12 AM, Phlip wrote:

On Jan 5, 10:54 pm, Benjamin Kaplanbenjamin.kap...@case.edu  wrote:

   

{41: None}[41] ?

In cases where None is a valid result, you can't use it to signal failure.
 

Asked and answered. You change the sentinel in .fetch to something
else.
   
When did I specify a sentinel value? You're saying that if None is a 
valid value in the dict, you can't use slice syntax for it.



But y'all keep on defending the language making your programming
decisions for you!
   


Your example is the one where the language makes programming decisions 
for you. Your language is deciding that if I use slice syntax, I want 
the sentinel to be None. Python is deciding that unless I give it a 
sentinel, there is no sentinel.

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


Re: TypeError

2010-01-06 Thread MRAB

Victor Subervi wrote:

Hi;
I get this error:

 /var/www/html/angrynates.com/christians/cart/simplemail/mail.py 
http://angrynates.com/christians/cart/simplemail/mail.py

  153 /head
  154 body'''
  155 commitSale()
  156 myMail()
  157 print '''
commitSale = function commitSale
 /var/www/html/angrynates.com/christians/cart/simplemail/mail.py 
http://angrynates.com/christians/cart/simplemail/mail.py in commitSale()

   98 cursor.execute('select max(ID) from %sCustomerData;' % store)
   99 custID = cursor.fetchone()[0]
  100   customerData(store, tmpTable, custID, patientID)
  101
  102 def myMail():
global customerData = function customerData, global store = 
'products', tmpTable = 'tem12627568064', custID = 1, global patientID = 
'None'
 /var/www/html/angrynates.com/christians/cart/customerData.py 
http://angrynates.com/christians/cart/customerData.py in 
customerData(store='products', tmpTable='tem12627568064', custID=1, 
patientID='None')

   39 body
   40 
   41   print 
   42   print 'h1 align=center%s Customer Data/h1' % 
(store[0].upper() + store[1:])

   43   cursor.execute('describe %sCustomerData' % store)
store = 'products'

ValueError: unsupported format character '(' (0x28) at index 54
  args = (unsupported format character '(' (0x28) at index 54,)

Apparently that character is a file separator, which I presume is an 
invisible character. I tried retyping the area in question, but with no 
avail (threw same error). Please advise. Complete code follows.



Please provide the actual code (and, preferably, an easier-to-understand
traceback, like what CPython does!). What you supplied isn't runnable.
--
http://mail.python.org/mailman/listinfo/python-list


Re: IOError - cannot create file (linux daemon-invoked script)

2010-01-06 Thread cassiope
On Jan 5, 10:58 am, Nobody nob...@nowhere.com wrote:
 On Mon, 04 Jan 2010 21:30:31 -0800, cassiope wrote:
  One more tidbit observed: my last note, that it works when using
  seteuid/setegid?
  Well - that only applies if the daemon is running under strace (!).
  It fails
  if started directly by root, or if the strace session has ended,
  leaving the
  main body of the daemon running in its normal headless manner.

  I wonder if running under strace -f - might setegid/seteuid be
  prevented from
  having their normal effect?

 Possibly. The ptrace() syscall on which strace depends will fail if you
 try to trace a privileged process and you aren't root, so it's possible
 that a ptrace()d process will refuse to become privileged.

 Here, privileged includes a process which has changed any of its UIDs or
 GIDs (this prevents a normal user from tracing, killing, etc an otherwise
 privileged process which has switched to the user's UID for the time being).

Thanks.

I guess it's time to trim this beast to a simpler state to isolate
what's
going wrong.  This may take awhile amidst everything else I have to be
doing...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Introspection

2010-01-06 Thread Steven D'Aprano
On Wed, 06 Jan 2010 06:53:40 -0800, m...@infoserv.dk wrote:

 I'm looking for a way to make a list of string literals in a class.
 
 Example:
 
 class A:
def method(self):
print 'A','BC'
 
 ExtractLiterals(A)
 ['A','BC']
 
 Is this possible? Can anyone point me in the right direction?


class A:
def extract_literals(self):
return A BC.split()
def method(self):
print self.extract_literals()


a = A()
a.extract_literals()



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


Re: TypeError

2010-01-06 Thread Victor Subervi
On Wed, Jan 6, 2010 at 12:29 PM, MRAB pyt...@mrabarnett.plus.com wrote:

 Victor Subervi wrote:

 Hi;
 I get this error:

  /var/www/html/angrynates.com/christians/cart/simplemail/mail.py 
 http://angrynates.com/christians/cart/simplemail/mail.py

  153 /head
  154 body'''
  155 commitSale()
  156 myMail()
  157 print '''
 commitSale = function commitSale
  /var/www/html/angrynates.com/christians/cart/simplemail/mail.py 
 http://angrynates.com/christians/cart/simplemail/mail.py in commitSale()

   98 cursor.execute('select max(ID) from %sCustomerData;' % store)
   99 custID = cursor.fetchone()[0]
  100   customerData(store, tmpTable, custID, patientID)
  101
  102 def myMail():
 global customerData = function customerData, global store = 'products',
 tmpTable = 'tem12627568064', custID = 1, global patientID = 'None'
  /var/www/html/angrynates.com/christians/cart/customerData.py 
 http://angrynates.com/christians/cart/customerData.py in
 customerData(store='products', tmpTable='tem12627568064', custID=1,
 patientID='None')

   39 body
   40 
   41   print 
   42   print 'h1 align=center%s Customer Data/h1' %
 (store[0].upper() + store[1:])
   43   cursor.execute('describe %sCustomerData' % store)
 store = 'products'

 ValueError: unsupported format character '(' (0x28) at index 54
  args = (unsupported format character '(' (0x28) at index 54,)

 Apparently that character is a file separator, which I presume is an
 invisible character. I tried retyping the area in question, but with no
 avail (threw same error). Please advise. Complete code follows.

  Please provide the actual code (and, preferably, an easier-to-understand
 traceback, like what CPython does!). What you supplied isn't runnable.


I ended up working around this problem another way. Thanks.
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need help to pass self.count to other classes.

2010-01-06 Thread Steve Holden
Bruno Desthuilliers wrote:
 Steve Holden a écrit :
 (snip)
 This is untested code
 
 indeed !-)
 
 class kbInterface(object):
 def __init__(self):
 self.zxc = 0
 def prompt1(self):
 self.count += 1
 
 Ahem...
 
 (snip)
 
 
Caveat emptor ... this code is worth what you paid for it :)

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


Re: creating tar file and streaming it over HTTP?

2010-01-06 Thread pbienst
Thanks for the tip! It doesn't change anything, though, so I've
debugged this a little bit further. The problem seems to be that the
receiving end (wsgi server) does not see the end of the data:

socket = environ[wsgi.input]
while True:
sys.stderr.write(before)
chunk = socket.read(4096)
sys.stderr.write(after)
if not chunk:
sys.stderr.write(done)
break
sys.stderr.write(chunk)

There is data from the tar file being printed, but in the end it hangs
in the 'before' statement, and never gets to 'done'. I tried flushing
the fileobj created by makefile(), but that doesn't seem to help.
There is also no environ[CONTENT_LENGTH] that I can use to detect
the end of the stream.

I'm probably missing something basic here...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Phlip

Steve Holden wrote:


y'all just keep defending the approach to programming that
*you* think is best.


Speak for yourself...
--
http://mail.python.org/mailman/listinfo/python-list


Re: lxml 2.2.4 on python3.1, Windows XP gives importerror

2010-01-06 Thread Sridhar Ratnakumar

On 1/5/2010 1:38 AM, VYAS ASHISH M-NTB837 wrote:

Dear All
I have Python 3.1 installed on Windows XP and Works nice.
I downloaded lxml 2.2.4 (lxml-2.2.4.win32-py3.1.exe) from pypi.
When I try:
from lxml import etree
I get:
ImportError: DLL load failed: This application has failed to start
because the application configuration is incorrect. Reinstalling the
application may fix this problem.


Are you by any chance running 64-bit Python (whereas the lxml binary you 
have installed is 32-bit)?


C: python -c import platform; print platform.architecture()

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


Re: how to change when the logging module creates the log file?

2010-01-06 Thread Chris Colbert
i was able to fix the exception by calling logging.shutdown() before the
call to os.remove().

However, I still think there is probably a more elegant solution.

On Wed, Jan 6, 2010 at 12:57 PM, Chris Colbert sccolb...@gmail.com wrote:

 I have an application the writes to a log file when specific exceptions are
 handled. However, if no exceptions are encountered, I don't want to create a
 log at all.

 The problem I am running into is that the stdlib logging module creates the
 log file immediately upon logger instantiation.

 Thus:
  logger = logging.basicConifg('testlog.txt')

 already creates the file 'testlog.txt'.

 So, at program close, I am reading the size of the log file, and if it is
 empty I remove it with os.remove(). This works fine on Linux, but throws a
 permission denied exception on Windows.

 There has to be a better way to do this than using a hack like that. Is
 there a way to make the logging module hold-off on file creation until the
 first log is generated? I could do it by wrapping logger in a class, but
 that would remove the beauty of having any module import logging from the
 stdlib and being able to write to the log.

 Thanks for any pointers!

 Chris

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


getfirst and re

2010-01-06 Thread Victor Subervi
Hi;
I need to do something like the following:

pat = re.compile('edit[0-9]*:[0-9]*')
check = form.getfirst(pat)

(to check things like 'edit0:1') How do I do this?
TIA,
beno

-- 
The Logos has come to bear
http://logos.13gems.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Python tk Listbox: -listvariable

2010-01-06 Thread Looney, James B
Yesterday, I searched all over trying to figure out how to properly use the 
listvariable argument with tk's Listbox class.  Unfortunately, no amount of 
searching (online) could come up with anything more useful than telling me the 
variable needed to be a list, and nothing built-in exists.

I finally came across a way of using it that I consider fairly simple, and 
wanted to toss it out there for everyone else.  One post I saw mentioned using 
StringVar.  That just didn't work well in my head, so instead I used its parent 
class: Variable.  Apparently, the trick is to use tuples.  If I use a list, 
string, etc - the Listbox seems to split the content based on spaces.  Not the 
behavior I was looking for as I have spaces in the strings I wish to display.

If anyone has better suggestions, I'd love to hear them.  (I thought about a 
ListVar class, but haven't made it much beyond the thought).  Regardless, I 
hope the following code helps others avoid the confusion I went through.

Sample code:
import Tkinter, tkSimpleDialog
from Tkconstants import *

class ListboxTest( tkSimpleDialog.Dialog ):
   #
   def __init__( self, master, tupleItems = () ):
  self.myVar = Tkinter.Variable()
  self.myVar.set( tupleItems )

  tkSimpleDialog.Dialog.__init__( self, master, Listbox testing )

   #
   def body( self, master ):
  lbox = Tkinter.Listbox( master, listvariable = self.myVar )
  lbox.grid( row = 0, column = 0, sticky = N + W )
  self.myVar.set( self.myVar.get() + tuple( [ * Final string being 
added * ] ) )
  print type( self.myVar.get() ), self.myVar.get()

if( __main__ == __name__ ):
   tk = Tkinter.Tk()
   lt = ListboxTest( tk, tuple( [ String 1 - with some spaces, String 2 - 
with more spaces ] ) )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getfirst and re

2010-01-06 Thread Tim Chase

I need to do something like the following:

pat = re.compile('edit[0-9]*:[0-9]*')
check = form.getfirst(pat)

(to check things like 'edit0:1') How do I do this?


Well, you can do it either as

  check = pat.search(string_to_search)

which is pretty plainly detailed in the help for the re module, 
both under the search() function and under the 8.2.2 Matching 
vs. Searching section.


Alternatively, if you plan to get the others too, you can use

  fi = pat.finditer(string_to_search)
  check = fi.next().group(0) # beware this may throw
  # a StopIteration if there are no more matches.

which would usually be done inside a loop where the StopIteration 
does the Right Thing(tm).


But if you're using it on HTML form text, regexps are usually the 
wrong tool, and you should be using an HTML parser (such as 
BeautifulSoup) that knows how to handle odd text and escapings 
better and more robustly than regexps will.


-tkc



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


Pass multidimensional array (matrix) to c function using ctypes

2010-01-06 Thread Daniel Platz
Hello,

I would like to pass a two dimensional array to C function in a dll. I
use ctypes to call the function.

I compile the dll with visual studio 2008 express and my C source code
looks like this.

#include stdio.h
#ifdef __cplusplus
extern C {  // only need to export C interface if
  // used by C++ source code
using namespace std;
#endif


__declspec(dllexport) int print(double** ptr, int ny, int nx)
{
int i, j;
for(i=0; iny; i++)
{
for(j=0; jnx; j++)
{
printf(%.3f \t, *(*(ptr+i)+j));
}
printf(\n);
}
return 0;
}

#ifdef __cplusplus
}
#endif

As you can see the function expects a doube** variable. I tried to
call this function from Python with this code.

import ctypes as ct

matrix = ct.cdll.LoadLibrary('matrix.dll')
getattr(matrix, 'print_matrix')

ptr_type = ct.c_double * 5 * 4
ptr = ptr_type()
matrix.print_matrix(ptr, ct.c_int(4), ct.c_int(5))

I expected to see a matrix showing only zeros since I can address the
single entries in Python by ptr[i][j]. Instead the interpreter returns
with the error message

WindowsError: exception: access violation reading 0x00
WARNING: Failure executing file: ctypes_matrix.py

Furthermore, I am wondering if there is a fast way to use a numpy 2D
array instead or alternatively to cast the ctypes array into a numpy
array.

Has someone an idea to help me?

Thank you very much

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


Re: getfirst and re

2010-01-06 Thread Victor Subervi
On Wed, Jan 6, 2010 at 1:27 PM, Tim Chase python.l...@tim.thechases.comwrote:

 But if you're using it on HTML form text, regexps are usually the wrong
 tool, and you should be using an HTML parser (such as BeautifulSoup) that
 knows how to handle odd text and escapings better and more robustly than
 regexps will.


I have an automatically generated HTML form from which I need to extract
data to the script which this form calls (to which the information is sent).
I believe BeautifulSoup is geared to scraping pages that exist permanently
on the web. By the time BeautifulSoup was called, this page would be gone.
Any other ideas?
TIA
beno
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getfirst and re

2010-01-06 Thread Tim Chase

Victor Subervi wrote:

On Wed, Jan 6, 2010 at 1:27 PM, Tim Chase python.l...@tim.thechases.comwrote:


But if you're using it on HTML form text, regexps are usually the wrong
tool, and you should be using an HTML parser (such as BeautifulSoup) that
knows how to handle odd text and escapings better and more robustly than
regexps will


I have an automatically generated HTML form from which I need to extract
data to the script which this form calls (to which the information is sent).
I believe BeautifulSoup is geared to scraping pages that exist permanently
on the web. By the time BeautifulSoup was called, this page would be gone.


BeautifulSoup takes string data fed to it, and builds a structure 
that can be neatly navigated.  That string data can come from a 
web page, from a disk, or even a serial port, a 
random-character-generator, or just from HTML that's built up in 
memory and never sees a network or a disk.  It's worth reading 
its documentation[1] and trying its examples to get familiar with it.


-tkc


[1]
http://www.crummy.com/software/BeautifulSoup/documentation.html



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


Re: please help shrink this each_with_index() implementation

2010-01-06 Thread Nobody
On Tue, 05 Jan 2010 12:20:58 -0800, Marco Nawijn wrote:

 You could use the build-in function enumerate inside a list
 comprehension.
 
 seq = range(5)
 [ (i,s) for i,s in enumerate(seq) ]
 [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

Just use list(), i.e. list(enumerate(seq)).

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


3 byte network ordered int, How To ?

2010-01-06 Thread mudit tuli
For a single byte, struct.pack('B',int)
For two bytes, struct.pack('H',int)
what if I want three bytes ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getfirst and re

2010-01-06 Thread Victor Subervi
On Wed, Jan 6, 2010 at 1:59 PM, Tim Chase python.l...@tim.thechases.comwrote:

 Victor Subervi wrote:

 On Wed, Jan 6, 2010 at 1:27 PM, Tim Chase python.l...@tim.thechases.com
 wrote:

  But if you're using it on HTML form text, regexps are usually the wrong
 tool, and you should be using an HTML parser (such as BeautifulSoup) that
 knows how to handle odd text and escapings better and more robustly than
 regexps will


 I have an automatically generated HTML form from which I need to extract
 data to the script which this form calls (to which the information is
 sent).
 I believe BeautifulSoup is geared to scraping pages that exist permanently
 on the web. By the time BeautifulSoup was called, this page would be gone.


 BeautifulSoup takes string data fed to it, and builds a structure that can
 be neatly navigated.  That string data can come from a web page, from a
 disk, or even a serial port, a random-character-generator, or just from HTML
 that's built up in memory and never sees a network or a disk.  It's worth
 reading its documentation[1] and trying its examples to get familiar with
 it.


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


File transfer with python

2010-01-06 Thread Valentin de Pablo Fouce
Hi there,

I hope this is the rigth place, if not please, tell me which is the
right dicussion place. I apologize in such case.

Ok, I am trying to do a very quick application (is home based so is
not a big deal...). My intention is to transfer files from one
computer to another.

I am using several OS (Linux and Windows basicly, but potentially in
the future Mac too), and the computers won't be potentially in the
same network (ok, the most times will... but there will be
exceptions).

My intention is to be able to transfer files from one computer to
another in this environment.

Looking (and surfing) at internet the only suggestion given is to use
low level sockets for this file transfer. Is there another way to do
it, is there any top level library that helps you to do that?

That's a lot!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: please help shrink this each_with_index() implementation

2010-01-06 Thread Carl Banks
On Jan 5, 2:40 pm, Phlip phlip2...@gmail.com wrote:
 On Jan 5, 1:10 pm, Antoine Pitrou solip...@pitrou.net wrote:

 http://docs.python.org/library/functions.html

  Don't forget that the Python documentation is rich and structured.
  And good luck.

 Does it say how to convert a string containing either an integer
 representation, or something alphabetic, into an integer, or a zero,
 in like 1 method call?


No, as he said, it only describes the most important functions.


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


Re: please help shrink this each_with_index() implementation

2010-01-06 Thread Nobody
On Tue, 05 Jan 2010 19:46:01 -0800, alex23 wrote:

 They will tell me how to use except: (which is a good example why a
 program should not use exceptions for its normal control flow if at
 all possible).
 
 Really? Magic functions that coerce and eat errors are a better coding
 technique than exceptions and explicit handling?
 
 What kool-aid have you been drinking?

Maybe he's doing it for a living?

Contract programming seems to work on the basis that the ultimate
requirement is for the client to hand over the money. If, at that point,
the program is still full of bugs, you get to charge extra for upgrades.

Writing robust software from the outset puts you at a competitive
disadvantage to those who understand how the system works.

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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Lie Ryan

On 1/7/2010 2:12 AM, Phlip wrote:

On Jan 5, 10:54 pm, Benjamin Kaplanbenjamin.kap...@case.edu  wrote:


{41: None}[41] ?

In cases where None is a valid result, you can't use it to signal failure..


Asked and answered. You change the sentinel in .fetch to something
else.


I believe Ben Kaplan's point is that if dict slicing returns sentinel 
for missing keys, the slicing syntax would be unusable to differentiate 
{41: sentinel} and {}; if the default sentinel had been None, that would 
make it too easy to forget to reset the sentinel and wrote a buggy code.



But y'all keep on defending the language making your programming
decisions for you!


When designing a language, there are two different ways to signal a 
missing key in a dict: 1) raise an exception or 2) return a sentinel. 
Both are useful for different purpose. One or the other must be the 
default behavior, and the other must give way.


Python decided that the default behavior should be raising exception and 
sentinel have to use the dict.get() method. Simple and clear. The other 
possible behavior (i.e. slicing returns a sentinel while dict.get() 
raises an exception) is arguably just as simple and just as clear; but 
python doesn't do it that way. Why? Because it's part of what makes 
python Python[1].



But y'all keep on defending the language making your programming
decisions for you!


Indeed, the language makes decisions for you; why would you want to use 
a language that nags you for every possible different behavior? I want a 
reasonable default and I want a reasonably easy way to access the 
non-default behaviors.


[1] the essence of which is emboldened as the Zen, which is the broad 
design guideline for both python's syntax and codes written in python. 
Specifically, Errors should never pass silently because missing key 
indicates a possible error and Simple is better than complex because 
returning sentinel for missing keys implies the need for an interface to 
change the sentinel[2].
[2] or become like Java, whose HashMap cannot reliably store null and 
doesn't allow you to specify the sentinel.

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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Lie Ryan

On 1/7/2010 3:41 AM, Phlip wrote:

Steve Holden wrote:


y'all just keep defending the approach to programming that
*you* think is best.


Speak for yourself...


Everyone speaks for themselves, is that a problem?
--
http://mail.python.org/mailman/listinfo/python-list


Re: 3 byte network ordered int, How To ?

2010-01-06 Thread Matthew Barnett

mudit tuli wrote:

For a single byte, struct.pack('B',int)
For two bytes, struct.pack('H',int)
what if I want three bytes ?


Four bytes and then discard the most-significant byte:

struct.pack('I', int)[ : -1]
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess.Popen does not close pipe in an error case

2010-01-06 Thread Nobody
On Tue, 05 Jan 2010 15:50:39 -0800, Steven K. Wong wrote:

 Below, I have a Python script that launches 2 child programs, prog1
 and prog2, with prog1's stdout connected to prog2's stdin via a pipe.
 (It's like executing prog1 | prog2 in the shell.)
 
 If both child programs exit with 0, then the script runs to
 completion. But if prog2 exits with non-0, prog1 does not exit and the
 script hangs (i.e. prog1.poll() always returns None) -- unless I
 uncomment the 2 lines marked by XXX to close prog1.stdout.
 
 I was expecting that I don't have to explicitly close prog1.stdout,
 whether prog2 succeeds or fails. Is the current behavior a bug in the
 subprocess module or is it expected? Or am I doing something wrong?
 
 Thanks.
 
 import subprocess
 import time
 
 # prog1: a program that writes lots of data to the pipe
 cmd = ['zcat', '--force', 'a_large_file']
 prog1 = subprocess.Popen(cmd, bufsize=-1, stdout=subprocess.PIPE)
 
 # prog2: a program that fails without reading much data from the pipe
 cmd = ['python', '-c', 'import time; time.sleep(10); asdf']
 prog2 = subprocess.Popen(cmd, bufsize=-1, stdin=prog1.stdout,
 stdout=open('popen.out', 'w'))

I think that you should close prog1.stdout here. Otherwise, there will
be two readers on the pipe (the calling process and prog2). Even if one of
them dies, there's always the possibility that the caller might eventually
decide to read prog1.stdout itself. If you close it in the caller, when
prog2 terminates there will be no readers, and prog1 will get SIGPIPE (or
write() will fail with EPIPE if SIGPIPE is handled).


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


Re: python xmlrpc client with ssl client certificates and standard modules

2010-01-06 Thread Heikki Toivonen
News123 wrote:
 This will probably work, but it requires the module M2Crypto.
 
 In order to avoid installing M2Crypto an all hosts that want to run the
 script I wondered, whether there is no other solution.
 
 I can do xmlrpc over ssl WITHOUT certificates with following code:
[...]

Please note that if you just use the stdlib it is not secure out of the
box. With Python 2.6 and the ssl module you can make it so, but it
requires some work on your part. See for example
http://www.heikkitoivonen.net/blog/2008/10/14/ssl-in-python-26/

-- 
  Heikki Toivonen - http://heikkitoivonen.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File transfer with python

2010-01-06 Thread Lie Ryan

On 1/7/2010 5:00 AM, Valentin de Pablo Fouce wrote:

My intention is to be able to transfer files from one computer to
another in this environment.


Do you have a USB flashdrive?


Looking (and surfing) at internet the only suggestion given is to use
low level sockets for this file transfer. Is there another way to do
it, is there any top level library that helps you to do that?


Networked file system (e.g. Samba/SMB), File Transfer Protocol (FTP), 
whatever works for you. pysamba is available from sourceforge and there 
is ftplib in the standard library. For most purposes though, you could 
just setup a network shared directory and drag and drop files from the 
file manager.

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


Re: Python books, literature etc

2010-01-06 Thread J
A good point was brought up to me privately, and I agree completely,
that the OP should re-state the request with a bit more specifics...

Since the OP says he is at least familiar with Python, does he need
info on beginner level books that are general purpose, or is he
interested in resources that are more specific (e.g. geared toward web
programming, mathematical analysis, data modeling, etc)

My suggestions were meant just as an example of what I use in the
course of learning something at the basic and intermediate level, once
it goes beyond that, it's useful to know WHAT you intend to do so you
can find the right resources to go in that direction.

Just want to make sure I am not misunderstood or anything :-)

For what it's worth, I also tend to collect technical books for some
reason... My wife is just barely tolerant of my bookshelf full of
things on various computer topics, astronomy, photography, radio and
antenna theory and so forth ;-)  I just let her keep her shoe
collection, and we have a quid pro quo.

Cheers
Jeff



-- 

Mike Ditka  - If God had wanted man to play soccer, he wouldn't have
given us arms. -
http://www.brainyquote.com/quotes/authors/m/mike_ditka.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: suds problem

2010-01-06 Thread Fencer

On 2010-01-06 19:33, Fencer wrote:

Hello, I just started using suds to use web services. First I tried suds
with a very simple web service I had written and was running myself.
That worked fine. Then I tried to use the web services provided by KEGG:
http://soap.genome.jp/KEGG.wsdl
But I get a SAXParseException due to a supposed mis-matched tag when I
try to consume that wsdl with suds. I checked the wsdl in oxygene and it
claims it's valid. What is the problem here? My test program is below
and it's very simple:
from suds.client import Client

url = 'http://soap.genome.jp/KEGG.wsdl'

client = Client(url)

print client

- Fencer


Same problem with reactome:
http://www.reactome.org:8080/caBIOWebApp/services/caBIOService?wsdl

I suppose I'm mis-using suds, maybe some setting that wasn't needed for 
my simple web service but is needed for kegg and reactome.


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


Re: getfirst and re

2010-01-06 Thread Carsten Haese
Victor Subervi wrote:
 I have an automatically generated HTML form from which I need to extract
 data to the script which this form calls (to which the information is
 sent).

Ideally, the script that receives the submitted fields should know how
the form was generated, so it knows what fields to expect. Failing that,
 you should realize that getfirst() is not the only way to access the
contents of a cgi.FieldStorage object.

If you need to know the values of all fields whose names obey a certain
pattern, I recommend you start with a list of all field names in the
FieldStorage object and pick out the ones whose names obey that pattern.
To get the list of field names, you should consider using the .keys()
method of the FieldStorage object.

-Carsten

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


Re: getfirst and re

2010-01-06 Thread Victor Subervi
On Wed, Jan 6, 2010 at 3:09 PM, Carsten Haese carsten.ha...@gmail.comwrote:

 Victor Subervi wrote:
  I have an automatically generated HTML form from which I need to extract
  data to the script which this form calls (to which the information is
  sent).

 Ideally, the script that receives the submitted fields should know how
 the form was generated, so it knows what fields to expect. Failing that,
  you should realize that getfirst() is not the only way to access the
 contents of a cgi.FieldStorage object.

 If you need to know the values of all fields whose names obey a certain
 pattern, I recommend you start with a list of all field names in the
 FieldStorage object and pick out the ones whose names obey that pattern.
 To get the list of field names, you should consider using the .keys()
 method of the FieldStorage object.


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


Astronomy--Programs to Compute Siderial Time?

2010-01-06 Thread W. eWatson
Is there a smallish Python library of basic astronomical functions? 
There are a number of large such libraries that are crammed with 
excessive functions not needed for common calculations.

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


Need help with multiprocessing.manager and passing the manager a multiprocessing.Connection

2010-01-06 Thread Metalone
The following code snippet is taken from the Python 2.6
multiprocessing documentation with a simple change and this change
does not work.  I would like to know how to make it work or something
similar.
I want to pass a Connection object to the MathsClass.
I get the following error on Windows:

Traceback (most recent call last):
  File c:\apps\python26\lib\multiprocessing\managers.py, line 214,
in serve_cl
ient
request = recv()
TypeError: Required argument 'handle' (pos 1) not found


from multiprocessing.managers import BaseManager
from multiprocessing import Pipe# I added this

class MathsClass(object):
def set(self, conn):  # I added the set() function
self.conn = conn
def add(self, x, y):
return x + y
def mul(self, x, y):
return x * y

class MyManager(BaseManager):
pass

MyManager.register('Maths', MathsClass)

if __name__ == '__main__':
parent_conn, child_conn = Pipe()# I added this
manager = MyManager()
manager.start()
maths = manager.Maths()
print maths.add(4, 3) # prints 7
print maths.mul(7, 8) # prints 56
maths.set(child_conn)   # I added this, error is thrown here
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess.Popen does not close pipe in an error case

2010-01-06 Thread Steven K. Wong
On Jan 6, 10:30 am, Nobody nob...@nowhere.com wrote:
 I think that you should close prog1.stdout here. Otherwise, there will
 be two readers on the pipe (the calling process and prog2). Even if one of
 them dies, there's always the possibility that the caller might eventually
 decide to read prog1.stdout itself. If you close it in the caller, when
 prog2 terminates there will be no readers, and prog1 will get SIGPIPE (or
 write() will fail with EPIPE if SIGPIPE is handled).

Thanks for raising a great point, that prog1.stdout is also readable
by the calling process, not just by prog2. Therefore, I agree it makes
sense to explicitly call prog1.stdout.close() in the given code (say
right after the creation of prog2).

Suppose now all the prog1.poll() calls/loop are replaced by a single
prog1.wait(). Without the explicit prog1.stdout.close(), prog1.wait()
will not return, so the calling process still hangs. Because calling
prog1.wait() means that the calling process will naturally never read
prog1.stdout, I would argue that prog1.wait() should close the pipe
before actually waiting for prog1 to exit. Makes sense?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Grant Edwards
On 2010-01-06, Lie Ryan lie.1...@gmail.com wrote:
 On 1/7/2010 3:41 AM, Phlip wrote:
 Steve Holden wrote:

 y'all just keep defending the approach to programming that
 *you* think is best.

 Speak for yourself...

 Everyone speaks for themselves, [...]

Except for the Lorax.  He speaks for the trees.

-- 
Grant Edwards   grante Yow! The SAME WAVE keeps
  at   coming in and COLLAPSING
   visi.comlike a rayon MUU-MUU ...
-- 
http://mail.python.org/mailman/listinfo/python-list


The END (of PyCon early bird registration) is NEAR!

2010-01-06 Thread VanL
Today is the last day of registration for PyCon 2010 at the early bird
rate. Registration at the early bird rate is still good as long as it is
January 6 somewhere in the world.

Register now!  - https://us.pycon.org/2010/register/

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


Re: please help shrink this each_with_index() implementation

2010-01-06 Thread Phlip

Nobody wrote:

On Tue, 05 Jan 2010 19:46:01 -0800, alex23 wrote:


They will tell me how to use except: (which is a good example why a
program should not use exceptions for its normal control flow if at
all possible).

Really? Magic functions that coerce and eat errors are a better coding
technique than exceptions and explicit handling?

What kool-aid have you been drinking?


Maybe he's doing it for a living?

Contract programming seems to work on the basis that the ultimate
requirement is for the client to hand over the money. If, at that point,
the program is still full of bugs, you get to charge extra for upgrades.


Uh, no, right now I'm working with the long-term goal of creating useful modules 
that sustain us equitably.



Writing robust software from the outset puts you at a competitive
disadvantage to those who understand how the system works.


And I, not my language, should pick and chose how to be rigorous. The language 
should not make the decision for me.

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


an't start a thread Pool from another thread

2010-01-06 Thread Glazner
Hi all,
I hope someone can help me with this issue
I see that i can't start a thread Pool from another thread, why?

running python 2.6.4 windowsXP
 import multiprocessing.dummy as threads
 def makePool():
threads.Pool(3)

 makePool()
 import thread
 thread.start_new(makePool,())
Unhandled exception in thread started by function makePool at
0x011EA670
6960
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Phlip
On Jan 6, 10:23 am, Lie Ryan lie.1...@gmail.com wrote:
 On 1/7/2010 3:41 AM, Phlip wrote:

  Steve Holden wrote:

  y'all just keep defending the approach to programming that
  *you* think is best.

  Speak for yourself...

 Everyone speaks for themselves, is that a problem?

Of course not. I was pointing out that Steve is telling me not to
force my programming opinions on everyone...

...while defending Python enforcing programming opinions on everyone.

And now, if everyone will excuse me, I have to get back to writing a
unit-test-to-code ratio of 2:1. Have fun being rigorous, everyone!
-- 
http://mail.python.org/mailman/listinfo/python-list


Mencoder and creating videos

2010-01-06 Thread aditya shukla
Hello Guys,

I have a multiprocessing script which downloads images from 5 urls to 5
directories(usinf multiprocess in python 2.6).The download is for 5 mins.My
aim is to create a video for every minute for each directory and dump the
images as the video is created. My question are , should i use *mencoder.exe
* to create the videos?  and how should i create the videos without
interrupting the download.

Thanks

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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Terry Reedy

On 1/6/2010 1:20 PM, Lie Ryan wrote:


Python decided that the default behavior should be raising exception and
sentinel have to use the dict.get() method. Simple and clear. The other
possible behavior (i.e. slicing returns a sentinel while dict.get()
raises an exception) is arguably just as simple and just as clear; but
python doesn't do it that way. Why? Because it's part of what makes
python Python[1].


The altermatives are not quite equivalent. The current way lets one 
specify the sentinel whereas the alternative does not. There is hardly 
any reason to specify the exception.


tjr

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


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Steven D'Aprano
On Wed, 06 Jan 2010 12:39:36 -0800, Phlip wrote:

 And now, if everyone will excuse me, I have to get back to writing a
 unit-test-to-code ratio of 2:1.

In my experience, that's about half as many unit-tests as needed for full 
code coverage for even a simple class. If you're trying to impress us, 
you have failed.


 Have fun being rigorous, everyone!

You say that as if writing correct code was a bad thing.



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


Re: Introspection

2010-01-06 Thread Jason Scheirer
On Jan 6, 8:38 am, Steven D'Aprano st...@remove-this-
cybersource.com.au wrote:
 On Wed, 06 Jan 2010 06:53:40 -0800, m...@infoserv.dk wrote:
  I'm looking for a way to make a list of string literals in a class.

  Example:

  class A:
     def method(self):
         print 'A','BC'

  ExtractLiterals(A)
  ['A','BC']

  Is this possible? Can anyone point me in the right direction?

 class A:
     def extract_literals(self):
         return A BC.split()
     def method(self):
         print self.extract_literals()

 a = A()
 a.extract_literals()

 --
 Steven

Slightly more robust than Miki's solution insofar as it doesn't
require the source to exist in a .py file:

import types
def extract_literals(klass):
for attr in (getattr(klass, item) for item in dir(klass)):
if isinstance(attr, types.MethodType):
for literal in attr.im_func.func_code.co_consts:
if isinstance(literal, basestring):
yield literal

class full_of_strings(object):
def a(self):
return a, b, c
def b(self):
y, z

print list(extract_literals(full_of_strings))
['a', 'b', 'c', 'y', 'z']

print list(extract_literals(full_of_strings()))
['a', 'b', 'c', 'y', 'z']

Note that this is evil and should be avoided.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: please help shrink this each_with_index() implementation

2010-01-06 Thread Steven D'Aprano
On Wed, 06 Jan 2010 12:12:08 -0800, Phlip wrote:

 And I, not my language, should pick and chose how to be rigorous. The
 language should not make the decision for me.

All languages make that decision for you by making some thing possible 
and other things not. The language designer, not the programmer, decides 
what syntactic features to allow and disallow, what programming styles to 
include, and what functionality to provide as primitives.




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


QDoubleValidator

2010-01-06 Thread Zabin
Hey!

I am new PyQt programmer and want to restrict users to allow only
numeric values into a table and lineedit boxes. I found the
QDoubleValidator class but am unsure as to how to implement it. (I am
a little shaky on the concept of parent and how to define them). Any
help would be much appreciated!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception as the primary error handling mechanism?

2010-01-06 Thread Steve Holden
Phlip wrote:
 On Jan 6, 10:23 am, Lie Ryan lie.1...@gmail.com wrote:
 On 1/7/2010 3:41 AM, Phlip wrote:

 Steve Holden wrote:
 y'all just keep defending the approach to programming that
 *you* think is best.
 Speak for yourself...
 Everyone speaks for themselves, is that a problem?
 
 Of course not. I was pointing out that Steve is telling me not to
 force my programming opinions on everyone...
 
 ...while defending Python enforcing programming opinions on everyone.
 
That's because Python is not a person, and Guido is a better language
designer than both of us put together. No languagecan be all things to
all programmers, and Python represents a set of pragmatic and useful
choices.

 And now, if everyone will excuse me, I have to get back to writing a
 unit-test-to-code ratio of 2:1. Have fun being rigorous, everyone!

Consider yourself excused ;-)

regards
 Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS:http://holdenweb.eventbrite.com/

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


  1   2   3   >