[ANN] guiqwt v2.1.3

2011-05-06 Thread Pierre.RAYBAUT
Hi all,

I am pleased to announce that `guiqwt` v2.1.3 has been released.

Based on PyQwt (plotting widgets for PyQt4 graphical user interfaces) and on 
the scientific modules NumPy and SciPy, guiqwt is a Python library providing 
efficient 2D data-plotting features (curve/image visualization and related 
tools) for interactive computing and signal/image processing application 
development.

Complete change log is now available here:
http://code.google.com/p/guiqwt/wiki/ChangeLog

Documentation with examples, API reference, etc. is available here:
http://packages.python.org/guiqwt/

This version of `guiqwt` includes a demo software, Sift (for Signal and Image 
Filtering Tool), based on `guidata` and `guiqwt`:
http://packages.python.org/guiqwt/sift.html
Windows users may even download the portable version of Sift 0.2.3 to test it 
without having to install anything:
http://code.google.com/p/guiqwt/downloads/detail?name=sift023_portable.zip

When compared to the excellent module `matplotlib`, the main advantages of 
`guiqwt` are:
  * Performance: see 
http://packages.python.org/guiqwt/overview.html#performances
  * Interactivity: see for example 
http://packages.python.org/guiqwt/_images/plot.png
  * Powerful signal processing tools: see for example 
http://packages.python.org/guiqwt/_images/fit.png
  * Powerful image processing tools:
* Real-time contrast adjustment: 
http://packages.python.org/guiqwt/_images/contrast.png
* Cross sections (line/column, averaged and oblique cross sections!): 
http://packages.python.org/guiqwt/_images/cross_section.png
* Arbitrary affine transforms on images: 
http://packages.python.org/guiqwt/_images/transform.png
* Interactive filters: 
http://packages.python.org/guiqwt/_images/imagefilter.png
* Geometrical shapes/Measurement tools: 
http://packages.python.org/guiqwt/_images/image_plot_tools.png
* Perfect integration of `guidata` features for image data editing: 
http://packages.python.org/guiqwt/_images/simple_window.png


But `guiqwt` is more than a plotting library; it also provides:

  * Framework for signal/image processing application development: see 
http://packages.python.org/guiqwt/examples.html

  * And many other features like making executable Windows programs easily 
(py2exe helpers): see http://packages.python.org/guiqwt/disthelpers.html

guiqwt has been successfully tested on GNU/Linux and Windows platforms.

Python package index page:
http://pypi.python.org/pypi/guiqwt/

Documentation, screenshots:
http://packages.python.org/guiqwt/

Downloads (source + Python(x,y) plugin):
http://guiqwt.googlecode.com

Cheers,
Pierre

---

Dr. Pierre Raybaut
CEA - Commissariat à l'Energie Atomique et aux Energies Alternatives
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

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


Wing IDE 4.0.2 released

2011-05-06 Thread Wingware

Hi,

Wingware has released version 4.0.2 of Wing IDE, an integrated development
environment designed specifically for the Python programming language.

Wing IDE is a cross-platform Python IDE that provides a professional code
editor with vi, emacs, and other key bindings, auto-completion, call tips,
refactoring, a powerful graphical debugger, version control, unit testing,
search, and many other features.

**Changes in Version 4.0.2**

* Added introduce variable refactoring operation
* Support for using *.pi files to augment source analysis of *.py files
* Support autocompletion for PySide Qt bindings
* Recognize tags and attributes for HTML5
* Avoid problems with Ubuntu Unity
* Fixed matplotlib support for GtkAgg backend and missing default backend
* Syntax highlight comments in Django template files
* Fixed syntax highlighting for Cython, VHDL, R, and several others
* Fixed failure to replace all search matches near the end of a file
* About 40 other bug fixes and minor improvements

See the change log for details.

**New Features in Version 4.0**

Version 4.0 adds the following new major features:

* Refactoring -- Rename/move symbols, extract to function/method, and 
introduce variable

* Find Uses -- Find all points of use of a symbol
* Diff/Merge -- Graphical file and repository comparison and merge
* Django Support -- Debug Django templates, run Django unit tests, and more
* matplotlib Support -- Maintains live-updating plots in shell and debugger
* Simplified Licensing -- Includes all OSes and adds Support+Upgrades 
subscriptions


Complete change log:   
http://wingware.com/pub/wingide/4.0.2/CHANGELOG.txt

Details on licensing changes:  http://wingware.com/news/2011-02-16

**About Wing IDE**

Wing IDE is an integrated development environment designed specifically for
the Python programming language.  It provides powerful editing, testing, and
debugging features that help reduce development and debugging time, cut down
on coding errors, and make it easier to understand and navigate Python code.
Wing IDE can be used to develop Python code for web, GUI, and embedded
scripting applications.

Wing IDE is available in three product levels:  Wing IDE Professional is
the full-featured Python IDE, Wing IDE Personal offers a reduced feature
set at a low price, and Wing IDE 101 is a free simplified version designed
for teaching beginning programming courses with Python.

Version 4.0 of Wing IDE Professional includes the following major features:

* Professional quality code editor with vi, emacs, and other keyboard
  personalities
* Code intelligence for Python:  Auto-completion, call tips, find uses,
  goto-definition, error indicators, refactoring, smart indent and 
rewrapping,

  and source navigation
* Advanced multi-threaded debugger with graphical UI, command line 
interaction,

  conditional breakpoints, data value tooltips over code, watch tool, and
  externally launched and remote debugging
* Powerful search and replace options including keyboard driven and 
graphical

  UIs, multi-file, wild card, and regular expression search and replace
* Version control integration for Subversion, CVS, Bazaar, git, 
Mercurial, and

  Perforce
* Integrated unit testing with unittest, nose, and doctest frameworks
* Django support:  Debugs Django templates, provides project setup tools,
  and runs Django unit tests
* Many other features including project manager, bookmarks, code snippets,
  diff/merge tool, OS command integration, indentation manager, PyLint
  integration, and perspectives
* Extremely configurable and may be extended with Python scripts
* Extensive product documentation and How-Tos for Django, matplotlib,
  Plone, wxPython, PyQt, mod_wsgi, Autodesk Maya, and many other frameworks

Please refer to http://wingware.com/wingide/features for a detailed listing
of features by product level.

System requirements are Windows 2000 or later, OS X 10.3.9 or later 
(requires
X11 Server), or a recent Linux system (either 32 or 64 bit).  Wing IDE 
supports

Python versions 2.0.x through 3.2.x and Stackless Python.

For more information, see the http://wingware.com/

**Downloads**

Wing IDE Professional and Wing IDE Personal are commercial software and
require a license to run. A free trial can be obtained directly from the
product when launched.

Wing IDE Pro -- Full-featured product:
http://wingware.com/downloads/wingide/4.0

Wing IDE Personal -- A simplified IDE:
http://wingware.com/downloads/wingide-personal/4.0

Wing IDE 101 -- For teaching with Python:
http://wingware.com/downloads/wingide-101/4.0

**Purchasing and Upgrading**

Wing 4.0 requires an upgrade for Wing IDE 2.x and 3.x users at a cost of
1/2 the full product pricing.

Upgrade a license:   https://wingware.com/store/upgrade
Purchase a new license:  https://wingware.com/store/purchase

--

The Wingware Team
Wingware | Python IDE
Advancing Software Development

www.wingware.com

--

Re: 回复: Re: BeautifulSoup import error

2011-05-06 Thread Stefan Behnel

1011_wxy, 06.05.2011 04:29:

发件人: James Mills

On Fri, May 6, 2011 at 11:37 AM, 1011_wxy wrote:

I got a import error when I use Python 3.2 to import BeautifulSoup 3.2.0 .
Is there any differences between Python 3.2 and other version? This is my
first time to use Python3.2 .
And the error message will be as below.


Judging from your tracebacks, it would appear
that BeuituflSoup has not yet been ported to
and/or fixed for Python 3 compatibility.


BeautifulSoup does not work well with Python3.2 .


You can try to convert it using 2to3, though.



I might suggest you take a look at using lxml instead


... which works with all Python versions from 2.3 through 3.2.



which ships with the standard library.


No. While this has been suggested, it will not become part of the stdlib in 
the foreseeable future. It's readily available as a separate package on 
PyPI, though.


Stefan

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


Re: 回复: Re: BeautifulSoup import error

2011-05-06 Thread James Mills
On Fri, May 6, 2011 at 3:57 PM, Stefan Behnel stefan...@behnel.de wrote:
 No. While this has been suggested, it will not become part of the stdlib in
 the foreseeable future. It's readily available as a separate package on
 PyPI, though.

Opps I meant xml.etree :/
My bad!

cheers
James

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


checking if a list is empty

2011-05-06 Thread Jabba Laci
Hi,

If I want to check if a list is empty, which is the more pythonic way?

li = []

(1) if len(li) == 0:
...
or
(2) if not li:
...

Thanks,

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


Re: Python-list Digest, Vol 92, Issue 40

2011-05-06 Thread Nico Grubert



PIL will compile and install if you don't have some development
libraries and then simply not work or not work up to full steam when
used.

To avoid this, you need to install the appropriate libraries, among
which are:

libjpeg-devel
freetype-devel
libpng-devel


Dear Albert

Thank you for your reply.
I did install all these libraries.
Testing it with yum shows:

$ yum install libpng-devel
Package 2:libpng-devel-1.2.10-7.1.el5_5.3.x86_64 already installed and 
latest version
Package 2:libpng-devel-1.2.10-7.1.el5_5.3.i386 already installed and 
latest version


$ yum install libjpeg-devel
Package libjpeg-devel-6b-37.x86_64 already installed and latest version
Package libjpeg-devel-6b-37.i386 already installed and latest version

$ yum install libpng-devel
Package 2:libpng-devel-1.2.10-7.1.el5_5.3.x86_64 already installed and 
latest version
Package 2:libpng-devel-1.2.10-7.1.el5_5.3.i386 already installed and 
latest version



Re-Compiling PIL shows:

$ python setup.py build_ext -i


*** TKINTER support not available
--- JPEG support available
--- ZLIB (PNG/ZIP) support available
--- FREETYPE2 support available
*** LITTLECMS support not available


However, running the selftest still fails:
$ python selftest.py
*** The _imaging C module is not installed

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


Re: checking if a list is empty

2011-05-06 Thread Chris Rebert
On Thu, May 5, 2011 at 11:36 PM, Jabba Laci jabba.l...@gmail.com wrote:
 Hi,

 If I want to check if a list is empty, which is the more pythonic way?

Option (2), IMO.

 li = []

 (1) if len(li) == 0:
 ...

FYI, also equivalent:
if not len(li):
...

 or
 (2) if not li:

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


string formatting

2011-05-06 Thread Jabba Laci
Hi,

Which is the preferred way of string formatting?

(1) the %s is %s % ('sky', 'blue')

(2) the {0} is {1}.format('sky', 'blue')

(3) the {} is {}.format('sky', 'blue')

As I know (1) is old style. (2) and (3) are new but (3) is only
supported from Python 2.7+.

Which one should be used?

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


Re: string formatting

2011-05-06 Thread Steven D'Aprano
On Fri, 06 May 2011 10:00:30 +0200, Web Dreamer wrote:

 Jabba Laci a écrit ce vendredi 6 mai 2011 09:18 dans
 mailman.1229.1304666321.9059.python-l...@python.org :
 
 Hi,
 
 Which is the preferred way of string formatting?
 
 (1) the %s is %s % ('sky', 'blue')
 
 (2) the {0} is {1}.format('sky', 'blue')
 
 (3) the {} is {}.format('sky', 'blue')
 
 As I know (1) is old style. (2) and (3) are new but (3) is only
 supported from Python 2.7+.
 
 Which one should be used?
 
 According to python's documentation, (3) and (2) are preferred and (1)
 is deprecated.

I think you are wrong, % formatting is not deprecated. Do you have a link 
showing otherwise?


[steve@sylar ~]$ python3.2
Python 3.2a1 (r32a1:83318, Aug 12 2010, 02:17:22)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type help, copyright, credits or license for more information.

 import warnings
 warnings.simplefilter(always)
 %d % 42
'42'


I see no DeprecationWarning.



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


Re: string formatting

2011-05-06 Thread Chris Rebert
On Fri, May 6, 2011 at 1:46 AM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 On Fri, 06 May 2011 10:00:30 +0200, Web Dreamer wrote:
 Jabba Laci a écrit ce vendredi 6 mai 2011 09:18 dans
 mailman.1229.1304666321.9059.python-l...@python.org :
 Hi,

 Which is the preferred way of string formatting?

 (1) the %s is %s % ('sky', 'blue')

 (2) the {0} is {1}.format('sky', 'blue')

 (3) the {} is {}.format('sky', 'blue')

 As I know (1) is old style. (2) and (3) are new but (3) is only
 supported from Python 2.7+.

 Which one should be used?

 According to python's documentation, (3) and (2) are preferred and (1)
 is deprecated.

 I think you are wrong, % formatting is not deprecated. Do you have a link
 showing otherwise?

I'm not them, but:
Note: The formatting operations described here [involving %] are
obsolete and may go away in future versions of Python. Use the new
String Formatting [i.e. format()] in new code.
http://docs.python.org/dev/library/stdtypes.html#old-string-formatting-operations

Technically, not formally deprecated, but such a characterization
isn't too far off the mark either.

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


seems like a bug in isinstance()

2011-05-06 Thread dmitrey
hi all,

suppose I've created a class Point in file .../openopt/kernel/Point.py

Consider the code in file .../somewhere/file1.py
from openopt.kernel.Point import Point
p = Point()

now let's pass p into a func from .../openopt/kernel/file2.py and
check
from Point import Point
isinstance(p, Point)

So, it returns False!

p is Point.Point instance at 0x30801b8, while Point is class
openopt.kernel.Point.Point at 0x2048e20

I have Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
D.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Development tools and practices for Pythonistas

2011-05-06 Thread Jonathan Hartley
On Apr 26, 3:39 pm, snorble snor...@hotmail.com wrote:
 I appreciate any advice or guidance anyone has to offer.

The 'Python Project HOWTO' gives good advice in terms of setting up a
new project, what files and directories to create, what to put in
version control, etc:

http://infinitemonkeycorps.net/docs/pph/

Also, where I work we have tried many IDEs, but happily and
productively use GVim and very little else, so don't feel you *have*
to use an IDE.

Best regards,

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


Re: seems like a bug in isinstance()

2011-05-06 Thread Chris Rebert
On Fri, May 6, 2011 at 2:24 AM, dmitrey dmitre...@gmail.com wrote:
 hi all,

 suppose I've created a class Point in file .../openopt/kernel/Point.py

 Consider the code in file .../somewhere/file1.py
 from openopt.kernel.Point import Point
 p = Point()

 now let's pass p into a func from .../openopt/kernel/file2.py and
 check
 from Point import Point
 isinstance(p, Point)

 So, it returns False!

 p is Point.Point instance at 0x30801b8, while Point is class
 openopt.kernel.Point.Point at 0x2048e20

 [Subject: seems like a bug in isinstance()]

This is due to a peculiarity of how (C)Python's import machinery
works; isinstance() is working just fine.
(And if you ever think you've found a bug in Python's built-ins, odds
are you haven't. Python has been around too long, someone ought to
have encountered it earlier, statistically speaking.)

Note how the class is referred to as both Point.Point and
openopt.kernel.Point.Point. This is because you did `from Point import
...` in file2.py, whereas in file1.py you did `from
openopt.kernel.Point import ...`. These 2 different ways of referring
to the same module are sufficient to trick/outsmart (C)Python and
cause it to import the same module twice as 2 separate instances (i.e.
it gets re-executed). Why the import machinery isn't smarter in this
situation, I don't recall.

The output of this should be illuminating:
print(Point, type(p), type(p) is Point, id(Point), id(type(p)))
As this demonstrates, you're dealing with 2 separate definitions of
the same Point class.

Solution: Avoid the implicitly-relative `from Point import ...` style
of import; always use the absolute `from openopt.kernel.Point import
...` style instead. Subsequent imports will thus reference the
already-previously-imported instance of a module rather than importing
a copy of it from scratch again.

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


Re: Development tools and practices for Pythonistas

2011-05-06 Thread Tim Golden

On 06/05/2011 10:51, Jonathan Hartley wrote:

On Apr 26, 3:39 pm, snorblesnor...@hotmail.com  wrote:

I appreciate any advice or guidance anyone has to offer.


The 'Python Project HOWTO' gives good advice in terms of setting up a
new project, what files and directories to create, what to put in
version control, etc:

http://infinitemonkeycorps.net/docs/pph/


I'd forgotten about that. Great resource! Thanks for reminding me...

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


Re: Embedding Python's library as zip file

2011-05-06 Thread Wojtek Mamrak
 Are you calling Py_SetProgramName?  That may help to set sys.prefix
 and sys.exec_prefix.  However, looking at site.py, it appears that
 it's only looking for proper directories.  I don't think it will be
 able to add a site-packages inside a zip archive at all; you will just
 have to add that yourself.

Yes, I have tried Py_SetProgramName, but I am even not sure what
argument (name, path?) should be passed to it and how it will affect
the application.


Some good news.
After simplifying my application I realized, that importing of modules
from the zip archive works well, I only have to add site-packages to
sys.path (it looks like python27.zip/site-packages).

Unfortunately even though I can import Image package, something still
causes applications' sudden death. I will try to figure out what is
the reason of that. As I said, the only non-standard package I am
using is PIL.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PIL: The _imaging C module is not installed

2011-05-06 Thread Christian Heimes
Am 06.05.2011 01:48, schrieb Michel Claveau - MVP:
 Re!
 
 And why the problem no exist with PIL 1.1.6?  (only 1.1.7)
 Is that the version 1.1.6 does not use these libraries?

PIL 1.1.6 also uses its internal C library to speed things up.

For Windows you should use the precompiled packages.
http://www.pythonware.com/products/pil/ offers X86 Windows binaries for
1.1.7. You might run into a problem with 1.1.7 Windows binaries. The
freetype C library references a debug CRT that is not available on all
machines. You can easily patch the _imagingft.pyd file with a hex editor.

Christian

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


Re: seems like a bug in isinstance()

2011-05-06 Thread dmitrey
On May 6, 12:57 pm, Chris Rebert c...@rebertia.com wrote:
 On Fri, May 6, 2011 at 2:24 AM, dmitrey dmitre...@gmail.com wrote:
  hi all,

  suppose I've created a class Point in file .../openopt/kernel/Point.py

  Consider the code in file .../somewhere/file1.py
  from openopt.kernel.Point import Point
  p = Point()

  now let's pass p into a func from .../openopt/kernel/file2.py and
  check
  from Point import Point
  isinstance(p, Point)

  So, it returns False!

  p is Point.Point instance at 0x30801b8, while Point is class
  openopt.kernel.Point.Point at 0x2048e20

  [Subject: seems like a bug in isinstance()]

 This is due to a peculiarity of how (C)Python's import machinery
 works; isinstance() is working just fine.
 (And if you ever think you've found a bug in Python's built-ins, odds
 are you haven't. Python has been around too long, someone ought to
 have encountered it earlier, statistically speaking.)

 Note how the class is referred to as both Point.Point and
 openopt.kernel.Point.Point. This is because you did `from Point import
 ...` in file2.py, whereas in file1.py you did `from
 openopt.kernel.Point import ...`. These 2 different ways of referring
 to the same module are sufficient to trick/outsmart (C)Python and
 cause it to import the same module twice as 2 separate instances (i.e.
 it gets re-executed). Why the import machinery isn't smarter in this
 situation, I don't recall.

 The output of this should be illuminating:
 print(Point, type(p), type(p) is Point, id(Point), id(type(p)))
 As this demonstrates, you're dealing with 2 separate definitions of
 the same Point class.

 Solution: Avoid the implicitly-relative `from Point import ...` style
 of import; always use the absolute `from openopt.kernel.Point import
 ...` style instead. Subsequent imports will thus reference the
 already-previously-imported instance of a module rather than importing
 a copy of it from scratch again.

 Cheers,
 Chris
 --http://rebertia.com

Thanks Cris, however, I had understood reason of the bug and mere
informed Python developers of the bug to fix it.

 print(Point, type(p), type(p) is Point, id(Point), id(type(p)))
(class openopt.kernel.Point.Point at 0x2a29d50, type 'instance',
False, 44211536, 8585344)

The proposed solution of using `from openopt.kernel.Point import ... '
everywhere is already performed but is not nice for me. I have lots of
places like that in my code; also, when I import something from
openopt it performs recursive import of many files including that one
where Point is defined, thus I have cycled imports (well, it somehow
works, but is unstable and may lead to future bugs). Also, writing
from Point import Point is much simpler than using each time the
long string from name1.name2.Point import Point. I think it's Python
developers who have to fix the issue, not users. I have 5 years of
intensive Python experience yet it took same time to me to locate the
bug, because my algorithm got False from isinstance() and went
absolutely different thread from if isinstance(): ... else: 
This bug could be encountered very seldom under rare circumstances and
thus be quite difficult to be located, especially for Python newbies
unawared of this one.

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


Re: checking if a list is empty

2011-05-06 Thread Richard Thomas
On May 6, 7:36 am, Jabba Laci jabba.l...@gmail.com wrote:
 Hi,

 If I want to check if a list is empty, which is the more pythonic way?

 li = []

 (1) if len(li) == 0:
 ...
 or
 (2) if not li:
 ...

 Thanks,

 Laszlo

I prefer (1), it feels more explicit about what I'm testing. The fact
that empty sequences evaluate as false feels like a bit of a quirk to
me. Actually the fact that 0 evaluates as false feels like a bit of a
quirk to me, I more of a use booleans in boolean contexts kind of
programmer.
-- 
http://mail.python.org/mailman/listinfo/python-list


if statement multiple or

2011-05-06 Thread Lutfi Oduncuoglu
Hi,

I am trying to write a script and I realised that I need to use something
like

if ('a' or 'b' or 'c')  not in line:
   print line

But it does not work for. What may be the problem

Thanks,

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


Re: if statement multiple or

2011-05-06 Thread Christian Heimes
Am 06.05.2011 12:47, schrieb Lutfi Oduncuoglu:
 Hi,
 
 I am trying to write a script and I realised that I need to use something
 like
 
 if ('a' or 'b' or 'c')  not in line:
print line
 
 But it does not work for. What may be the problem

if any(s not in line for s in ('a', 'b', 'c')):
   # do something

Christian

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


Re: if statement multiple or

2011-05-06 Thread Albert Hopkins
On Fri, 2011-05-06 at 13:47 +0300, Lutfi Oduncuoglu wrote:
 Hi,
 
 I am trying to write a script and I realised that I need to use
 something like
 
 if ('a' or 'b' or 'c')  not in line:
print line
 

The expression:
('a' or 'b' or 'c') 

evaluates to True

True not in line

Is probably not what you intended.


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


Re: if statement multiple or

2011-05-06 Thread Albert Hopkins
Correction:

('a' or 'b' or 'c') evaluates to 'a'


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


Re: if statement multiple or

2011-05-06 Thread Chris Rebert
On Fri, May 6, 2011 at 4:02 AM, Albert Hopkins mar...@letterboxes.org wrote:
 On Fri, 2011-05-06 at 13:47 +0300, Lutfi Oduncuoglu wrote:
 Hi,

 I am trying to write a script and I realised that I need to use
 something like

 if ('a' or 'b' or 'c')  not in line:
    print line


 The expression:
    ('a' or 'b' or 'c')

 evaluates to True

Not quite:

$ python
Python 2.6.6 (r266:84292, Jan 12 2011, 13:35:00)
 'a' or 'b' or 'c'
'a'


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


Re: checking if a list is empty

2011-05-06 Thread James Mills
On Fri, May 6, 2011 at 4:36 PM, Jabba Laci jabba.l...@gmail.com wrote:
 If I want to check if a list is empty, which is the more pythonic way?

[...]

 (2) if not li:

This is fine.

cheers
James

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


Re: if statement multiple or

2011-05-06 Thread James Mills
On Fri, May 6, 2011 at 8:47 PM, Lutfi Oduncuoglu
lutfioduncuo...@gmail.com wrote:
 I am trying to write a script and I realised that I need to use something
 like

 if ('a' or 'b' or 'c')  not in line:
    print line

 But it does not work for. What may be the problem

You will need to (naively) do this:

if a not in line or b not in line or c not in line:
print line

cheers
James

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


Python packaging (was Development tools and practices for Pythonistas)

2011-05-06 Thread rusi
On May 6, 2:59 pm, Tim Golden m...@timgolden.me.uk wrote:
 On 06/05/2011 10:51, Jonathan Hartley wrote:

  On Apr 26, 3:39 pm, snorblesnor...@hotmail.com  wrote:
  I appreciate any advice or guidance anyone has to offer.

  The 'Python Project HOWTO' gives good advice in terms of setting up a
  new project, what files and directories to create, what to put in
  version control, etc:

 http://infinitemonkeycorps.net/docs/pph/

 I'd forgotten about that. Great resource! Thanks for reminding me...

 TJG

Thanks for that link.

There is one question in this regard that is not covered: package-use
Of course this http://infinitemonkeycorps.net/docs/pph/#id10 is there.
But I am talking of setting up one's python environment.

For example on a linux box how to best optimize using the native
package manager (eg apt/rpm) along with packages from pypi.  And when
one needs to run with multiple pythons how to use virtualenv etc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if statement multiple or

2011-05-06 Thread scattered
On May 6, 7:00 am, Christian Heimes li...@cheimes.de wrote:
 Am 06.05.2011 12:47, schrieb Lutfi Oduncuoglu:

  Hi,

  I am trying to write a script and I realised that I need to use something
  like

  if ('a' or 'b' or 'c')  not in line:
     print line

  But it does not work for. What may be the problem

 if any(s not in line for s in ('a', 'b', 'c')):
    # do something

 Christian

sets could also work

if set('abc')  set(line) == set():
 print line
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if statement multiple or

2011-05-06 Thread Christian Heimes
Am 06.05.2011 14:09, schrieb scattered:
 sets could also work
 
 if set('abc')  set(line) == set():
  print line

Right!
Sets work in this special case, because the OP just wants to search for
a single char. It won't work for longer strings, though.

Also I would write the test as:

if set(line).isdisjoint(abc):
print line

Christian


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


Re: BeautifulSoup import error

2011-05-06 Thread nirinA raseliarison

[1011_wxy]


I got a import error when I use Python 3.2 to import BeautifulSoup 3.2.0


the error i see is a SyntaxError.


Is there any differences between Python 3.2 and other version?


yes. and there is a tool, 2to3, which converts
Python 2.x scripts to work with 3.x.


And the error message will be as below.



from BeautifulSoup import BeautifulSoup

Traceback (most recent call last):
  File pyshell#2, line 1, in module
from BeautifulSoup import BeautifulSoup
  File C:\Python32\BeautifulSoup.py, line 448
raise AttributeError, '%s' object has no attribute '%s' %  
(self.__class__.__name__, attr)

^
SyntaxError: invalid syntax


a quick fix here, change:

raise AttributeError, '%s' object has no attribute '%s'
%(self.__class__.__name__, attr)

to:

raise AttributeError('%s' object has no attribute '%s'
%(self.__class__.__name__, attr))

enclose the string message with parentheses.
at least, you will not get the SyntaxError.
but a better solution is to use 2to3.

i don't use BeautifulSoup, and i'm still stick with
Python2.5.4 on windows, so can't help much.

with Linux, it is just:

  2to3 a_python_file_or_a_dir_package

on windows, i don't know, maybe:

  import subprocess
  subprocess.Popen(('python.exe', 'Tools/Scripts/2to3.py', 'the_package'))

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


Re: PIL: The _imaging C module is not installed

2011-05-06 Thread Wojtek Mamrak
@Michel
use PIL downloaded from here: http://www.lfd.uci.edu/~gohlke/pythonlibs/

regards

2011/5/6 Christian Heimes li...@cheimes.de:
 Am 06.05.2011 01:48, schrieb Michel Claveau - MVP:
 Re!

 And why the problem no exist with PIL 1.1.6?  (only 1.1.7)
 Is that the version 1.1.6 does not use these libraries?

 PIL 1.1.6 also uses its internal C library to speed things up.

 For Windows you should use the precompiled packages.
 http://www.pythonware.com/products/pil/ offers X86 Windows binaries for
 1.1.7. You might run into a problem with 1.1.7 Windows binaries. The
 freetype C library references a debug CRT that is not available on all
 machines. You can easily patch the _imagingft.pyd file with a hex editor.

 Christian

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

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


Re: string formatting

2011-05-06 Thread nn
On May 6, 8:10 am, Web Dreamer webdrea...@nospam.fr wrote:
 Chris Rebert a écrit ce vendredi 6 mai 2011 11:23 dans
 mailman.1230.1304673808.9059.python-l...@python.org :



  I'm not them, but:
  Note: The formatting operations described here [involving %] are
  obsolete and may go away in future versions of Python. Use the new
  String Formatting [i.e. format()] in new code.
 http://docs.python.org/dev/library/stdtypes.html#old-string-formatting-
 operations

  Technically, not formally deprecated, but such a characterization
  isn't too far off the mark either.

 Thanks Chris for the link.

 Indeed, They mention:

 The formatting operations described here are obsolete and may go away in
 future versions of Python. Use the new String Formatting in new code.

 So the proper word is obsolete and in my mind I remembered deprecated
 since they say it could be removed from future versions of python.

 So I should have said obsolete.

 What I would like to know is the difference between deprecated and
 obsolete...

 --
 Web Dreamer

In this context I think obsolete means: Will be removed in some
undetermined version in the future; 3 versions or more from now.
There is also pending deprecation: Will be (usually) removed in the
version after the next. And
deprecated: Will be removed in the next version.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: access to some text string in PDFs

2011-05-06 Thread Robert Pazur
Hi Chris,

thanks for fast reply and all recommendations in helps me much!
as you recommended me i used Pdfminer module to extract the text from pdf
files and then with file.xreadlines() I  allocated the lines where my
keyword (factors in this case) appears.
Till now i extract just the lines but im wondering if its able to extract
whole sentenses (only this)   where my keawords (factors in this case) are
located.

I used following script  

import os, subprocess

path=C:\\PDF  # insert the path to the directory of interest here
dirList=os.listdir(path)
for fname in dirList:
output =fname.rstrip(.pdf) + .txt
subprocess.call([C:\Python26\python.exe, pdf2txt.py, -o, output,
fname])
print fname
file = open(output)
for line in file.xreadlines():
if driving in line:
print(line)

---
Robert Pazur
Mobile : +421 948 001 705
Skype  : ruegdeg


2011/5/6 Chris Rebert c...@rebertia.com

 On Thu, May 5, 2011 at 2:26 PM, Robert Pazur pazurrob...@gmail.com
 wrote:
  Dear all,
  i would like to access some text and count the occurrence as follows 
  I got a lots of pdf with some scientific articles and i want to preview
   which words are usually related with for example determinants
  as an example in the article is a sentence  elevation is the most
  important determinant
  how can i acquire the elevation string?
  of course i dont know where the sententence in article is located or
 which
  particular word could there be
  any suggestions?

 Extract the text using PDFMiner[1], pyPdf[2], or PageCatcher[3]. Then
 use something similar to n-grams on the extracted text, filtering out
 those that don't contain determinant(s). Then just keep a word
 frequency table for the remaining n-grams.

 Not-quite-pseudo-code:
 from collections import defaultdict, deque
 N = 7 # length of n-grams to consider; tune as needed
 buf = deque(maxlen=N)
 targets = frozenset((determinant, determinants))
 steps_until_gone = 0
 word2freq = defaultdict(int)
 for word in words_from_pdf:
if word in targets:
steps_until_gone = N
buf.append(word)
if steps_until_gone:
for related_word in buf:
if related_word not in targets:
word2freq[related_word] += 1
steps_until_gone -= 1
 for count, word in sorted((v,k) for k,v in word2freq.iteritems()):
print(word, ':', count)

 Making this more efficient and less naive is left as an exercise to the
 reader.
 There may very well already be something similar but more
 sophisticated in NLTK[4]; I've never used it, so I dunno.

 [1]: http://www.unixuser.org/~euske/python/pdfminer/index.html
 [2]: http://pybrary.net/pyPdf/
 [3]: http://www.reportlab.com/software/#pagecatcher
 [4]: http://www.nltk.org/

 Cheers,
 Chris
 --
 http://rebertia.com

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


Re: What other languages use the same data model as Python?

2011-05-06 Thread Neil Cerutti
On 2011-05-05, Chris Angelico ros...@gmail.com wrote:
 On Fri, May 6, 2011 at 1:29 AM, Roy Smith r...@panix.com wrote:
 Hey, let's override operator,() and have some fun

 Destroying sanity, for fun and profit.

I was thinking more along the lines of stuff like combining the
envelope pattern (an interface class containing a pointer to an
implementation) with template classes to create type-safe
polymorphic types with specializable, decoupled implementations.
 
A Python programmer just feels depressed that anyone could have a
need for such innovations, though. ;)

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


Re: if statement multiple or

2011-05-06 Thread scattered
On May 6, 8:25 am, Christian Heimes li...@cheimes.de wrote:
 Am 06.05.2011 14:09, schrieb scattered:

  sets could also work

  if set('abc')  set(line) == set():
       print line

 Right!
 Sets work in this special case, because the OP just wants to search for
 a single char. It won't work for longer strings, though.

 Also I would write the test as:

 if set(line).isdisjoint(abc):
     print line

 Christian

Thanks for the tip - I'm still learning Python and was unaware of the
isdisjoint method.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python's library as zip file

2011-05-06 Thread Wojtek Mamrak
 I used py2exe in the past for that, see 
 http://www.py2exe.org/index.cgi/ShippingEmbedded

Thanks for the advice, py2exe seems to be a great tool.
Unfortunately the application stops executing at the same place. It
might be the case of PIL library, I found some entries about it on
py2exe site.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if statement multiple or

2011-05-06 Thread Tim Golden

On 06/05/2011 14:17, scattered wrote:

On May 6, 8:25 am, Christian Heimesli...@cheimes.de  wrote:

Am 06.05.2011 14:09, schrieb scattered:


sets could also work



if set('abc')  set(line) == set():
  print line


Right!
Sets work in this special case, because the OP just wants to search for
a single char. It won't work for longer strings, though.

Also I would write the test as:

if set(line).isdisjoint(abc):
 print line

Christian


Thanks for the tip - I'm still learning Python and was unaware of the
isdisjoint method.


If it's any consolation, I've been using Python for 10 years and
I was unaware of the isdisjoint method. :)

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


Re: PIL: The _imaging C module is not installed

2011-05-06 Thread Nico Grubert


 PIL will compile and install if you don't have some development
 libraries and then simply not work or not work up to full steam when
 used.

 To avoid this, you need to install the appropriate libraries, among
 which are:

 libjpeg-devel
 freetype-devel
 libpng-devel

Dear Albert

Thank you for your reply.
I did install all these libraries.
Testing it with yum shows:

$ yum install libpng-devel
Package 2:libpng-devel-1.2.10-7.1.el5_5.3.x86_64 already installed and 
latest version
Package 2:libpng-devel-1.2.10-7.1.el5_5.3.i386 already installed and 
latest version


$ yum install libjpeg-devel
Package libjpeg-devel-6b-37.x86_64 already installed and latest version
Package libjpeg-devel-6b-37.i386 already installed and latest version

$ yum install libpng-devel
Package 2:libpng-devel-1.2.10-7.1.el5_5.3.x86_64 already installed and 
latest version
Package 2:libpng-devel-1.2.10-7.1.el5_5.3.i386 already installed and 
latest version



Re-Compiling PIL shows:

$ python setup.py build_ext -i


*** TKINTER support not available
--- JPEG support available
--- ZLIB (PNG/ZIP) support available
--- FREETYPE2 support available
*** LITTLECMS support not available


However, running the selftest still fails:
$ python selftest.py
*** The _imaging C module is not installed

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


Re: string formatting

2011-05-06 Thread Steven D'Aprano
On Fri, 06 May 2011 02:23:19 -0700, Chris Rebert wrote:

 On Fri, May 6, 2011 at 1:46 AM, Steven D'Aprano
 steve+comp.lang.pyt...@pearwood.info wrote:
 On Fri, 06 May 2011 10:00:30 +0200, Web Dreamer wrote:
 Jabba Laci a écrit ce vendredi 6 mai 2011 09:18 dans
 mailman.1229.1304666321.9059.python-l...@python.org :
 Hi,

 Which is the preferred way of string formatting?

 (1) the %s is %s % ('sky', 'blue')

 (2) the {0} is {1}.format('sky', 'blue')

 (3) the {} is {}.format('sky', 'blue')

 As I know (1) is old style. (2) and (3) are new but (3) is only
 supported from Python 2.7+.

 Which one should be used?

 According to python's documentation, (3) and (2) are preferred and (1)
 is deprecated.

 I think you are wrong, % formatting is not deprecated. Do you have a
 link showing otherwise?
 
 I'm not them, but:
 Note: The formatting operations described here [involving %] are
 obsolete and may go away in future versions of Python. Use the new
 String Formatting [i.e. format()] in new code.
 http://docs.python.org/dev/library/stdtypes.html#old-string-formatting-
operations
 
 Technically, not formally deprecated, but such a characterization isn't
 too far off the mark either.

Not deprecated at all. In context, deprecation *is* a formal process.

In any case, on occasions that the issue has been raised, there has been 
considerable community objection to removal of % formatting. Guido might 
want to remove it, but I wouldn't bet on it happening before Python 4000.

It's perfectly safe to continue using % formatting, if you choose.



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


Re: string formatting

2011-05-06 Thread Steven D'Aprano
On Fri, 06 May 2011 14:10:17 +0200, Web Dreamer wrote:

 What I would like to know is the difference between deprecated and
 obsolete...


Writing x*x instead of x**2 is obsolete, but it will never go away.

Writing apply(func, args) instead of func(*args) is deprecated. It has 
gone away.

Obsolete is a value judgment you are welcome to ignore. Deprecation is a 
formal process that warns you that your code *will* break in the future.

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


Wing IDE 4.0.2 Released

2011-05-06 Thread Wingware

Hi,

Wingware has released version 4.0.2 of Wing IDE, an integrated development
environment designed specifically for the Python programming language.

Wing IDE is a cross-platform Python IDE that provides a professional code
editor with vi, emacs, and other key bindings, auto-completion, call tips,
refactoring, a powerful graphical debugger, version control, unit testing,
search, and many other features.

**Changes in Version 4.0.2**

* Added introduce variable refactoring operation
* Support for using *.pi files to augment source analysis of *.py files
* Support autocompletion for PySide Qt bindings
* Recognize tags and attributes for HTML5
* Avoid problems with Ubuntu Unity
* Fixed matplotlib support for GtkAgg backend and missing default backend
* Syntax highlight comments in Django template files
* Fixed syntax highlighting for Cython, VHDL, R, and several others
* Fixed failure to replace all search matches near the end of a file
* About 40 other bug fixes and minor improvements

See the change log for details.

**New Features in Version 4.0**

Version 4.0 adds the following new major features:

* Refactoring -- Rename/move, extract to function/method, and introduce 
variable

* Find Uses -- Find all points of use of a symbol
* Diff/Merge -- Graphical file and repository comparison and merge
* Django Support -- Debug Django templates, run Django unit tests, and more
* matplotlib Support -- Maintains live-updating plots in shell and debugger
* Simplified Licensing -- Includes all OSes and adds Support+Upgrades 
subscriptions


Complete change log:   
http://wingware.com/pub/wingide/4.0.2/CHANGELOG.txt

Details on licensing changes:  http://wingware.com/news/2011-02-16

**About Wing IDE**

Wing IDE is an integrated development environment designed specifically for
the Python programming language.  It provides powerful editing, testing, and
debugging features that help reduce development and debugging time, cut down
on coding errors, and make it easier to understand and navigate Python code.
Wing IDE can be used to develop Python code for web, GUI, and embedded
scripting applications.

Wing IDE is available in three product levels:  Wing IDE Professional is
the full-featured Python IDE, Wing IDE Personal offers a reduced feature
set at a low price, and Wing IDE 101 is a free simplified version designed
for teaching beginning programming courses with Python.

Version 4.0 of Wing IDE Professional includes the following major features:

* Professional quality code editor with vi, emacs, and other keyboard
  personalities
* Code intelligence for Python:  Auto-completion, call tips, find uses,
  goto-definition, error indicators, refactoring, smart indent and 
rewrapping,

  and source navigation
* Advanced multi-threaded debugger with graphical UI, command line 
interaction,

  conditional breakpoints, data value tooltips over code, watch tool, and
  externally launched and remote debugging
* Powerful search and replace options including keyboard driven and 
graphical

  UIs, multi-file, wild card, and regular expression search and replace
* Version control integration for Subversion, CVS, Bazaar, git, 
Mercurial, and

  Perforce
* Integrated unit testing with unittest, nose, and doctest frameworks
* Django support:  Debugs Django templates, provides project setup tools,
  and runs Django unit tests
* Many other features including project manager, bookmarks, code snippets,
  diff/merge tool, OS command integration, indentation manager, PyLint
  integration, and perspectives
* Extremely configurable and may be extended with Python scripts
* Extensive product documentation and How-Tos for Django, matplotlib,
  Plone, wxPython, PyQt, mod_wsgi, Autodesk Maya, and many other frameworks

Please refer to http://wingware.com/wingide/features for a detailed listing
of features by product level.

System requirements are Windows 2000 or later, OS X 10.3.9 or later 
(requires
X11 Server), or a recent Linux system (either 32 or 64 bit).  Wing IDE 
supports

Python versions 2.0.x through 3.2.x and Stackless Python.

For more information, see the http://wingware.com/

**Downloads**

Wing IDE Professional and Wing IDE Personal are commercial software and
require a license to run. A free trial can be obtained directly from the
product when launched.

Wing IDE Pro -- Full-featured product:
http://wingware.com/downloads/wingide/4.0

Wing IDE Personal -- A simplified IDE:
http://wingware.com/downloads/wingide-personal/4.0

Wing IDE 101 -- For teaching with Python:
http://wingware.com/downloads/wingide-101/4.0

**Purchasing and Upgrading**

Wing 4.0 requires an upgrade for Wing IDE 2.x and 3.x users at a cost of
1/2 the full product pricing.

Upgrade a license:   https://wingware.com/store/upgrade
Purchase a new license:  https://wingware.com/store/purchase

--

The Wingware Team
Wingware | Python IDE
Advancing Software Development

www.wingware.com

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


Re: Python IDE/text-editor

2011-05-06 Thread Alec Taylor
No thanks, it's shareware, doesn't included embedded python
interpreter out-of-the-box, and isn't portable.

On Fri, May 6, 2011 at 2:39 PM, JussiJ jus...@zeusedit.com wrote:
 On Apr 16, 1:20 pm, Alec Taylor alec.tayl...@gmail.com wrote:

 I'm looking for an IDE which offers syntax-highlighting,
 code-completion, tabs,

 The Zeus editor does offers all these features:

    http://www.zeusedit.com/

 Zeus is also scriptable and Zeus scripts can be written in Python.

 Zeus also does Python smart indenting and code folding.

 an embedded interpreter and which is portable

 Zeus does not have an embedded Python interpreter, but by using
 something like tee.exe it should be possible to emulate this:

    http://www.zeusedit.com/zforum/viewtopic.php?t=3156

 (for running from USB on Windows).

 Zeus is a Windows editor but it is not a Protable application.

 NOTE: Zeus is shareware.

 Jussi Jumppanen
 Author: Zeus for Windows
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: string formatting

2011-05-06 Thread MRAB

On 06/05/2011 08:18, Jabba Laci wrote:

Hi,

Which is the preferred way of string formatting?

(1) the %s is %s % ('sky', 'blue')

(2) the {0} is {1}.format('sky', 'blue')

(3) the {} is {}.format('sky', 'blue')

As I know (1) is old style. (2) and (3) are new but (3) is only
supported from Python 2.7+.

Which one should be used?


I use Python 3, and I tend to use (3), unless I need to use the same
value more than once.
--
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting

2011-05-06 Thread Adam Tauno Williams
On Fri, 2011-05-06 at 15:58 +0100, MRAB wrote:
 On 06/05/2011 08:18, Jabba Laci wrote:
  Which is the preferred way of string formatting?
  (1) the %s is %s % ('sky', 'blue')
  (2) the {0} is {1}.format('sky', 'blue')
  (3) the {} is {}.format('sky', 'blue')
  As I know (1) is old style. (2) and (3) are new but (3) is only
  supported from Python 2.7+.
  Which one should be used?
 I use Python 3, and I tend to use (3), unless I need to use the same
 value more than once.

I like:

'my name is {name}'.format(name='Adam')

That makes things clearest, IMO.

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


Re: string formatting

2011-05-06 Thread MRAB

On 06/05/2011 16:06, Adam Tauno Williams wrote:

On Fri, 2011-05-06 at 15:58 +0100, MRAB wrote:

On 06/05/2011 08:18, Jabba Laci wrote:

Which is the preferred way of string formatting?
(1) the %s is %s % ('sky', 'blue')
(2) the {0} is {1}.format('sky', 'blue')
(3) the {} is {}.format('sky', 'blue')
As I know (1) is old style. (2) and (3) are new but (3) is only
supported from Python 2.7+.
Which one should be used?

I use Python 3, and I tend to use (3), unless I need to use the same
value more than once.


I like:

'my name is {name}'.format(name='Adam')

That makes things clearest, IMO.


I wouldn't do that for a short piece of text, but for a much longer
piece of text with multiple values, it does make it a lot clearer.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Coolest Python recipe of all time

2011-05-06 Thread Steven D'Aprano
On Mon, 02 May 2011 10:33:31 -0700, Raymond Hettinger wrote:

 I think it is time to give some visibility to some of the instructive
 and very cool recipes in ActiveState's python cookbook.
[...]
 What are your favorites?


I'm not sure if favourite is the right word, but I'm amazed by this one: 
McCarthy's amb (ambiguous) operator.

http://code.activestate.com/recipes/577368

Here's how I might use it to solve the problem if making change. In 
Australian currency, I have 5, 10, 20, 50 cent and $1 and $2 coins. 
Ignoring the dollar coins, how can I make up change for any multiple of 
five cents up to a dollar?

Suppose I have more 5 cent coins that I can deal with, and I want to make 
sure I hand out at least three of them. Here's how to make 45 cents worth 
of change:

 amb = Amb()
 a = amb(range(3, 21))  # number of 5 cent coins
 b = amb(range(11))  # number of 10 cent coins
 c = amb(range(6))  # number of 20 cent coins
 d = amb(range(3))  # number of 50 cent coins
 for _ in amb(lambda a,b,c,d: 5*a+10*b+20*c+50*d == 45):
... print a, b, c, d
...
3 1 1 0
3 3 0 0
5 0 1 0
5 2 0 0
7 1 0 0
9 0 0 0


Suppose I have some words, and want to put them together so that there 
are a certain number of vowels:

 amb = Amb()
 a = amb(['quick', 'slow', 'hungry', 'wise-old'])
 b = amb(['fox', 'hare', 'turtle', 'kangaroo'])
 c = amb(['lazy', 'stupid', 'sleepy', 'confused'])
 d = amb(['dog', 'aardvark', 'sloth', 'wombat'])

 def test(a, b, c, d):
... s = The %s brown %s jumped over the %s %s. % (a, b, c, d)
... num_vowels = sum(s.count(c) for c in 'aeiou')
... return num_vowels in (12, 18, 19)
...
 for _ in amb(test):
... print a, b, c, d
...
quick fox lazy sloth
quick fox lazy dog
quick kangaroo stupid aardvark
[...more solutions cut for brevity]
hungry kangaroo confused aardvark



As written, amb is just a brute-force solver using more magic than is 
good for any code, but it's fun to play with.



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


Re: seems like a bug in isinstance()

2011-05-06 Thread Ian Kelly
On Fri, May 6, 2011 at 4:20 AM, dmitrey dmitre...@gmail.com wrote:
 Thanks Cris, however, I had understood reason of the bug and mere
 informed Python developers of the bug to fix it.

No you haven't.  Few if any Python developers make a habit of reading
this newsgroup.  To actually report the issue so that it might get
fixed, you need to add it to the issue tracker at
http://bugs.python.org

Anyway, I played around with this a little and was unable to reproduce
it, so I suspect the issue is actually a bit more complicated than
what Chris is describing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coolest Python recipe of all time

2011-05-06 Thread geremy condra
On Fri, May 6, 2011 at 9:59 AM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 On Mon, 02 May 2011 10:33:31 -0700, Raymond Hettinger wrote:

 I think it is time to give some visibility to some of the instructive
 and very cool recipes in ActiveState's python cookbook.
 [...]
 What are your favorites?


 I'm not sure if favourite is the right word, but I'm amazed by this one:
 McCarthy's amb (ambiguous) operator.

 http://code.activestate.com/recipes/577368

 Here's how I might use it to solve the problem if making change. In
 Australian currency, I have 5, 10, 20, 50 cent and $1 and $2 coins.
 Ignoring the dollar coins, how can I make up change for any multiple of
 five cents up to a dollar?

 Suppose I have more 5 cent coins that I can deal with, and I want to make
 sure I hand out at least three of them. Here's how to make 45 cents worth
 of change:

 amb = Amb()
 a = amb(range(3, 21))  # number of 5 cent coins
 b = amb(range(11))  # number of 10 cent coins
 c = amb(range(6))  # number of 20 cent coins
 d = amb(range(3))  # number of 50 cent coins
 for _ in amb(lambda a,b,c,d: 5*a+10*b+20*c+50*d == 45):
 ...     print a, b, c, d
 ...
 3 1 1 0
 3 3 0 0
 5 0 1 0
 5 2 0 0
 7 1 0 0
 9 0 0 0


 Suppose I have some words, and want to put them together so that there
 are a certain number of vowels:

 amb = Amb()
 a = amb(['quick', 'slow', 'hungry', 'wise-old'])
 b = amb(['fox', 'hare', 'turtle', 'kangaroo'])
 c = amb(['lazy', 'stupid', 'sleepy', 'confused'])
 d = amb(['dog', 'aardvark', 'sloth', 'wombat'])

 def test(a, b, c, d):
 ...     s = The %s brown %s jumped over the %s %s. % (a, b, c, d)
 ...     num_vowels = sum(s.count(c) for c in 'aeiou')
 ...     return num_vowels in (12, 18, 19)
 ...
 for _ in amb(test):
 ...     print a, b, c, d
 ...
 quick fox lazy sloth
 quick fox lazy dog
 quick kangaroo stupid aardvark
 [...more solutions cut for brevity]
 hungry kangaroo confused aardvark



 As written, amb is just a brute-force solver using more magic than is
 good for any code, but it's fun to play with.

I use a similar technique *a lot* for various kinds of constraint
solvers, but I have yet to come up with a really satisfying spelling
for it. Have you looked at the way this is done in Sage?

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


setuptools for 64-bit 2.7.1 on 64-bit Windows 7?

2011-05-06 Thread Dick Bridges
Hi all,

 

Can someone provide some search terms I can use to find guidelines for
installing modules for my 'stock' 64-bit r 271:86832, Nov 27, 2010 [MSC
v.1500 64 bit (AMD)] on Win32. Host is 64-bit Windows 7.

 

My goal is to install suds. Period. That's all. So far I've spent the better
part of two days trying to figure out how to make

python setup.py install

actually work. Current error involves ...no module named setuptools and,
of course all I can find is the 32-bit setuptools-0.6c11.win32-py2.7.exe
which fails with Python version 2.7 required, which was not found in the
registry.

 

There's nothing new here - all of this has appeared in various forums over
the last few years - but none I have found contains an actual answer.

 

Simple question: Is it true that no setuptools (or any other module
installer) exists for 64-bit python 2.7.1? If there is an installer that
works, what terms might I use to Google for information on how to acquire
and install it?

 

 Regards,

   Dick Bridges

  (\(\ Western Digital

¸. ..  

 (  . .)  The opinions and data in this missive are my own and do not
necessarily

|   ° ¡  represent Western Digital positions, strategies, or opinions.

¿ ;  

c?.UJ   Glenda: http://glenda.cat-v.org/gallery/
http://glenda.cat-v.org/gallery/ 

 

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


Re: PIL: The _imaging C module is not installed

2011-05-06 Thread Irmen de Jong

On 06-05-11 15:56, Nico Grubert wrote:



However, running the selftest still fails:
$ python selftest.py
*** The _imaging C module is not installed



I had this happening to me as well someday.
I recall that first installing it (python setup.py install), and then 
rerunning selftest, solved that error.


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


Re: Hello Friends

2011-05-06 Thread Alister Ware
On Thu, 05 May 2011 21:55:22 -0700, Ashraf Ali wrote:

 Do you need legal help.If so Please visit
 www.chicagopersonalinjurylawyerz.blogspot.com

sorry I would only use a reputable firm
(spaming a news group makes you disreputable by default)



-- 
My NOSE is NUMB!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-06 Thread Chris Torek
 John Nagle wrote:
 A reasonable compromise would be that is is treated as == on
 immutable objects.

(Note: I have no dog in this fight, I would be happy with a changed
is or with the current one -- leaky abstractions are fine with
me, provided I am told *when* they may -- or sometimes may not --
leak. :-) )

 On 5/5/2011 3:06 AM, Gregory Ewing wrote:
 That wouldn't work for tuples, which can contain references
 to other objects that are not immutable.

On Thu, May 5, 2011 at 9:41 AM, John Nagle na...@animats.com wrote:
 Such tuples are still identical, even if they
 contain identical references to immutable objects.

In article mailman.1196.1304613911.9059.python-l...@python.org
Ian Kelly  ian.g.ke...@gmail.com wrote:
 a = (1, 2, [3, 4, 5])
 b = (1, 2, [3, 4, 5])
 a == b
True
 a is b  # Using the proposed definition
True

I believe that John Nagle's proposal would make a is b false,
because while a and b are both immutable, they contain *different*
refernces to *mutable* objects (thus failing the identical
references to immutable objects part of the claim).

On the other hand, should one do:

L = [3, 4, 5]
a = (1, 2, L)
b = (1, 2, L)

then a is b should (I say) be True under the proposal -- even
though they contain (identical) references to *mutable* objects.
Loosely speaking, we would define the is relation as:

(x is y) if and only if
   (id(x) == id(y)
   or
   (x is immutable and y is immutable and
(for all components xi and yi of x, xi is yi)))

In this case, even if the tuples a and b have different id()s,
we would find that both have an immutable type, and both have
components -- in this case, numbered, subscriptable tuple elements,
but instances of immutable class types like decimal.Decimal would
have dictionaries instead -- and thus we would recursively apply
the modified is definition to each element.  (For tuples, the
all components implies that the lengths must be equal; for class
instances, it implies that they need to have is-equal attributes,
etc.)

It's not entirely clear to me whether different immutable classes
(i.e., different types) but with identical everything-else should
compare equal under this modified is.  I.e., today:

$ cp /usr/lib/python2.?/decimal.py /tmp/deccopy.py
$ python
...
 sys.path.append('/tmp')
 import decimal
 import deccopy
 x = decimal.Decimal('1')
 y = deccopy.Decimal('1')
 print x, y
1 1
 x == y
False

and obviously x is y is currently False:

 type(x)
class 'decimal.Decimal'
 type(y)
class 'deccopy.Decimal'

However, even though the types differ, both x and y are immutable
[%] and obviously (because I copied the code) they have all the
same operations.  Since they were both created with the same starting
value, x and y will behave identically given identical treatment.
As such, it might be reasonable to ask that x is y be True
rather than False.

[% This is not at all obvious -- I have written an immutable class,
and it is pretty easy to accidentally mutate an instance inside
the class implementation.  There is nothing to prevent this in
CPython, at least.  If there were a minor bug in the decimal.Decimal
code such that x.invoke_bug() modified x, then x would *not* be
immutable, even though it is intended to be.  (As far as I know
there are no such bugs in decimal.Decimal, it's just that I had
them in my Money class.)]
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-06 Thread Chris Torek
In article GOmwp.13554$vp.9...@newsfe14.iad
harrismh777  harrismh...@charter.net wrote:
There may be some language somewhere that does pass-by-reference which 
is not implemented under the hood as pointers, but I can't think of 
any...   'cause like I've been saying, way down under the hood, we only 
have direct and indirect memory addressing in today's processors. EOS.

There have been Fortran compilers that implemented modification of
variables via value-result rather than by-reference.

This is perhaps best illustrated by some code fragments:

  SUBROUTINE FOO(X, Y)
  INTEGER X, Y
  ...
  X = 3
  Y = 4
  RETURN

  SUBROUTINE BAR(A)
  FOO(A, 0)
  RETURN

might compile to the equivalent of the following C code:

void foo(int *x0, int *y0) {
int x = *x0, y = *y0;
...
*x0 = x;
*y0 = y;
}

void bar(int *a0) {
int a = *a0;
int temp = 0;
foo(a, temp);
*a0 = a;
}

In order to allow both by-reference and value-result, Fortran
forbids the programmer to peek at the machinery.  That is, the
following complete program is invalid:

  SUBROUTINE PEEK(X)
  INTEGER X, GOTCHA
  COMMON /BLOCK/ GOTCHA
  PRINT *, 'INITIALLY GOTCHA = ', GOTCHA
  X = 4
  PRINT *, 'AFTER X=4 GOTCHA = ', GOTCHA
  RETURN

  PROGRAM MAIN
  INTEGER GOTCHA
  COMMON /BLOCK/ GOTCHA
  GOTCHA = 3
  PEEK(GOTCHA)
  PRINT *, 'FINALLY   GOTCHA = ', GOTCHA
  STOP
  END

(It has been so long since I used Fortran that the above may not
be quite right in ways other than the one intended.  Please forgive
small errors. :-) )

The trick in subroutine peek is that it refers to both a global
variable (in Fortran, simulated with a common block) and a dummy
variable (as it is termed in Fortran) -- the parameter that aliases
the global variable -- in such a way that we can see *when* the
change happens.  If gotcha starts out set to 3, remains 3 after
assignment to x, and changes to 4 after peek() returns, then peek()
effectively used value-result to change the parameter.  If, on the
other hand, gotcha became 4 immediately after the assignment to
x, then peek() effectively used by-reference.

The key take-away here is not so much the trick by which we peeked
inside the implementation (although peeking *is* useful in solving
the murder mystery we have after some program aborts with a
core-dump or what-have-you), but rather the fact that the Fortran
language proper forbids us from peeking at all.  By forbidding it
-- by making the program illegal -- the language provide implementors
the freedom to use *either* by-reference or value-result.  All
valid Fortran programs behave identically under either kind of
implementation.

Like it or not, Python has similar defined as undefined grey
areas: one is not promised, for instance, whether the is operator
is always True for small integers that are equal (although it is
in CPython), nor when __del__ is called (if ever), and so on.  As
with the Python-named-Monty, we have rigidly defined areas of
doubt and uncertainty.  These exist for good reasons: to allow
different implementations.
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coolest Python recipe of all time

2011-05-06 Thread Ian Kelly
On Fri, May 6, 2011 at 10:59 AM, Steven D'Aprano
steve+comp.lang.pyt...@pearwood.info wrote:
 As written, amb is just a brute-force solver using more magic than is
 good for any code, but it's fun to play with.

This isn't really amb; as you said it's just a brute-force solver with
some weird syntax.  The whole point of amb is to enable
non-deterministic programming, such as this:

def find_values():
a = amb(1, 3, 5)
b = amb(2, 4, 8)
if a + b = 5:
fail()
if not is_prime(a * b + 1):
fail()
c = amb(a, b, None)
if c is not None and c  5:
fail()
return a, b, c

The amb engine would conceptually execute this function for every
possible combination of a, b, and c, pruning away the combinations
that fail at some point, and arbitrarily returning one of the
remaining combinations.  So find_values() here might return (3, 4,
None) after failing at one point or another on (1, 2); (1, 4); (1, 8);
(3, 2); (3, 4, 3); and (3; 4; 4).

Note in particular that the declaration of c is not easily expressible
using the Python recipe.

This is typically implemented using continuations, and I'm not sure
whether a true amb could actually be achieved in Python without adding
continuations or flow-control macros to the language.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hello Friends

2011-05-06 Thread John Bokma
Alister Ware alister.w...@ntlworld.com writes:

 On Thu, 05 May 2011 21:55:22 -0700, Ashraf Ali wrote:

 Do you need legal help.If so Please visit
 

 sorry I would only use a reputable firm
 (spaming a news group makes you disreputable by default)

Does it make you disreputable? Since you just repeated the spamvertized
URL...

-- 
John Bokma   j3b

Blog: http://johnbokma.com/Facebook: http://www.facebook.com/j.j.j.bokma
Freelance Perl  Python Development: http://castleamber.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-06 Thread Chris Torek
In article iq1e0j02...@news2.newsguy.com I wrote, in part:
Like it or not, Python has similar defined as undefined grey
areas: one is not promised, for instance, whether the is operator
is always True for small integers that are equal (although it is
in CPython), nor when __del__ is called (if ever), and so on.  As
with the Python-named-Monty, we have rigidly defined areas of
doubt and uncertainty.  These exist for good reasons: to allow
different implementations.

Oops, attribution error: this comes from Douglas Adams rather
than Monty Python.
-- 
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)  http://web.torek.net/torek/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting

2011-05-06 Thread harrismh777

Steven D'Aprano wrote:

It's perfectly safe to continue using % formatting, if you choose.



   I would hope so, since its the way in most of the books, much of the 
doc and a majority of the code...


   I don't really like the old style, not because there is anything 
wrong with it, because its an obvious carry-over from the cryptic 
formatting style of 'C' printf(), and others. It seems to me that the 
purpose of formatting is to make output clear, and therefore the output 
formatting style itself should be clear and clean.

   On the other hand, among the three styles listed by the OP

(1) the %s is %s % ('sky', 'blue')

(2) the {0} is {1}.format('sky', 'blue')

(3) the {} is {}.format('sky', 'blue')

...  they all *feel* good... I mean, they're all clear, clean, 
precise...


   On the other hand, while any 'C' programmer is able to see instantly 
that (1) is a some type of formatting construct, (2)  (3) are clear and 
obvious formatting constructs, even for newbies and esp. for non 'C' 
programmers.


   On the other hand, at this point, it seems that this is personal 
preference issue completely. So, if the book says you can do it, and 
there is no formal deprecation process in the works, feel free to 
express yourself with the style that best suits 'you'.


   On the other hand,.   :)



kind regards,
m harris

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


Re: What other languages use the same data model as Python?

2011-05-06 Thread harrismh777

Chris Torek wrote:

with the Python-named-Monty, we have rigidly defined areas of
doubt and uncertainty.  These exist for good reasons: to allow
different implementations.

Oops, attribution error: this comes from Douglas Adams rather
than Monty Python.


Well, its certainly Monte-esq I like it, whoever said it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Terry Reedy

On 5/6/2011 7:34 AM, James Mills wrote:

On Fri, May 6, 2011 at 4:36 PM, Jabba Lacijabba.l...@gmail.com  wrote:

If I want to check if a list is empty, which is the more pythonic way?


[...]


(2) if not li:


This is fine.


This is the intended way. Anything in addition is extra noise and wasted 
calculation. In other words, let Python do the boilerplate work for you.


--
Terry Jan Reedy

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


Re: Coolest Python recipe of all time

2011-05-06 Thread Ian Kelly
On Fri, May 6, 2011 at 12:36 PM, Ian Kelly ian.g.ke...@gmail.com wrote:
 This is typically implemented using continuations, and I'm not sure
 whether a true amb could actually be achieved in Python without adding
 continuations or flow-control macros to the language.

I stand corrected.  After poking around a bit more I found this recipe
that is designed for unit-testing but implements amb beautifully.

http://lackingrhoticity.blogspot.com/2009/08/how-to-do-model-checking-of-python-code.html

My code from the previous post using this recipe:

def find_values(chooser):
def amb(*choices):
return chooser.choose(choices)
def require(x):
if not x:
amb()
a = amb(1, 3, 5)
b = amb(2, 4, 8)
require(a + b  5)
require(is_prime(a * b + 1))
c = amb(a, b, None)
require(c is None or c = 5)
return a, b, c

check(find_values)

The one downside is that the check function (again, designed for
unit-testing) does not provide any way to retrieve the returned
values, but that is easily solved by rewriting as a generator.

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


Re: string formatting

2011-05-06 Thread harrismh777

harrismh777 wrote:OP wrote:


(1) the %s is %s % ('sky', 'blue')

(2) the {0} is {1}.format('sky', 'blue')

(3) the {} is {}.format('sky', 'blue')


   On the other hand, consider this 3.x code snip:

   print(the %s is %d % ('sky', 'blue'))


   That formatting will throw an exception, because the format 
construct is restricting the format entry to be a number, which 'blue' 
clearly isn't


   The following print() is better, because *any* time or *most* types 
can be substituted and the 'polymorphism' of Python kicks in allowing 
for that, as so:


print(the {} is {}.format('sky', 3.4))

print(the {} is {}.format('sky', 'blue'))


l=['cloudy', 'today']
print(the {} is {}.format('sky', l))


   On the other hand, :)


kind regards,
m harris
--
http://mail.python.org/mailman/listinfo/python-list


Python 3 dict question

2011-05-06 Thread dmitrey
hi all,
suppose I have Python dict myDict and I know it's not empty.
I have to get any (key, value) pair from the dict (no matter which
one) and perform some operation.
In Python 2 I used mere
key, val = myDict.items()[0]
but in Python 3 myDict.items() return iterator.
Of course, I could use
for key, val in myDict.items():
   do_something
   break
but maybe there is any better way?

Thank you in advance, D.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread harrismh777

Terry Reedy wrote:

(2) if not li:


This is fine.


This is the intended way. Anything in addition is extra noise and wasted
calculation. In other words, let Python do the boilerplate work for you.


   I agree, but I don't like it.

... if not li  says nothing about what li is supposed to 'be' and 
implies in any case that li does not exist, or worse is some kind of 
boolean.


   li is in fact an empty list [] and will identify as such, and of 
course (as a list object) has all of the attributes and methods of a list...


   Why not have a list method that makes this more explicit:


   if not li.emptylist()

   if not li.empty([])

  there might be others...



kind regards,
m harris


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


Re: Python 3 dict question

2011-05-06 Thread Chris Rebert
On Fri, May 6, 2011 at 12:40 PM, dmitrey dmitre...@gmail.com wrote:
 hi all,
 suppose I have Python dict myDict and I know it's not empty.
 I have to get any (key, value) pair from the dict (no matter which
 one) and perform some operation.
 In Python 2 I used mere
 key, val = myDict.items()[0]
 but in Python 3 myDict.items() return iterator.
 Of course, I could use
 for key, val in myDict.items():
   do_something
   break
 but maybe there is any better way?

key, val = next(myDict.items())

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


Re: string formatting

2011-05-06 Thread Neil Cerutti
On 2011-05-06, harrismh777 harrismh...@charter.net wrote:
 Steven D'Aprano wrote:
 It's perfectly safe to continue using % formatting, if you
 choose.

 I would hope so, since its the way in most of the books, much
 of the doc and a majority of the code...

 I don't really like the old style, not because there is
 anything wrong with it, because its an obvious carry-over from
 the cryptic formatting style of 'C' printf(), and others. It
 seems to me that the purpose of formatting is to make output
 clear, and therefore the output formatting style itself should
 be clear and clean.

C's printf is a venerable example of the power of notation.
Notation kicks ass. Another that's well known are regular
expressions. Python uses this powerful idea again in the struct
module. Any other places?

Functions and classes are a general purpose, though verbose, form
of notation and can be used in place of mini languages when you
don't want to bother, e.g., C++'s iostreams, and pyparsing's
grammar declarations.

Lisp declared that you could implement mini-languages in Lisp,
rather than just parsing them.

Python 3's format notation is an improvement for Python, since
Python doesn't need the type information that's crucial for C and
particularly scanf, an application of C's mini-language that
Python doesn't need. Delimiting the escape sequences also makes
it easier to read and parse complex formating declarations.

For simple constructs there's not much difference between them,
but if you switch to .format you'll probably reap some benefit.

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


Re: string formatting

2011-05-06 Thread Ian Kelly
On Fri, May 6, 2011 at 1:39 PM, harrismh777 harrismh...@charter.net wrote:
 harrismh777 wrote:    OP wrote:

 (1) the %s is %s % ('sky', 'blue')

 (2) the {0} is {1}.format('sky', 'blue')

 (3) the {} is {}.format('sky', 'blue')

   On the other hand, consider this 3.x code snip:

   print(the %s is %d % ('sky', 'blue'))


   That formatting will throw an exception, because the format construct is
 restricting the format entry to be a number, which 'blue' clearly isn't

If you used %d, then that exception is presumably what you wanted.  If
not, then you should just do:

print(the %s is %s % ('sky', 'blue'))

   The following print() is better, because *any* time or *most* types can be
 substituted and the 'polymorphism' of Python kicks in allowing for that, as
 so:

'%s' has exactly the same degree of polymorphism as '{}', because both
simply call str() on their argument.  There are good reasons to use
format instead of % if possible, but polymorphism isn't one of them.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3 dict question

2011-05-06 Thread dmitrey
On May 6, 10:51 pm, Chris Rebert c...@rebertia.com wrote:
 On Fri, May 6, 2011 at 12:40 PM, dmitrey dmitre...@gmail.com wrote:
  hi all,
  suppose I have Python dict myDict and I know it's not empty.
  I have to get any (key, value) pair from the dict (no matter which
  one) and perform some operation.
  In Python 2 I used mere
  key, val = myDict.items()[0]
  but in Python 3 myDict.items() return iterator.
  Of course, I could use
  for key, val in myDict.items():
    do_something
    break
  but maybe there is any better way?

 key, val = next(myDict.items())

 Cheers,
 Chris

Unfortunately, it doesn't work, it turn out to be dict_items:
 next({1:2}.items())
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: dict_items object is not an iterator
 dir({1:2}.items())
['__and__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__gt__',
'__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__',
'__ne__', '__new__', '__or__', '__rand__', '__reduce__',
'__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__',
'__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__',
'__xor__', 'isdisjoint']
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coolest Python recipe of all time

2011-05-06 Thread Raymond Hettinger
[Steven D'Aprano]:
 As written, amb is just a brute-force solver using more magic than is
 good for any code, but it's fun to play with.

With a small change in API, much of the magic isn't needed.

from itertools import product

def amb(func, *argument_ranges):
for args in product(*argument_ranges):
if func(*args):
print(args)

amb(lambda a,b,c,d: 5*a+10*b+20*c+50*d == 45,
range(3, 21),   # number of 5 cent coins
range(11),  # number of 10 cent coins
range(6),   # number of 20 cent coins
range(3),   # number of 50 cent coins
)

def test(a, b, c, d):
s = The %s brown %s jumped over the %s %s. % (a, b, c, d)
num_vowels = sum(s.count(c) for c in 'aeiou')
return num_vowels in (12, 18, 19)

amb(test,
['quick', 'slow', 'hungry', 'wise-old'],
['fox', 'hare', 'turtle', 'kangaroo'],
['lazy', 'stupid', 'sleepy', 'confused'],
['dog', 'aardvark', 'sloth', 'wombat'],
)

amb(lambda x, y, z: x*x + y*y == z*z,
range(1, 11),
range(1, 11),
range(1, 11),
)


Raymond


follow my recipes and tips on twitter: @raymondh
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Eric Snow
On Fri, May 6, 2011 at 1:31 PM, Terry Reedy tjre...@udel.edu wrote:

 On 5/6/2011 7:34 AM, James Mills wrote:

 On Fri, May 6, 2011 at 4:36 PM, Jabba Lacijabba.l...@gmail.com  wrote:

 If I want to check if a list is empty, which is the more pythonic way?


 [...]

  (2) if not li:


 This is fine.


 This is the intended way. Anything in addition is extra noise and wasted
 calculation. In other words, let Python do the boilerplate work for you.


That works for lists, but for a class that implements a list-like interface,
subclassing list or not, it will not always work the way you want.  The
language reference indicates that, for the implicit cast to a bool, __bool__
is checked on the object, then __len__, and then it defaults to True [1].
 So the above only works the way you expect if __len__ is the normal length
for a list and __bool__ is not defined.

I ran into this once when I had a class that defined __len__ but wanted the
object to cast to True no matter what.  For my case I chose to redefine
__bool__.

So it seems like this boils down to what you want to know.  Is the list
empty (length 0) or is the boolean version false?  Again, for lists these
are the same.  For list-like classes they are not necessarily the same.

Incidently, you can also check if li == []:.  This will let the __eq__
operator jump in.

-eric

[1] http://docs.python.org/dev/py3k/reference/datamodel.html#object.__bool__

-- 
 Terry Jan Reedy


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

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


Re: Python 3 dict question

2011-05-06 Thread Ian Kelly
On Fri, May 6, 2011 at 1:51 PM, Chris Rebert c...@rebertia.com wrote:
 On Fri, May 6, 2011 at 12:40 PM, dmitrey dmitre...@gmail.com wrote:
 hi all,
 suppose I have Python dict myDict and I know it's not empty.
 I have to get any (key, value) pair from the dict (no matter which
 one) and perform some operation.
 In Python 2 I used mere
 key, val = myDict.items()[0]
 but in Python 3 myDict.items() return iterator.
 Of course, I could use
 for key, val in myDict.items():
   do_something
   break
 but maybe there is any better way?

 key, val = next(myDict.items())

Recognizing that if myDict is empty then this will raise StopIteration
instead of KeyError.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Adam Tauno Williams
On Fri, 2011-05-06 at 14:49 -0500, harrismh777 wrote:
 Terry Reedy wrote:
  (2) if not li:
  This is fine.
  This is the intended way. Anything in addition is extra noise and wasted
  calculation. In other words, let Python do the boilerplate work for you.
 I agree, but I don't like it.

+1  This is the Python reality-distortion-field at work.

Motto#1: Python is all about readability!
Motto#2: Crytic code is awesome if it is Pythoncally cryptic!

I'd never accept code like if not x as an empty test.

 ... if not li  says nothing about what li is supposed to 'be' and 
 implies in any case that li does not exist, or worse is some kind of 
 boolean.
 li is in fact an empty list [] and will identify as such, and of 
 course (as a list object) has all of the attributes and methods of a list...
 Why not have a list method that makes this more explicit:
 if not li.emptylist()
 if not li.empty([])
 there might be others...

Good luck.  Just code -
  # You can immediately tell what this is meant to do!
  if len(x) == 0:  
- and ignore the Pythonistas [they're nuts;  that x.count() doesn't work
is amazingly stupid].

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


Re: checking if a list is empty

2011-05-06 Thread Chris Rebert
On Fri, May 6, 2011 at 1:05 PM, Adam Tauno Williams
awill...@whitemice.org wrote:
snip
 - and ignore the Pythonistas [they're nuts;  that x.count() doesn't work
 is amazingly stupid].

Eh? It works fine. [5, 2, 2, 1, 2].count(2) == 3. If you mean you want
len(x) to be spelled x.count(), that's equally stupid; `count` would
be a lousy name (people would confuse it with what the current
.count() does). `length` or `size` would make much more sense.

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


Re: Python 3 dict question

2011-05-06 Thread Ian Kelly
On Fri, May 6, 2011 at 1:57 PM, dmitrey dmitre...@gmail.com wrote:
 Unfortunately, it doesn't work, it turn out to be dict_items:
 next({1:2}.items())
 Traceback (most recent call last):
  File stdin, line 1, in module
 TypeError: dict_items object is not an iterator

So call iter() on it first:

next(iter(myDict.items()))
-- 
http://mail.python.org/mailman/listinfo/python-list


How can I print one sqlite table with UTF-8 collumn

2011-05-06 Thread Jayme Proni Filho
I have one sqlite database called aripuanaonline.db. In this database I have
one table with two collumns first with autoincrement not null and other with
varchar(100) not null.

I got this error:

Traceback (most recent call last):
  File C:\Documents and Settings\Marco\Desktop\aripuanaonline\aripuana.py,
line 9, in module
rows = cursor.fetchall()
sqlite3.OperationalError: Could not decode to UTF-8 column 'mensagem' with
text 'Shampoo Pantene Restaura��o Profunda � vista por R$4,99'

How can I print my table?


---
Jayme Proni Filho
Skype: jaymeproni
Twitter: @jaymeproni
Phone: +55 - 17 - 3631 - 6576
Mobile: +55 - 17 - 9605 - 3560
e-Mail: jaymeproni at yahoo dot com dot br
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3 dict question

2011-05-06 Thread Rob Wolfe
dmitrey dmitre...@gmail.com writes:

 hi all,
 suppose I have Python dict myDict and I know it's not empty.
 I have to get any (key, value) pair from the dict (no matter which
 one) and perform some operation.
 In Python 2 I used mere
 key, val = myDict.items()[0]
 but in Python 3 myDict.items() return iterator.
 Of course, I could use
 for key, val in myDict.items():
do_something
break
 but maybe there is any better way?

key, val = next(iter(myDict.items()))

http://docs.python.org/py3k/library/stdtypes.html#dictionary-view-objects

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


Re: string formatting

2011-05-06 Thread Terry Reedy

On 5/6/2011 3:22 PM, harrismh777 wrote:


I don't really like the old style, not because there is anything wrong
with it,


There is in that it special cases tuples. For instance, a message 
function like


def emsg(x):
  print(The following object caused a proplem: %s % x)

raises TypeError: not all arguments converted during string formatting
if x is a tuple with other than 1 member and extracts x[0] if there is 
just one. Neither is the desired behavior. That has been a problem (and 
sometimes a debugging puzzle) in real code One has to remember to write 
something like


def emsg(x):
  if isinstance(x,tuple):
x = (x,)
  print(The following object caused a proplem: %s % x)

Guido sees that his original design is a bit of a bug trap, which is one 
reason he wanted to replace it.


--
Terry Jan Reedy

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


Re: Python 3 dict question

2011-05-06 Thread nirinA raseliarison
[dmitrey]
 hi all,
 suppose I have Python dict myDict and I know it's not empty.
 I have to get any (key, value) pair from the dict (no matter which
 one) and perform some operation.
 In Python 2 I used mere
 key, val = myDict.items()[0]
 but in Python 3 myDict.items() return iterator.
 Of course, I could use
 for key, val in myDict.items():
   do_something
   break
 but maybe there is any better way?

key, val = list(myDict.items())[0]

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


Re: checking if a list is empty

2011-05-06 Thread scattered
On May 6, 2:36 am, Jabba Laci jabba.l...@gmail.com wrote:
 Hi,

 If I want to check if a list is empty, which is the more pythonic way?

 li = []

 (1) if len(li) == 0:
 ...
 or
 (2) if not li:
 ...

 Thanks,

 Laszlo

is there any problem with

(3) if li == []:

?

Seems to work when I test it and seems to clearly test what you are
trying to test. The only problem might be if in some contexts == has
the semantics of checking for object identity.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: setuptools for 64-bit 2.7.1 on 64-bit Windows 7?

2011-05-06 Thread David Robinow
On Fri, May 6, 2011 at 1:43 PM, Dick Bridges dick.brid...@wdc.com wrote:
 Simple question: Is it true that no setuptools (or any other module
 installer) exists for 64-bit python 2.7.1? If there is an installer that
 works, what terms might I use to Google for information on how to acquire
 and install it?
Doesn't the installer at
http://www.lfd.uci.edu/~gohlke/pythonlibs/
work?
-- 
http://mail.python.org/mailman/listinfo/python-list


Dictionary Views -- good examples? [was Re: Python 3 dict question]

2011-05-06 Thread Ethan Furman

Ian Kelly wrote:

On Fri, May 6, 2011 at 1:57 PM, dmitrey dmitre...@gmail.com wrote:

Unfortunately, it doesn't work, it turn out to be dict_items:

next({1:2}.items())

Traceback (most recent call last):
 File stdin, line 1, in module
TypeError: dict_items object is not an iterator


So call iter() on it first:

next(iter(myDict.items()))


Which is becoming less elegant.  Seems to me that View objects should be 
directly iterable, but then I don't really understand the motivation 
behind them or what greatness is facilitated by having them.


Anybody care to chime in with their usage of this construct?

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


Re: checking if a list is empty

2011-05-06 Thread Raymond Hettinger
On May 5, 11:36 pm, Jabba Laci jabba.l...@gmail.com wrote:
 Hi,

 If I want to check if a list is empty, which is the more pythonic way?

 li = []

 (1) if len(li) == 0:
 ...
 or
 (2) if not li:

The Python core developers use the second form.
See http://www.python.org/dev/peps/pep-0008/
for the official recommendation.


Raymond

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


Re: checking if a list is empty

2011-05-06 Thread Philip Semanchuk

On May 6, 2011, at 5:57 PM, scattered wrote:

 On May 6, 2:36 am, Jabba Laci jabba.l...@gmail.com wrote:
 Hi,
 
 If I want to check if a list is empty, which is the more pythonic way?
 
 li = []
 
 (1) if len(li) == 0:
 ...
 or
 (2) if not li:
 ...
 
 Thanks,
 
 Laszlo
 
 is there any problem with
 
 (3) if li == []:
 
 ?

What if it's not a list but a tuple or a numpy array? Often I just want to 
iterate through an element's items and I don't care if it's a list, set, etc. 
For instance, given this function definition --

def print_items(an_iterable):
if not an_iterable:
print The iterable is empty
else:
for item in an_iterable:
print item

I get the output I want with all of these calls:
print_items( list() )
print_items( tuple() )
print_items( set() )
print_items( numpy.array([]) )

Given this slightly different definition, only the  first call gives me the 
output I expect: 

def print_items(an_iterable):
if an_iterable == []:
print The iterable is empty
else:
for item in an_iterable:
print item


I find I use the the former style (if not an_iterable) almost exclusively.


bye
Philip




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


Re: What other languages use the same data model as Python?

2011-05-06 Thread Chris Angelico
On Sat, May 7, 2011 at 5:25 AM, harrismh777 harrismh...@charter.net wrote:
 Chris Torek wrote:

 with the Python-named-Monty, we have rigidly defined areas of
 doubt and uncertainty.  These exist for good reasons: to allow
 different implementations.

 Oops, attribution error: this comes from Douglas Adams rather
 than Monty Python.

 Well, its certainly Monte-esq I like it, whoever said it.

Same style of humour, they both derived significantly from Spike
Milligan and The Goon Show. That particular quote relates to the
famous computer that calculated the number 42, which - to drag this,
kicking and screaming, back to some semblance of on-topicness - was
clearly built with a view to conserving programmer time at the expense
of execution time. I don't understand why they didn't just recode the
heavy computation in C and cut it down to just a few thousand years...

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


Re: checking if a list is empty

2011-05-06 Thread Ian Kelly
On Fri, May 6, 2011 at 4:21 PM, Philip Semanchuk phi...@semanchuk.com wrote:
 What if it's not a list but a tuple or a numpy array? Often I just want to 
 iterate through an element's items and I don't care if it's a list, set, etc. 
 For instance, given this function definition --

 def print_items(an_iterable):
    if not an_iterable:
        print The iterable is empty
    else:
        for item in an_iterable:
            print item

 I get the output I want with all of these calls:
 print_items( list() )
 print_items( tuple() )
 print_items( set() )
 print_items( numpy.array([]) )

But sadly it fails on iterators:
print_items(xrange(0))
print_items(-x for x in [])
print_items({}.iteritems())
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting

2011-05-06 Thread Chris Angelico
On Sat, May 7, 2011 at 6:54 AM, Terry Reedy tjre...@udel.edu wrote:
 def emsg(x):
  if isinstance(x,tuple):
    x = (x,)
  print(The following object caused a proplem: %s % x)


Couldn't you just do that unconditionally?
print(The following object caused a proplem: %s % (x,))

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


Re: Dictionary Views -- good examples? [was Re: Python 3 dict question]

2011-05-06 Thread Ian Kelly
On Fri, May 6, 2011 at 4:49 PM, Ethan Furman et...@stoneleaf.us wrote:
 Ian Kelly wrote:

 On Fri, May 6, 2011 at 1:57 PM, dmitrey dmitre...@gmail.com wrote:

 Unfortunately, it doesn't work, it turn out to be dict_items:

 next({1:2}.items())

 Traceback (most recent call last):
  File stdin, line 1, in module
 TypeError: dict_items object is not an iterator

 So call iter() on it first:

 next(iter(myDict.items()))

 Which is becoming less elegant.

That's not even the worst of it.  If the dict is empty, then the code
above will raise a StopIteration, which must be caught locally since
if it propagates it could be swallowed by a generator.  So a full
recipe should really look more like this:

try:
first_item = next(iter(my_dict.items()))
except StopIteration:
raise ValueError(empty dict)

 Seems to me that View objects should be directly iterable

They are.  They're just not directly nextable because they're treated
as dependent collections, not iterators.

 but then I don't really understand the motivation behind them or what 
 greatness is facilitated by having them.

 Anybody care to chime in with their usage of this construct?

You should start with PEP 3106.  The main idea is that dict.keys() and
dict.items() can be treated as frozensets, while still being more
lightweight than lists.  That lets you do nifty things like a.keys()
== b.keys() which, if a and b are Python 3 dicts, will tell you
whether they contain the same keys.

Whether anybody actually uses this, I have no idea.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: checking if a list is empty

2011-05-06 Thread Jon Clements
On May 7, 12:51 am, Ian Kelly ian.g.ke...@gmail.com wrote:
 On Fri, May 6, 2011 at 4:21 PM, Philip Semanchuk phi...@semanchuk.com wrote:
  What if it's not a list but a tuple or a numpy array? Often I just want to 
  iterate through an element's items and I don't care if it's a list, set, 
  etc. For instance, given this function definition --

  def print_items(an_iterable):
     if not an_iterable:
         print The iterable is empty
     else:
         for item in an_iterable:
             print item

  I get the output I want with all of these calls:
  print_items( list() )
  print_items( tuple() )
  print_items( set() )
  print_items( numpy.array([]) )

 But sadly it fails on iterators:
 print_items(xrange(0))
 print_items(-x for x in [])
 print_items({}.iteritems())

My stab:

from itertools import chain

def print_it(iterable):
it = iter(iterable)
try:
head = next(it)
except StopIteration:
print 'Empty'
return
for el in chain( (head,), it ):
print el

Not sure if I'm truly happy with that though.

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


Re: checking if a list is empty

2011-05-06 Thread Chris Angelico
On Sat, May 7, 2011 at 6:05 AM, Adam Tauno Williams
awill...@whitemice.org wrote:
 On Fri, 2011-05-06 at 14:49 -0500, harrismh777 wrote:
 Terry Reedy wrote:
  (2) if not li:
  This is fine.
  This is the intended way. Anything in addition is extra noise and wasted
  calculation. In other words, let Python do the boilerplate work for you.
     I agree, but I don't like it.

 +1  This is the Python reality-distortion-field at work.

 Motto#1: Python is all about readability!
 Motto#2: Crytic code is awesome if it is Pythoncally cryptic!

As a C and C++ programmer, I probably shouldn't offer an opinion, but
it is quite normal in C++ to compare objects for truth/falseness - for
instance, stream objects return false on error/eof, so you can
efficiently code a loop with while (infile) {...}. Not to mention
that the nullness of a C string (a PSZ) is quite happily and safely
tested by seeing if the pointer is true (non-null) or false (null).

That said, though, readability is a relative thing. A construct is
transparently obvious if it does something in the exact same way that
it's always been done, no matter how obscure it was the first time.
Why is it, for instance, that putting two short strokes perpendicular
to one another indicates addition? Yet if you see the construct x +
y, you know exactly what it means - it's readable, it's not cryptic
at all. People assume and expect that this compact syntax will be
available, and object heavily to such notation as add(x,y) which
says exactly what it does.

if not li:

is perfectly readable; you just need a comprehension of what truth
means for a list.

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


PyGTK, Glade/libglade. What am I doing wrong?

2011-05-06 Thread Даниил Рыжков
Sorry for my English (I could not find help in the Russian community)
I'm trying to learn PyGTK and Glade. I made test window in Glade and
saved it as test.glade (attached). Then I wrote script
test.py(attached, http://pastebin.com/waKytam3). I tried to run it.
While the script was executed, console did not show anything and
window wasn't displayed. When I pressed CTRL+С console displayed
trackback:
---
CTraceback (most recent call last):
  File test.py, line 32, in module
gtk.main()
KeyboardInterrupt
---
So what am I doing wrong?

-- 
Best wishes,
Daniil
#!/usr/bin/env python

import sys
try:
 	import pygtk
  	pygtk.require(2.0)
except:
  	pass
try:
	import gtk
  	import gtk.glade
except:
	sys.exit(1)

class TestPyGtk:
	This is an Hello World GTK application

	def __init__(self):
		
		#Set the Glade file
		self.gladefile = test.glade  
	self.wTree = gtk.glade.XML(self.gladefile) 
		
		#Create our dictionay and connect it
		dic = {on_MainWindow_destroy : gtk.main_quit }
		self.wTree.signal_autoconnect(dic)



if __name__ == __main__:
	TestPyGtk = TestPyGtk()
	gtk.main()


test.glade
Description: application/glade
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string formatting

2011-05-06 Thread Steven D'Aprano
On Fri, 06 May 2011 14:39:15 -0500, harrismh777 wrote:

 On the other hand, consider this 3.x code snip:
 
 print(the %s is %d % ('sky', 'blue'))
 
 
 That formatting will throw an exception, because the format
 construct is restricting the format entry to be a number, which 'blue'
 clearly isn't

Er, yes. That's clearly deliberate, because the target uses %d rather 
than %s. If the author wanted to accept anything, she would used %r or %s.

You might as well argue that:

print(the {} is {}.format('sky', int(x)))

is wrong, because if you leave the int out, any object can be used.




 The following print() is better, because *any* time or *most* types
 can be substituted and the 'polymorphism' of Python kicks in allowing
 for that, as so:
 
  print(the {} is {}.format('sky', 3.4))


This is not comparing apples with apples. The format equivalent is:

print(the {} is {:d}.format('sky', 'blue'))

which will also raise an exception, ValueError instead of TypeError.



-- 
Steven

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


Re: PyGTK, Glade/libglade. What am I doing wrong?

2011-05-06 Thread Benjamin Kaplan
On May 6, 2011 7:05 PM, Даниил Рыжков daniil...@gmail.com wrote:

 Sorry for my English (I could not find help in the Russian community)
 I'm trying to learn PyGTK and Glade. I made test window in Glade and
 saved it as test.glade (attached). Then I wrote script
 test.py(attached, http://pastebin.com/waKytam3). I tried to run it.
 While the script was executed, console did not show anything and
 window wasn't displayed. When I pressed CTRL+С console displayed
 trackback:
 ---
 CTraceback (most recent call last):
  File test.py, line 32, in module
gtk.main()
 KeyboardInterrupt
 ---
 So what am I doing wrong?


I haven't used gtk before, but is there a show method or something similar
you need, to actually make the window appear? The KeyboardInterrupt is
normal. That's how control-c works.
 --
 Best wishes,
 Daniil

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

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


Re: checking if a list is empty

2011-05-06 Thread Steven D'Aprano
On Fri, 06 May 2011 16:05:09 -0400, Adam Tauno Williams wrote:

 I'd never accept code like if not x as an empty test.

So much the worse for you then.

The point of the if x idiom is that it is a polymorphic test which is 
independent of the type. It works with any non-broken object[1], no 
matter what x is, since it allows x to decide for itself whether it is 
empty or not.

Of course, you can write your own polymorphic test:


try:
flag = len(x) == 0
except TypeError:
# This *should* succeed, for anything not broken. If not, we can't
# recover, so just let the exception propagate.
flag = bool(x)
# Hilariously, bool(x) may also try len(x) == 0... oh well.
if flag:
...

Congratulations! You've now found a way to write if x: in five lines, 
53 characters (plus whitespace and comments) and an extraneous variable 
polluting the namespace. If you're being paid per line of code, this is a 
good win.

Of course, sometimes you don't want polymorphism (or at least, not too 
much polymorphism). Sometimes I'll write if x == 0 or similar if I want 
to emphasize that x is a special case unrelated to the truth/falseness of 
x. But that's quite rare. Normally I trust x to decide for itself whether 
it is empty or not.





[1] Arguably with the exception of iterables. But then the len(x) test 
doesn't work for them either.


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


Re: checking if a list is empty

2011-05-06 Thread Steven D'Aprano
On Fri, 06 May 2011 14:57:21 -0700, scattered wrote:

 is there any problem with
 
 (3) if li == []:
 
 ?
 
 Seems to work when I test it and seems to clearly test what you are
 trying to test. The only problem might be if in some contexts == has the
 semantics of checking for object identity.

Yes, if li == [] works too. But how do you know li is a list and not some 
other sequence type?

The advantage of the if x test is that it is independent of the type of 
x.

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


Re: PyGTK, Glade/libglade. What am I doing wrong?

2011-05-06 Thread Даниил Рыжков
 I haven't used gtk before, but is there a show method or something similar
 you need, to actually make the window appear?
I don't know. I think self.wTree = gtk.glade.XML(self.gladefile)
should do this. For example, author of this tutorial
(http://www.learningpython.com/2006/05/07/creating-a-gui-using-pygtk-and-glade/)
wrote script similar to my.

P.S. I have glade3 3.8.0, gtk 2.24.4, GNOME 2.32.1 and Python 2.7.1

--
Best wishes,
Daniil
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyGTK, Glade/libglade. What am I doing wrong?

2011-05-06 Thread craf
On May 6, 2011 7:05 PM, Даниил Рыжков daniil...@gmail.com wrote:

 Sorry for my English (I could not find help in the Russian community)
 I'm trying to learn PyGTK and Glade. I made test window in Glade and
 saved it as test.glade (attached). Then I wrote script
 test.py(attached, http://pastebin.com/waKytam3). I tried to run it.
 While the script was executed, console did not show anything and
 window wasn't displayed. When I pressed CTRL+С console displayed
 trackback:
 ---
 CTraceback (most recent call last):
  File test.py, line 32, in module
gtk.main()
 KeyboardInterrupt
 ---
 So what am I doing wrong?


I haven't used gtk before, but is there a show method or something
similar you need, to actually make the window appear? The
KeyboardInterrupt is normal. That's how control-c works.
 --
 Best wishes,
 Daniil

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


Hi.

Try this:

#!/usr/bin/env python

import gtk.glade

class TestPyGtk:
This is an Hello World GTK application

def __init__(self):

#Set the Glade file
self.gladefile = test.glade
self.glade = gtk.glade.XML(self.gladefile)

self.MainWindow = self.glade.get_widget('MainWindow')
self.MainWindow.show()
self.MainWindow.connect('destroy', lambda e:gtk.main_quit())



TestPyGtk()
gtk.main()

Regards.

Cristian.

List of Pygtk: http://www.daa.com.au/mailman/listinfo/pygtk





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


Re: PyGTK, Glade/libglade. What am I doing wrong?

2011-05-06 Thread Даниил Рыжков
Thanks, Cristian! It works.
 List of Pygtk: http://www.daa.com.au/mailman/listinfo/pygtk
Thanks again. Subscribed :)
2011/5/7 craf pyclut...@gmail.com:
 Hi.

 Try this:

 #!/usr/bin/env python

 import gtk.glade

 class TestPyGtk:
    This is an Hello World GTK application

    def __init__(self):

        #Set the Glade file
        self.gladefile = test.glade
        self.glade = gtk.glade.XML(self.gladefile)

        self.MainWindow = self.glade.get_widget('MainWindow')
        self.MainWindow.show()
        self.MainWindow.connect('destroy', lambda e:gtk.main_quit())



 TestPyGtk()
 gtk.main()

 Regards.

 Cristian.

 List of Pygtk: http://www.daa.com.au/mailman/listinfo/pygtk
--
Best wishes,
Daniil
-- 
http://mail.python.org/mailman/listinfo/python-list


Testing tools classification

2011-05-06 Thread rusi
There is this nice page of testing tools taxonomy:
http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy

But it does not list staf: http://staf.sourceforge.net/index.php.
-- 
http://mail.python.org/mailman/listinfo/python-list


[issue11015] Bring test.support docs up to date

2011-05-06 Thread Eli Bendersky

Eli Bendersky eli...@gmail.com added the comment:

Terry,

I've incorporated your suggestions except the new formulation for verbosity to 
doctest.testmod, since it's not really clear which one is more accurate. I 
think it's intelligible as it is now (especially given that test.support is for 
use of Python contributors, and not random users). If you have strong 
preferences about it, feel free to commit another formulation.

Ezio,

I answered your comments in the code review tool.
Regarding the use of assertEqual for the floating point results, I just didn't 
want to rely on the exact representation of these values. I'm not 100% sure 
Python ensures this is true on all platforms it supports. Recall that I was 
just replacing the fcmp code which did basically the same, also not comparing 
exactly.



I will commit a fixed patch to default. I see no reason to backport this since 
test.support is just a tool for core-devs and contributors and is mainly used 
for future developments.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue11015
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue11015] Bring test.support docs up to date

2011-05-06 Thread Roundup Robot

Roundup Robot devnull@devnull added the comment:

New changeset 2fd435ac3551 by Eli Bendersky in branch 'default':
Issue #11015: bring test.support docs up to date
http://hg.python.org/cpython/rev/2fd435ac3551

--
nosy: +python-dev

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue11015
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12015] possible characters in temporary file name is too few

2011-05-06 Thread Amaury Forgeot d'Arc

Amaury Forgeot d'Arc amaur...@gmail.com added the comment:

- How is it an issue? is the number of combinations really important to you?
- Isn't there a greater risk of collisions on a case-insensitive filesystem?

--
nosy: +amaury.forgeotdarc

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12015
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12014] str.format parses replacement field incorrectly

2011-05-06 Thread Mark Dickinson

Changes by Mark Dickinson dicki...@gmail.com:


--
nosy: +eric.smith, mark.dickinson

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12014
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



  1   2   3   >