IMDbPY 3.7 released
IMDbPY 3.7 is available (tgz, deb, rpm, exe) from: http://imdbpy.sourceforge.net/ IMDbPY is a Python package useful to retrieve and manage the data of the IMDb movie database about movies, people, characters and companies. In this release the html parsers were replaced with new DOM/XPath-based parsers, mostly based on the work of H. Turgut Uyar, who I thank. Platform-independent and written in pure Python (and few C lines), it can retrieve data from both the IMDb's web server and a local copy of the whole database. IMDbPY package can be very easily used by programmers and developers to provide access to the IMDb's data to their programs. Some simple example scripts are included in the package; other IMDbPY-based programs are available from the home page. -- Davide Alberani [EMAIL PROTECTED] [PGP KeyID: 0x465BFD47] http://erlug.linux.it/~da/ -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
PUB (Python Users Berlin) meeting: 24.09., 7pm, newthinking store
The next PUB meeting takes place on 24.09. at newthinking store, tucholskystr. 48, 10117 Berlin, Germany at 7pm. Afterwards, we'll go to a restaurant for food and drink. We welcome all people interested in the Python programming language. best regards, stephan -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
pyArkansas Set for October 4th
This is a reminder of the upcoming pyArkansas one-day Python conference being held on the campus of the University of Central Arkansas on Sat Oct 4, 2008. The schedule is pretty much set ( http://pycamp.python.org/Arkansas/Schedule) and has something for anyone interested in Python, from intro workshops to advanced topics. Jeff Rush and Noah Gift are scheduled to present workshops and talks while Dr. Bernard Chen (UCA Faculty) will teach a 3-hour class on Python for the Absolute Beginner. Eggs, pyGame, standard library, Eclipse and OLPC are some of the other talks scheduled. This is a *FREE* event (we have GREAT sponsors), so all you need to bring is yourself. We have over 45 people -- from 4 States -- registered and tons of great swag and giveaways lined up. See our wiki (http://pycamp.python.org/Arkansas/HomePage) for more details and registration info. Greg Lindstrom Python Artists of Arkansas (pyAR^2) -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Elisa Media Center 0.5.11 Release
Dear Elisa users, The Elisa team is happy to announce the release of Elisa Media Center 0.5.11, code-named Corporal Nobbs. This 11th release of the 0.5 series introduces the following new features: - Extended D-Bus API to control the media scanning process - Rotation of pictures is available as a control of the photo player - New D-Bus interface to perform common operations on the audio player: play, pause, stop, currently playing media, etc. - Favorites are now available for videos as well On top of that few but hindering bugs have been resolved during this cycle. A complete list of the new features and bugs fixed by this release is available at: https://bugs.launchpad.net/elisa/+milestone/0.5.11 Installers and sources can be downloaded from http://elisa.fluendo.com/download/ Bug reports and feature requests are welcome at https://bugs.launchpad.net/elisa/+filebug Have a nice evening, The Elisa team -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: dict generator question
On Fri, Sep 19, 2008 at 9:51 PM, Steven D'Aprano [EMAIL PROTECTED] wrote: Extending len() to support iterables sounds like a good idea, except that it's not. Here are two iterables: def yes(): # like the Unix yes command while True: yield y def rand(total): Return random numbers up to a given total. from random import random tot = 0.0 while tot total: x = random() yield x tot += x What should len(yes()) and len(rand(100)) return? Clearly, len(yes()) would never return, and len(rand(100)) would return a random integer not less than 101. -Miles -- http://mail.python.org/mailman/listinfo/python-list
External code and functions integration
Good day. I am using python for quite some time now and i decided to advance a little. I want to write a little extension, or add some C modules for my python. I use Active version. What i want to do is write some wrappers for a game library, called HGE. See hge.relishgames.com. I wrote some applications with HGE, in C++ and i like it pretty much. In order to make a HGE application in C++, i need to include hge.h, include hge.lib and hgelehper.lib, and have hge.dll in the same directory. So it's 3 things i must have for the program to work. This game library is open source, so i have the source for the libs and the dll. Now, what i was thinking was to make some wrapping code like hge.h to call all the functions in the libs, that (i guess) call the functions from hge.dll, that (blah blah) calls DirectX and so on. I guess that if i write all that hge.h includes and wariables in python, will be okay... even if i still don't have the skill. I tried to call hge.lib like this: from ctypes import * cdll.LoadLibrary(D:/HGE18/lib/bc/hge.lib) But i get WindowsError: [Error 193] %1 is not a valid Win32 application. I tried with windll.LoadLibrary ... and i get the same error. I tried with the other lib versions, there are 3 versions: BorlandC, GCC, VisualC, callind cdll or windll. All lib versions report the same error. Recently i discovered PyInline and SciPy Weave. They say that Weave can run C code on the fly, inline... I really dobt that it can parse things like: #ifndef HGE_H #define HGE_H or: #include windows.h #define HGE_VERSION 0x180 #ifdef HGEDLL #define EXPORT __declspec(dllexport) #else #define EXPORT #endif #define CALL __stdcall Has anyone ever encountered a problem like this ? Any, ANY advice or idea would be useful ! Thank you very much. -- http://mail.python.org/mailman/listinfo/python-list
Re: External code and functions integration
Cro schrieb: Good day. I am using python for quite some time now and i decided to advance a little. I want to write a little extension, or add some C modules for my python. I use Active version. What i want to do is write some wrappers for a game library, called HGE. See hge.relishgames.com. I wrote some applications with HGE, in C++ and i like it pretty much. In order to make a HGE application in C++, i need to include hge.h, include hge.lib and hgelehper.lib, and have hge.dll in the same directory. So it's 3 things i must have for the program to work. This game library is open source, so i have the source for the libs and the dll. Now, what i was thinking was to make some wrapping code like hge.h to call all the functions in the libs, that (i guess) call the functions from hge.dll, that (blah blah) calls DirectX and so on. I guess that if i write all that hge.h includes and wariables in python, will be okay... even if i still don't have the skill. I tried to call hge.lib like this: from ctypes import * cdll.LoadLibrary(D:/HGE18/lib/bc/hge.lib) But i get WindowsError: [Error 193] %1 is not a valid Win32 application. I tried with windll.LoadLibrary ... and i get the same error. I tried with the other lib versions, there are 3 versions: BorlandC, GCC, VisualC, callind cdll or windll. All lib versions report the same error. Because you need to load the DLL. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: understanding list scope
On Sep 21, 7:48 pm, Peter Pearson [EMAIL PROTECTED] wrote: FWIW, since I started following this newsgroup, I've noticed that I no longer have those crises that revolve around the depth of a copy. I conjecture that they resulted from non-pythonic style. Try following this newsgroup for a while, and you might see a lot of startlingly elegant ways of doing things. -- To email me, substitute nowhere-spamcop, invalid-net. I know the code is really ugly but I just make a quick and dirty snippet to ask for help. I should have wrapped the code between bad code/bas code tags ;-) Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
On Sep 21, 4:39 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: I have a class which is not intended to be instantiated. Instead of using the class to creating an instance and then operate on it, I use the class directly, with classmethods. Essentially, the class is used as a function that keeps state from one call to the next. The problem is that I don't know what to call such a thing! Abstract class isn't right, because that implies that you should subclass the class and then instantiate the subclasses. What do you call such a class? If defining it as a normal class, it is a namespace. Just a way to cluster multiple globals into a single global. The borg pattern does the same thing, but with a 12 page treatise on why it shouldn't do exactly what it's doing. If using a factory you should probably be using an instance; the fact that your instance is a class is a relatively minor implementation detail. Indeed, the only reason to have a class is to have your methods bound when looked up. You might want a metaclass to cripple it, preventing subclassing and whatnot. *shrug*. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about sorted in Python 3.0rc1
On 22 Sep, 04:05, josh logan [EMAIL PROTECTED] wrote: Hello, I have 2 questions. Say I have this class: class Player(object): def __init__(self, fname, lname, score): self.score = score self.fname = fname self.lname = lname def __cmp__(self, other): return (-cmp(self.score, other.score) or cmp(self.lname, other.lname) or cmp(self.fname, other.fname)) def __repr__(self): return 'Player(fname={0.fname}, lname={0.lname}, score={0.score})'.format(self) def __eq__(self, others): if isinstance(other, Player): return (self.score == other.score and self.lname == other.lname and self.fname == other.fname) return False def __ne__(self, others): return not self.__eq__(others) fnames = ['Julie', 'Ben', 'Jason', 'David'] lnames = ['Parks', 'Smith'] scores = [100, 95, 95, 130, 58, 74] import itertools as it score_iter = it.cycle(scores) P = [Player(fn, ln, next(score_iter)) for fn in fnames for ln in lnames] cmp(P[0], P[1]) # returns -1 sorted(P) # throws TypeError: unorderable types Player() Player() The sorted function works when I define __lt__. I must be misreading the documentation, because I read for the documentation __cmp__ that it is called if none of the other rich comparison functions are defined. Is this a bug in Python 3.0rc1, or am I missing something? Secondly, say that we suddenly need another sorting order, where we want to sort by decreasing score and then by DECREASING last name (instead of increasing last name, defined above). Now that the comparison function argument is taken away from the sorted builtin, how do we accomplish this with the key parameter? Thank you I don't know about __cmp__ but for the second part of the question you can probably do: sorted(P, key=lambda p: (p.score, p.lname), reverse=True) HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Python newbie question re Strings and integers
rmac a écrit : Ah! Arghh!!! You are so correct on the usage of the ':' Python syntax is a little different from what I am used to. I don't know what you're used to, but chances are that more than the syntax differs !-) -- http://mail.python.org/mailman/listinfo/python-list
matrix algebra
Hi, My OS is Linux (openSUSE 10.3) and my interest in retirement is Python applications to Structural Analysis of Civil Engineering structures, currently in 2 dimensions only (under GPL). Modern Structural Analysis is highly matrix oriented, but requires only a few basic matrix operations, namely matrix creation, transposition, multiplication, invertion and linear equation solution. For stability analysis one would require Eigenvalues and Eigenvectors. In 3 dimensions, additionally highly desirable would be vector algebra. The packages do have all these functions, but currently only the basic functions are in the wrapper. There are several packages for matrix algebra. I tried Numeric, numpy and numarray. All three are very good, but each uses different syntax. Not a good thing for teaching... So I wrote a little python wrapper (under GPL) to unify all packages with the same simple and transparent syntax. Currently it deals with the Numeric, numpy and numarray and covers creation of zero filled matrices, transposition, matrix multiplication, solution of equations and inversion. This is a very active newsgroup that incudes such giants as Frederik Lundh and countless others. I wonder: 1. Is there any interest in matrix algebra for the masses (I mean interest in a wrapper for a subset of functions of the packages with a unified simple syntax)? 2. What other matrix operations would be required for your area of interest? 3. What other matrix packages, if any, should one include in the wrapper? A copy of the wrapper is stored in a small, public svn repository. If you would like to download it, please contact me by email at. Of course, if there is interest, I would be delighted to upload it to a generally accessible repository. Finally, if this is a re-invention of the wheel (which it may well be), would you kindly let me know? akabaila [at] pcug [dot] org [dot] au. I would be very happy to send you the checkout instructions, but I should discuss that with the people who run the repository. My home page that I quote with my signature is not a repository nor does it have the current programs. OldAl. -- Al Kabaila (Dr) http://akabaila.pcug.org.au/StructuralAnalysis -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
Steven D'Aprano a écrit : I have a class which is not intended to be instantiated. Instead of using the class to creating an instance and then operate on it, I use the class directly, with classmethods. Essentially, the class is used as a function that keeps state from one call to the next. The problem is that I don't know what to call such a thing! Abstract class isn't right, because that implies that you should subclass the class and then instantiate the subclasses. What do you call such a class? nitpick Err... A possible design smell ?-) /nitpick More seriously: this looks quite like a singleton, which in Python is usually implemented way more simply using a module and plain functions. Do you have a use case for specializing this class ? -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
On Mon, 22 Sep 2008 10:12:38 +1000, James Mills wrote: On Mon, Sep 22, 2008 at 9:39 AM, Calvin Spealman [EMAIL PROTECTED] wrote: I call it an obvious misuse and misunderstanding of why you'd use a class in the first place. Either create an instance and not make these things classmethods or just share the stuff in a module-level set of variables. But the instantiating is the best options. Your class attributes might not be globals, but you're still using global state and you should avoid it where you can. I concur. Use a _proper_ state object that you share amongst your other objects. But that's precisely what I want to avoid: I don't want the objects to share *any* state, not even their class. I'm not trying for a Borg or Singleton: the user can call the factory as many times as they want, but the objects returned shouldn't share any state. I don't know if what I want has a name. Judging from people's reactions, I'd say probably not. (For the pedantic: the instances will all have the same methods, but I'm not including methods as state.) For instance, in many of my systems and applications I write, I often have an Environment instance, which is a container object that holds other objects required by parts of the system. Every other component/object in the system that is instantiated recievees exactly one instnace of thie Environment called, env. Accessing shared states amongst components/objects within the system is as simple as this: class Foo(object): def __init__(self, env, *args, **kwargs): self.env = env def foo(self): if self.env.some_state: print Do something useful Seems wasteful to me. Why give every instance it's own instance-level reference to the shared object? Why not make env a class attribute, set once, instead of every time you instantiate the class? class Foo(object): env = env But in any case, this is not the behaviour I want. It's the opposite of the behaviour I want. I don't want the objects to share state. I'm not exactly sure what I said that has given so many people the impression that I do. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
A bit weird dictionary behavior
Hello, just noticed this: Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type help, copyright, credits or license for more information. {1: 2} {1: 2} {True: False} {True: False} {1: 2, True: False} {1: False} This must be because True == 1 and True in {1: 2} True but it still doesn't feel exactly right. Would it be worth submitting a bug? Cheers, .peke -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
Steven D'Aprano [EMAIL PROTECTED] writes: I don't want the objects to share state. I'm not exactly sure what I said that has given so many people the impression that I do. This: Steven D'Aprano [EMAIL PROTECTED] writes: Essentially, the class is used as a function that keeps state from one call to the next. Perhaps if you say what you want that isn't provided by any of a function, a module, or a class. Specifically, what state you want to track, and why it's so important that the state not be available to the instances. -- \ “I love and treasure individuals as I meet them, I loathe and | `\ despise the groups they identify with and belong to.” —George | _o__) Carlin, 2007 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: matrix algebra
On Mon, Sep 22, 2008 at 6:02 PM, Al Kabaila [EMAIL PROTECTED] wrote: Hi, My OS is Linux (openSUSE 10.3) and my interest in retirement is Python applications to Structural Analysis of Civil Engineering structures, currently in 2 dimensions only (under GPL). Modern Structural Analysis is highly matrix oriented, but requires only a few basic matrix operations, namely matrix creation, transposition, multiplication, invertion and linear equation solution. For stability analysis one would require Eigenvalues and Eigenvectors. In 3 dimensions, additionally highly desirable would be vector algebra. The packages do have all these functions, but currently only the basic functions are in the wrapper. There are several packages for matrix algebra. I tried Numeric, numpy and numarray. All three are very good, but each uses different syntax. Not a good thing for teaching... So I wrote a little python wrapper (under GPL) to unify all packages with the same simple and transparent syntax. There is no need for a wrapper. Both numarray and Numeric have been deprecated in favour of numpy, so numpy is the only one you need to use. Numpy should have all the tools you need. If you find something missing, there's a good chance it's included in scipy (which is built on top of numpy). For full details see www.scipy.org. Cheers, Tim Currently it deals with the Numeric, numpy and numarray and covers creation of zero filled matrices, transposition, matrix multiplication, solution of equations and inversion. This is a very active newsgroup that incudes such giants as Frederik Lundh and countless others. I wonder: 1. Is there any interest in matrix algebra for the masses (I mean interest in a wrapper for a subset of functions of the packages with a unified simple syntax)? 2. What other matrix operations would be required for your area of interest? 3. What other matrix packages, if any, should one include in the wrapper? A copy of the wrapper is stored in a small, public svn repository. If you would like to download it, please contact me by email at. Of course, if there is interest, I would be delighted to upload it to a generally accessible repository. Finally, if this is a re-invention of the wheel (which it may well be), would you kindly let me know? akabaila [at] pcug [dot] org [dot] au. I would be very happy to send you the checkout instructions, but I should discuss that with the people who run the repository. My home page that I quote with my signature is not a repository nor does it have the current programs. OldAl. -- Al Kabaila (Dr) http://akabaila.pcug.org.au/StructuralAnalysis -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
On Mon, 22 Sep 2008 10:11:58 +0200, Bruno Desthuilliers wrote: Steven D'Aprano a écrit : I have a class which is not intended to be instantiated. Instead of using the class to creating an instance and then operate on it, I use the class directly, with classmethods. Essentially, the class is used as a function that keeps state from one call to the next. The problem is that I don't know what to call such a thing! Abstract class isn't right, because that implies that you should subclass the class and then instantiate the subclasses. What do you call such a class? nitpick Err... A possible design smell ?-) /nitpick More seriously: this looks quite like a singleton, which in Python is usually implemented way more simply using a module and plain functions. I really don't know why everyone thinks I want a Singleton. I want to uncouple objects, not increase the coupling. Consider a factory function: def factory(x): # a toy example alist = [x] def foo(): return alist return foo Now suppose we instantiate the factory (for lack of a better term): f1 = factory(0) f2 = factory(0) Even though f1 and f2 have the same behaviour, they are obviously not the same object. And although both return a list [0], it is not the same list: f1() == f2() == [0] True f1() is f2() False They have a (very little) amount of state, which is *not* shared: L = f1() L.append(1) f1() [0, 1] f2() [0] But there's only a limited amount of state that functions carry around. I can give them more state like this: f1.attr = 'x' but it isn't good enough if the function needs to refer to it's own state, because functions can only refer to themselves by name and the factory can't know what name the function will be bound to. As far as I know, the only objects that know how to refer to themselves no matter what name they have are classes and instances. And instances share at least some state, by virtue of having the same class. (Pedants will argue that classes also share state, by virtue of having the same metaclass. Maybe so, but that's at a deep enough level that I don't care.) I'm now leaning towards just having factory() instantiate the class and return the instance, instead of having to do metaclass chicanery. Because the class is built anew each time by the factory, two such instances aren't actually sharing the same class. I think that will reduce confusion all round (including mine!). Hopefully now that I've explained what I want in more detail, it won't seem so bizarre. Factory functions do it all the time. Is there a name for this pattern? Thanks to everyone who commented, your comments helped me reason out a better alternative to what I first suggested. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py
En Sun, 21 Sep 2008 19:42:10 -0300, Blubaugh, David A. [EMAIL PROTECTED] escribió: Sir, Thank you for your reply. This is as to how I developed my .pyd file. I entered the following commands within my MS-DOS prompt within Windows XP: C:\python25\Scripts C:\python25\python f2py.py -c --fcompiler=gnu95 --compiler=mingw32 -m hello hello.f90 I am using the gfortran compiler, that was prescribed to use, as well as, the required commands on the following website: http://www.scipy.org/F2PY_Window https://webmail.belcan.com/exchweb/bin/redir.asp?URL=http://www.scipy.org/F2PY_Window I comes down to that yes, I am able to generate a .pyd file, which was generated by f2py. However, when I tried to import this file into my python script program I was given the following error: error 193?? I do not know as to what I am doing incorrectly, since I am generating a .pyd file by f2py? If I am doing anything that is incorrect, then why am I EVEN ABLE TO GENERATE A .PYD FILE IN THE FIRST PLACE??? Any Help will be greatly appreciated! Below there is a transcript of a compile session. I've used a somewhat old version of mingw and g77, scipy 1.1.1, python 2.5.2: C:\TEMP\fordir /b dscal.for C:\TEMP\fortype dscal.for SUBROUTINE DSCAL(N, ALPHA, X) * * X - ALPHA * X * INTEGER N DOUBLE PRECISION ALPHA DOUBLE PRECISION X(*) DO I = 1, N X(I) = ALPHA * X(I) END DO WRITE (*,*) ALPHA RETURN END C:\TEMP\forg77 --version GNU Fortran (GCC) 3.4.2 (mingw-special) Copyright (C) 2004 Free Software Foundation, Inc. GNU Fortran comes with NO WARRANTY, to the extent permitted by law. You may redistribute copies of GNU Fortran under the terms of the GNU General Public License. For more information about these matters, see the file named COPYING or type the command `info -f g77 Copying'. C:\TEMP\forpython -V Python 2.5.2 C:\TEMP\forpython c:\apps\python25\scripts\f2py.py -v 2_5590 C:\TEMP\forpython c:\apps\python25\scripts\f2py.py -c -m dscal dscal.for [...lots of output...] Found executable c:\apps\mingw\bin\g77.exe gnu: no Fortran 90 compiler found customize Mingw32CCompiler using scons Found executable c:\apps\mingw\bin\g++.exe [...] gcc -mno-cygwin -O2 -Wall -Wstrict-prototypes -Ic:\docume~1\gabriel\config~1\tem p\tmpoygjnk\src.win32-2.5 -IC:\Apps\Python25\lib\site-packages\numpy\core\includ e -IC:\Apps\Python25\include -IC:\Apps\Python25\PC -c c:\docume~1\gabriel\config ~1\temp\tmpoygjnk\src.win32-2.5\dscalmodule.c -o c:\docume~1\gabriel\config~1\te mp\tmpoygjnk\Release\docume~1\gabriel\config~1\temp\tmpoygjnk\src.win32-2.5\dsca lmodule.o gcc -mno-cygwin -O2 -Wall -Wstrict-prototypes -Ic:\docume~1\gabriel\config~1\tem p\tmpoygjnk\src.win32-2.5 -IC:\Apps\Python25\lib\site-packages\numpy\core\includ e -IC:\Apps\Python25\include -IC:\Apps\Python25\PC -c c:\docume~1\gabriel\config ~1\temp\tmpoygjnk\src.win32-2.5\fortranobject.c -o c:\docume~1\gabriel\config~1\ temp\tmpoygjnk\Release\docume~1\gabriel\config~1\temp\tmpoygjnk\src.win32-2.5\fo rtranobject.o [...] c:\apps\mingw\bin\g77.exe -g -Wall -mno-cygwin -g -Wall -mno-cygwin -shared c:\d ocume~1\gabriel\config~1\temp\tmpoygjnk\Release\docume~1\gabriel\config~1\temp\t mpoygjnk\src.win32-2.5\dscalmodule.o c:\docume~1\gabriel\config~1\temp\tmpoygjnk \Release\docume~1\gabriel\config~1\temp\tmpoygjnk\src.win32-2.5\fortranobject.o c:\docume~1\gabriel\config~1\temp\tmpoygjnk\Release\dscal.o -Lc:\apps\mingw\lib -Lc:\apps\mingw\lib\gcc\mingw32\3.4.2 -LC:\Apps\Python25\libs -LC:\Apps\Python25 \PCBuild -lpython25 -lg2c -o .\dscal.pyd [...] C:\TEMP\fordir /b dscal.for dscal.pyd C:\TEMP\forpython Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. py import numpy py import dscal py print dscal.dscal.__doc__ dscal - Function signature: dscal(n,alpha,x) Required arguments: n : input int alpha : input float x : input rank-1 array('d') with bounds (*) py v = numpy.array([1,2,3,4,5], 'd') py print v [ 1. 2. 3. 4. 5.] py dscal.dscal(len(v), 2, v) 2. py print v [ 2. 4. 6. 8. 10.] -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
On 22 Sep 2008 09:07:43 GMT, Steven D'Aprano But that's precisely what I want to avoid: I don't want the objects to share *any* state, not even their class. I'm not trying for a Borg or Singleton: the user can call the factory as many times as they want, but the objects returned shouldn't share any state. I don't know if what I want has a name. Judging from people's reactions, I'd say probably not. Snce when are users ever involved in programming problems or programming languages ? --JamesMills -- -- -- Problems are solved by method -- http://mail.python.org/mailman/listinfo/python-list
Re: A bit weird dictionary behavior
On 22 Sep, 10:25, Pekka Laukkanen [EMAIL PROTECTED] wrote: Hello, just noticed this: Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type help, copyright, credits or license for more information. {1: 2} {1: 2} {True: False} {True: False} {1: 2, True: False} {1: False} This must be because True == 1 and True in {1: 2} True That's exactly the reason! but it still doesn't feel exactly right. Would it be worth submitting a bug? I don't think it can be considered as a bug, for the reason you gave above and because dictionary keys are by definition unique with respect to equality. Perhaps you could call it a surprising feature :) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
Steven D'Aprano a écrit : On Mon, 22 Sep 2008 10:11:58 +0200, Bruno Desthuilliers wrote: Steven D'Aprano a écrit : I have a class which is not intended to be instantiated. Instead of using the class to creating an instance and then operate on it, I use the class directly, with classmethods. Essentially, the class is used as a function that keeps state from one call to the next. The problem is that I don't know what to call such a thing! Abstract class isn't right, because that implies that you should subclass the class and then instantiate the subclasses. What do you call such a class? nitpick Err... A possible design smell ?-) /nitpick More seriously: this looks quite like a singleton, which in Python is usually implemented way more simply using a module and plain functions. I really don't know why everyone thinks I want a Singleton. May I quote you ? Instead of using the class to creating an instance and then operate on it, I use the class directly, with classmethods. Essentially, the class is used as a function that keeps state from one call to the next. I want to uncouple objects, not increase the coupling. Consider a factory function: def factory(x): # a toy example alist = [x] def foo(): return alist return foo Now suppose we instantiate the factory (for lack of a better term): f1 = factory(0) f2 = factory(0) Even though f1 and f2 have the same behaviour, they are obviously not the same object. And although both return a list [0], it is not the same list: f1() == f2() == [0] True f1() is f2() False They have a (very little) amount of state, which is *not* shared: L = f1() L.append(1) f1() [0, 1] f2() [0] But there's only a limited amount of state that functions carry around. I can give them more state like this: f1.attr = 'x' but it isn't good enough if the function needs to refer to it's own state, because functions can only refer to themselves by name and the factory can't know what name the function will be bound to. Then define your own callable type. As far as I know, the only objects that know how to refer to themselves no matter what name they have are classes and instances. And instances share at least some state, by virtue of having the same class. Is that a problem in your use case, and if so, why ??? (Pedants will argue that classes also share state, by virtue of having the same metaclass. Maybe so, but that's at a deep enough level that I don't care.) I'm now leaning towards just having factory() instantiate the class and return the instance, instead of having to do metaclass chicanery. Because the class is built anew each time by the factory, two such instances aren't actually sharing the same class. I think that will reduce confusion all round (including mine!). Hopefully now that I've explained what I want in more detail, it won't seem so bizarre. Factory functions do it all the time. Is there a name for this pattern? Thanks to everyone who commented, your comments helped me reason out a better alternative to what I first suggested. Glad to know you found something helpful in all these answers, but as far as I'm concerned, I'm afraid I still fail to understand what exactly you're after... -- http://mail.python.org/mailman/listinfo/python-list
Re: BadStatusLine:
noelob a écrit : Hi All, During performance testing of my web application, I occasionally get a BadStatusLine exception from httplib. Reading http://docs.python.org/lib/module-httplib.html#l2h-4021 tells me that it's Raised if a server responds with a HTTP status code that we don't understand. Is there a way to find what the actual status code returned was? I.e. the value that caused the exception to be thrown? Under what circumstances is a BadStatusLine normally thrown? (e.g. data corruption?) httplib is a pure-python module, so nothing prevents you from reading the source code to get more accurate informations. It appears that this exception is raised when: - the status line is empty - the 'strict' flag is on and the status line didn't start with 'HTTP/' - the 'status' part of the status line is not convertible to an int - the status code ('status' part of the status line, converted to an int) is lower than 100 or higher than 999 NB: I may have missed something... In all cases, the offending status line is accessible as either .line and .args attribute of the exception. I'm quite new to python, but not to programming. Apologies if this is a silly question ;) Well... Not a silly question IMHO, but surely one you could have solved by yourself. It only requires two commands on an average posix system: - cd /your/python/install/lib/ - grep -A5 -B5 BadStatusLine httplib.py HTH -- http://mail.python.org/mailman/listinfo/python-list
imagefap showfavorites - Free
imagefap showfavorites . . . ***CLICK HERE http://vids365.cn/imagefap-showfavorites * . . . . . . . . . . . . imagefap showfavorites -- http://mail.python.org/mailman/listinfo/python-list
www amateurgalore net - Free
www amateurgalore net . . . ***CLICK HERE http://vids365.cn/www-amateurgalore-net * . . . . . . . . . . . . www amateurgalore net -- http://mail.python.org/mailman/listinfo/python-list
redtube xtube youporn - Free
redtube xtube youporn . . . ***CLICK HERE http://vids365.cn/redtube-xtube-youporn * . . . . . . . . . . . . redtube xtube youporn -- http://mail.python.org/mailman/listinfo/python-list
download from redtube - Free
download from redtube . . . ***CLICK HERE http://vids365.cn/download-from-redtube * . . . . . . . . . . . . download from redtube -- http://mail.python.org/mailman/listinfo/python-list
www shockingtube com - Free
www shockingtube com . . . ***CLICK HERE http://vids365.cn/www-shockingtube-com * . . . . . . . . . . . . www shockingtube com -- http://mail.python.org/mailman/listinfo/python-list
Re: New Web2Py framework SLASHES development time...
On 22 Sep, 04:49, Steve Shephed [EMAIL PROTECTED] wrote: bhttp://www.web2py.comWeb2Py - Python Framework/b is the newest kid on the block for Python frameworks. I'm not going to dwell on the merits of web2py, I'm afraid... It has a lot of features that simply are not there in other frameworks. Even Ruby!. You can design database models graphically online. I had a closer look at the model designer, and the client-side magic seems to originate from this project: http://ondras.zarovi.cz/sql/ It looks quite fancy, especially since it all seems to be happening in the browser. Thanks for indirectly bringing this to our attention! ;-) Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
2008/9/22 Bruno Desthuilliers [EMAIL PROTECTED]: Steven D'Aprano a écrit : On Mon, 22 Sep 2008 10:11:58 +0200, Bruno Desthuilliers wrote: Steven D'Aprano a écrit : I have a class which is not intended to be instantiated. Instead of using the class to creating an instance and then operate on it, I use the class directly, with classmethods. Essentially, the class is used as a function that keeps state from one call to the next. Sounds to me like a functor, aka a function object: http://en.wikipedia.org/wiki/Function_object -- Tim Rowe -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about sorted in Python 3.0rc1
josh logan wrote: A better example would be sorting by increasing last name and decreasing first name. This would be easy with the sort function comparator, but I can't see how to do the same with the key argument. Is the only solution to decorate the Player objects in another class that has the appropriate __cmp__ function (or whatever is needed) and then retrieve the Player objects back? Python's sort algorithm is guaranteed to be stable; therefore you can sort twice: ordered = sorted(players, key=lambda p: p.fname, reverse=True) ordered.sort(key=lambda p: p.lname) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: dict generator question
Steven D'Aprano: Extending len() to support iterables sounds like a good idea, except that it's not. Python language lately has shifted toward more and more usage of lazy iterables (see range lazy by default, etc). So they are now quite common. So extending len() to make it act like leniter() too is a way to adapt a basic Python construct to the changes of the other parts of the language. In languages like Haskell you can count how many items a lazy sequence has. But those sequences are generally immutable, so they can be accessed many times, so len(iterable) doesn't exhaust them like in Python. So in Python it's less useful. This is a common situation where I can only care of the len of the g group: [leniter(g) for h,g in groupby(iterable)] There are other situations where I may be interested only in how many items there are: leniter(ifilter(predicate, iterable)) leniter(el for el in iterable if predicate(el)) For my usage I have written a version of the itertools module in D (a lot of work, but the result is quite useful and flexible, even if I miss the generator/iterator syntax a lot), and later I have written a len() able to count the length of lazy iterables too (if the given variable has a length attribute/property then it returns that value), and I have found that it's useful often enough (almost as the string.xsplit()). But in Python there is less need for a len() that counts lazy iterables too because you can use the following syntax that isn't bad (and isn't available in D): [sum(1 for x in g) for h,g in groupby(iterable)] sum(1 for x in ifilter(predicate, iterable)) sum(1 for el in iterable if predicate(el)) So you and Python designers may choose to not extend the semantics of len() for various good reasons, but you will have a hard time convincing me it's a useless capability :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Encoding.ASCII.GetBytes similar for Python ?
Hi, how can i do what Encoding.ASCII.GetBytes (in .net, c#) does with the strings. I am trying to query some dns server to check its response using udp sockets. Some of the source below: # encoding: utf8 import socket import sys import struct IP_PORT = 53 server_host = ('4.2.2.1', IP_PORT) transaction_id = Q1 TIMEOUT = 5 type_string = \u0001\u\u\u0001\u\u\u\u\u\u trailer_string = \u\u\u0001\u\u0001 address = 'google.com' url_name_start, domain_name = address.split(.) # Query format copied from the C# example. #QueryString = TransactionID1 + TypeString + (char)URLNameStart.Length + URLNameStart + (char)DomainName.Length + DomainName+ TrailerString; query = (transaction_id + type_string + str(len(url_name_start)) + url_name_start + str(len(domain_name)) + domain_name + trailer_string) print query sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(TIMEOUT) sock.connect(server_host) sock.send(query) data = sock.recv(512) for data_item in data: try: print chr(data_item) except: print data_item But it just returns trash: python dns_checker.py Q1\u0001\u\u\u0001\u\u\u\u\u\u6google3com \u\ u\u0001\u\u0001 Q 1 Ï ◄ Any advice ? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: BadStatusLine:
noelob wrote: Hi All, During performance testing of my web application, I occasionally get a BadStatusLine exception from httplib. Reading http://docs.python.org/lib/module-httplib.html#l2h-4021 tells me that it's Raised if a server responds with a HTTP status code that we don't understand. Is there a way to find what the actual status code returned was? I.e. the value that caused the exception to be thrown? Under what circumstances is a BadStatusLine normally thrown? (e.g. data corruption?) I'm quite new to python, but not to programming. Apologies if this is a silly question ;) Bruno gave some advice already. I can only add that for the general task of inspecting HTTP-traffic, tools such as axis-tcpmon or wireshark are useful. There you can see what happens on the protocol level. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about sorted in Python 3.0rc1
On Sep 22, 3:41 am, Arnaud Delobelle [EMAIL PROTECTED] wrote: On 22 Sep, 04:05, josh logan [EMAIL PROTECTED] wrote: Hello, I have 2 questions. Say I have this class: class Player(object): def __init__(self, fname, lname, score): self.score = score self.fname = fname self.lname = lname def __cmp__(self, other): return (-cmp(self.score, other.score) or cmp(self.lname, other.lname) or cmp(self.fname, other.fname)) def __repr__(self): return 'Player(fname={0.fname}, lname={0.lname}, score={0.score})'.format(self) def __eq__(self, others): if isinstance(other, Player): return (self.score == other.score and self.lname == other.lname and self.fname == other.fname) return False def __ne__(self, others): return not self.__eq__(others) fnames = ['Julie', 'Ben', 'Jason', 'David'] lnames = ['Parks', 'Smith'] scores = [100, 95, 95, 130, 58, 74] import itertools as it score_iter = it.cycle(scores) P = [Player(fn, ln, next(score_iter)) for fn in fnames for ln in lnames] cmp(P[0], P[1]) # returns -1 sorted(P) # throws TypeError: unorderable types Player() Player() The sorted function works when I define __lt__. I must be misreading the documentation, because I read for the documentation __cmp__ that it is called if none of the other rich comparison functions are defined. Is this a bug in Python 3.0rc1, or am I missing something? Secondly, say that we suddenly need another sorting order, where we want to sort by decreasing score and then by DECREASING last name (instead of increasing last name, defined above). Now that the comparison function argument is taken away from the sorted builtin, how do we accomplish this with the key parameter? Thank you I don't know about __cmp__ but for the second part of the question you can probably do: sorted(P, key=lambda p: (p.score, p.lname), reverse=True) HTH -- Arnaud Thank you for the prompt reply. I didn't think my second question completely through. A better example would be sorting by increasing last name and decreasing first name. This would be easy with the sort function comparator, but I can't see how to do the same with the key argument. Is the only solution to decorate the Player objects in another class that has the appropriate __cmp__ function (or whatever is needed) and then retrieve the Player objects back? -- http://mail.python.org/mailman/listinfo/python-list
Re: A bit weird dictionary behavior
Pekka Laukkanen: but it still doesn't feel exactly right. Would it be worth submitting a bug? It feels wrong because it is. In a tidier language (Pascal, Java, etc) a boolean and an integer must be different types. Keeping booleans and integers separated may avoid some bugs too (I don't know how many/ often). But the Python language copies many things from C, where most things are chosen for practical purposes and maximum efficiency (and from much simpler Python implementations, where there was no boolean type, so bools are grafted in), so it's not a bug, and I think it will not be fixed soon (Python 3 was probably the last chance to change it, for several years to come). So you probably have to live with this illogical behavior. On the other hand it has some little practical advantages, you can do: sum(x == y for x in iterable) That also equals to a more tidy: sum(1 for x in iterable if x == y) Regarding the dict, they are dynamically typed, but good programming practice (that comes from experience of bugs that have bitten you) tells you that generally it's better to be careful with the inserting different types into a dict; often it's better to avoid doing it. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about sorted in Python 3.0rc1
josh logan [EMAIL PROTECTED] wrote: sorted(P) # throws TypeError: unorderable types Player() Player() The sorted function works when I define __lt__. I must be misreading the documentation, because I read for the documentation __cmp__ that it is called if none of the other rich comparison functions are defined. You're either misreading or forgetting that __eq__ and __ne__, which you define, are rich comparison functions. __cmp__ will only be called for a comparison when *none* of the rich comparison functions are defined, not just the one in question. -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ Frankly I have no feelings towards penguins one way or the other -- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
Tim Rowe a écrit : 2008/9/22 Bruno Desthuilliers [EMAIL PROTECTED]: Steven D'Aprano a écrit : On Mon, 22 Sep 2008 10:11:58 +0200, Bruno Desthuilliers wrote: Steven D'Aprano a écrit : I have a class which is not intended to be instantiated. Instead of using the class to creating an instance and then operate on it, I use the class directly, with classmethods. Essentially, the class is used as a function that keeps state from one call to the next. Sounds to me like a functor, aka a function object: http://en.wikipedia.org/wiki/Function_object Ok, then the simple solution is to implement a callable type (__call__ method), possibly with appropriate support for the descriptor protocol if it's meant to be usable as a method. -- http://mail.python.org/mailman/listinfo/python-list
Re: Encoding.ASCII.GetBytes similar for Python ?
Hi, Rui wrote: Hi, how can i do what Encoding.ASCII.GetBytes (in .net, c#) does with the strings. I am trying to query some dns server to check its What would it do? response using udp sockets. Some of the source below: # encoding: utf8 import socket import sys import struct IP_PORT = 53 server_host = ('4.2.2.1', IP_PORT) transaction_id = Q1 TIMEOUT = 5 type_string = \u0001\u\u\u0001\u\u\u\u\u\u trailer_string = \u\u\u0001\u\u0001 address = 'google.com' url_name_start, domain_name = address.split(.) # Query format copied from the C# example. #QueryString = TransactionID1 + TypeString + (char)URLNameStart.Length + URLNameStart + (char)DomainName.Length + DomainName+ TrailerString; query = (transaction_id + type_string + str(len(url_name_start)) + url_name_start + str(len(domain_name)) + domain_name + trailer_string) print query You should refrain from trying a 1:1 translation from one language to another. This makes funny things with natural languages as well as it is horribly with computer languages. You should really read on string formatting in python. Also, while indeed usefull to understand whats going on for production use this is not recommended anymore, since you would have to randomize ports for requests instead of using fixed 53UDP. I'd recommend having a look on python adns - http://code.google.com/p/adns-python/ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(TIMEOUT) sock.connect(server_host) sock.send(query) data = sock.recv(512) for data_item in data: try: print chr(data_item) this is never going to work since recv() returns a string buffer, not a list of integers. HTH Tino smime.p7s Description: S/MIME Cryptographic Signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about sorted in Python 3.0rc1
On 22 Sep, 11:52, josh logan [EMAIL PROTECTED] wrote: On Sep 22, 3:41 am, Arnaud Delobelle [EMAIL PROTECTED] wrote: On 22 Sep, 04:05, josh logan [EMAIL PROTECTED] wrote: Hello, I have 2 questions. Say I have this class: class Player(object): def __init__(self, fname, lname, score): self.score = score self.fname = fname self.lname = lname def __cmp__(self, other): return (-cmp(self.score, other.score) or cmp(self.lname, other.lname) or cmp(self.fname, other.fname)) def __repr__(self): return 'Player(fname={0.fname}, lname={0.lname}, score={0.score})'.format(self) def __eq__(self, others): if isinstance(other, Player): return (self.score == other.score and self.lname == other.lname and self.fname == other.fname) return False def __ne__(self, others): return not self.__eq__(others) fnames = ['Julie', 'Ben', 'Jason', 'David'] lnames = ['Parks', 'Smith'] scores = [100, 95, 95, 130, 58, 74] import itertools as it score_iter = it.cycle(scores) P = [Player(fn, ln, next(score_iter)) for fn in fnames for ln in lnames] cmp(P[0], P[1]) # returns -1 sorted(P) # throws TypeError: unorderable types Player() Player() The sorted function works when I define __lt__. I must be misreading the documentation, because I read for the documentation __cmp__ that it is called if none of the other rich comparison functions are defined. Is this a bug in Python 3.0rc1, or am I missing something? Secondly, say that we suddenly need another sorting order, where we want to sort by decreasing score and then by DECREASING last name (instead of increasing last name, defined above). Now that the comparison function argument is taken away from the sorted builtin, how do we accomplish this with the key parameter? Thank you I don't know about __cmp__ but for the second part of the question you can probably do: sorted(P, key=lambda p: (p.score, p.lname), reverse=True) HTH -- Arnaud Thank you for the prompt reply. I didn't think my second question completely through. A better example would be sorting by increasing last name and decreasing first name. This would be easy with the sort function comparator, but I can't see how to do the same with the key argument. Is the only solution to decorate the Player objects in another class that has the appropriate __cmp__ function (or whatever is needed) and then retrieve the Player objects back? You can use the stability of the sorting algorithm as Peter pointed out. If decorating, you don't need to decorate the Player objects, but you can decorate the keys instead: e.g class RevStr(str): def __lt__(self, other): return str.__lt__(other, self) def __ge__(self, other): retrn str.__gt__(other, self) then you can write: sorted(P, key=lambda p:(p.lname, RevStr(p.fname))) -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
On 22 Sep, 10:32, Steven D'Aprano [EMAIL PROTECTED] wrote: but it isn't good enough if the function needs to refer to it's own state, because functions can only refer to themselves by name and the factory can't know what name the function will be bound to. As far as I know, the only objects that know how to refer to themselves no matter what name they have are classes and instances. And instances share at least some state, by virtue of having the same class. Here is a simple way to make a function able to refer to its own state: def bindfunction(f): def bound_f(*args, **kwargs): return f(bound_f, *args, **kwargs) bound_f.__name__ = f.__name__ return bound_f @bindfunction ... def foo(me, x): ... me.attr.append(x) ... return me.attr ... foo.attr = [] foo(3) [3] foo(5) [3, 5] -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about sorted in Python 3.0rc1
On Sep 22, 7:32 am, Sion Arrowsmith [EMAIL PROTECTED] wrote: josh logan [EMAIL PROTECTED] wrote: sorted(P) # throws TypeError: unorderable types Player() Player() The sorted function works when I define __lt__. I must be misreading the documentation, because I read for the documentation __cmp__ that it is called if none of the other rich comparison functions are defined. You're either misreading or forgetting that __eq__ and __ne__, which you define, are rich comparison functions. __cmp__ will only be called for a comparison when *none* of the rich comparison functions are defined, not just the one in question. -- \S -- [EMAIL PROTECTED] --http://www.chaos.org.uk/~sion/ Frankly I have no feelings towards penguins one way or the other -- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump Hello Sion, When I don't define the __eq__ and __ne__ comparison functions, the same unexpected behavior occurs. -- http://mail.python.org/mailman/listinfo/python-list
Re: Encoding.ASCII.GetBytes similar for Python ?
On Mon, 22 Sep 2008 04:23:09 -0700, Rui wrote: Hi, how can i do what Encoding.ASCII.GetBytes (in .net, c#) does with the strings. I am trying to query some dns server to check its response using udp sockets. Some of the source below: # encoding: utf8 import socket import sys import struct IP_PORT = 53 server_host = ('4.2.2.1', IP_PORT) transaction_id = Q1 TIMEOUT = 5 type_string = \u0001\u\u\u0001\u\u\u\u\u\u trailer_string = \u\u\u0001\u\u0001 Are you sure you want normal byte strings with *that* content!? In [90]: s = \u\u\u0001\u\u0001 In [91]: len(s) Out[91]: 30 In [92]: print s \u\u\u0001\u\u0001 This is not 5 unicode characters but 30 ASCII characters. But why using unicode anyway? I guess the DNS server expects bytes and not unicode characters. address = 'google.com' url_name_start, domain_name = address.split(.) # Query format copied from the C# example. #QueryString = TransactionID1 + TypeString + (char)URLNameStart.Length + URLNameStart + (char)DomainName.Length + DomainName+ TrailerString; query = (transaction_id + type_string + str(len(url_name_start)) + url_name_start + str(len(domain_name)) + domain_name + trailer_string) print query sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(TIMEOUT) sock.connect(server_host) sock.send(query) data = sock.recv(512) for data_item in data: try: print chr(data_item) except: print data_item This will always end up in the ``except`` branch because `data` is a string and `chr()` expects integers. Any chance you wanted `ord()` instead? When you print out trash please use `repr()` so we can see what trash *exactly* you get. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about sorted in Python 3.0rc1
josh logan [EMAIL PROTECTED] writes: sorted(P) # throws TypeError: unorderable types Player() Player() The sorted function works when I define __lt__. I must be misreading the documentation, because I read for the documentation __cmp__ that it is called if none of the other rich comparison functions are defined. Is this a bug in Python 3.0rc1, or am I missing something? What documentation are you referring to, exactly? The whole __cmp__ thing was supposed to be removed from Python 3, so mention of it sounds like a documentation bug. Secondly, say that we suddenly need another sorting order, where we want to sort by decreasing score and then by DECREASING last name (instead of increasing last name, defined above). Now that the comparison function argument is taken away from the sorted builtin, how do we accomplish this with the key parameter? By calling sort twice on the sequence: lst.sort(key=lambda x: x.score) lst.sort(key=lambda x: x.last_name, reverse=True) As much as I like the key argument, I believe it was a mistake to remove cmp, simply because it was the more general mechanism. Emulating cmp with key is possible, but it requires creating a bunch of objects for each sort. (I'm aware that list.sort caches the calculated keys, but it still has to create as many of them as there are list items.) -- http://mail.python.org/mailman/listinfo/python-list
Re: matrix algebra
On Sep 22, 4:02 am, Al Kabaila [EMAIL PROTECTED] wrote: This is a very active newsgroup that incudes such giants as Frederik Lundh He looks rather small to me in this picture: http://www.python.org/~guido/confpix/flundh-2.jpg -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
2008/9/22 Bruno Desthuilliers [EMAIL PROTECTED]: Sounds to me like a functor, aka a function object: http://en.wikipedia.org/wiki/Function_object Ok, then the simple solution is to implement a callable type (__call__ method), possibly with appropriate support for the descriptor protocol if it's meant to be usable as a method. Yes -- and instantiate the thing and keep the state in the instance, rather than keeping the state in the class, so that it's possible to safely have more than one of them if a later design change calls for it (probably what led people off onto the sidetrack of thinking a singleton was called for). That's the classic way of implementing a class [to be] used as a function. -- Tim Rowe -- http://mail.python.org/mailman/listinfo/python-list
Re: understanding list scope
Hi, Alex wrote: Hi all! I have a problem understanding the behaviour of this snippet: data_set = ({param:a},{param:b},{param:c}) for i in range(len(data_set)): ds = data_set[:] data = ds[i] if i == 1: data['param'] = y if i == 2: data['param'] = x print data_set Beside the data copy which is explained in the other posts, what is the problem you want to solve? Would data_set[1]['param']=x data_set[2]['param']=y not doing the same? or more to your point: ds=data_set[:1]+[dict(param=x),dict(param=y)]+data_set[2:] HTH Tino smime.p7s Description: S/MIME Cryptographic Signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about sorted in Python 3.0rc1
On Sep 22, 9:29 am, Hrvoje Niksic [EMAIL PROTECTED] wrote: josh logan [EMAIL PROTECTED] writes: sorted(P) # throws TypeError: unorderable types Player() Player() The sorted function works when I define __lt__. I must be misreading the documentation, because I read for the documentation __cmp__ that it is called if none of the other rich comparison functions are defined. Is this a bug in Python 3.0rc1, or am I missing something? What documentation are you referring to, exactly? The whole __cmp__ thing was supposed to be removed from Python 3, so mention of it sounds like a documentation bug. Secondly, say that we suddenly need another sorting order, where we want to sort by decreasing score and then by DECREASING last name (instead of increasing last name, defined above). Now that the comparison function argument is taken away from the sorted builtin, how do we accomplish this with the key parameter? By calling sort twice on the sequence: lst.sort(key=lambda x: x.score) lst.sort(key=lambda x: x.last_name, reverse=True) As much as I like the key argument, I believe it was a mistake to remove cmp, simply because it was the more general mechanism. Emulating cmp with key is possible, but it requires creating a bunch of objects for each sort. (I'm aware that list.sort caches the calculated keys, but it still has to create as many of them as there are list items.) It looks like __cmp__ is still in the documentation, and it seems to work somewhat in Python 3.0rc1. Here is the link to the documnetation http://docs.python.org/dev/3.0/reference/datamodel.html#object.__cmp__ -- http://mail.python.org/mailman/listinfo/python-list
Re: A bit weird dictionary behavior
Hi, [EMAIL PROTECTED] wrote: Pekka Laukkanen: ... On the other hand it has some little practical advantages, you can do: sum(x == y for x in iterable) That also equals to a more tidy: sum(1 for x in iterable if x == y) Wouldn't len([x for x in iterable if x==y]) or even shorter: iterable.count(y) not work and read better anyway? even calculating with boolean values isn't neccessary since 'and' and 'foo if bar else blub' are working much better so the type coalescing bool - int - float can really go away. Tino smime.p7s Description: S/MIME Cryptographic Signature -- http://mail.python.org/mailman/listinfo/python-list
Re: A bit weird dictionary behavior
Tino Wildenhain: Wouldn't len([x for x in iterable if x==y]) or even shorter: iterable.count(y) not work and read better anyway? The first version creates an actual list just to take its length, think about how much memory it may use. The second version requires the 'iterable' object to have a count() method, and in general this is false. even calculating with boolean values isn't neccessary since 'and' and 'foo if bar else blub' are working much better so the type coalescing bool - int - float can really go away. I don't understand. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Reading Windows CSV file with LCID entries under Linux.
Dear all, I've stumbled over a problem with Windows Locale ID information and codepages. I'm writing a Python application that parses a CSV file, the format of a line in this file is LCID;Text1;Text2. Each line can contain a different locale id (LCID) and the text fields contain data that is encoded in some codepage which is associated with this LCID. My current data file contains the codes 1033 for German and 1031 for English US (as listed in http://www.microsoft.com/globaldev/reference/lcid-all.mspx). Unfortunately, I cannot find out which Codepage (like cp-1252 or whatever) belongs to which LCID. My question is: How can I convert this data into something more reasonable like unicode? Basically, what I want is something like Text1;Text2, both fields encoded as UTF-8. Can this be done with Python? How can I find out which codepage I have to use for 1033 and 1031? Any help appreciated, Thomas. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading Windows CSV file with LCID entries under Linux.
Thomas My question is: How can I convert this data into something more Thomas reasonable like unicode? Basically, what I want is something Thomas like Text1;Text2, both fields encoded as UTF-8. Can this be Thomas done with Python? How can I find out which codepage I have to Thomas use for 1033 and 1031? There are examples at end of the CSV module documentation which show how to create Unicode readers and writers. You can extend the UnicodeReader class to peek at the LCID field and save the corresponding codepage for the remainder of the line. (This would assume you're not creating CSV files which contain newlines. Each line read would be assumed to be a new record in the file.) Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading Windows CSV file with LCID entries under Linux.
Thomas Troeger wrote: I've stumbled over a problem with Windows Locale ID information and codepages. I'm writing a Python application that parses a CSV file, the format of a line in this file is LCID;Text1;Text2. Each line can contain a different locale id (LCID) and the text fields contain data that is encoded in some codepage which is associated with this LCID. My current data file contains the codes 1033 for German and 1031 for English US (as listed in http://www.microsoft.com/globaldev/reference/lcid-all.mspx). Unfortunately, I cannot find out which Codepage (like cp-1252 or whatever) belongs to which LCID. My question is: How can I convert this data into something more reasonable like unicode? Basically, what I want is something like Text1;Text2, both fields encoded as UTF-8. Can this be done with Python? How can I find out which codepage I have to use for 1033 and 1031? The GetLocaleInfo API call can do that conversion: http://msdn.microsoft.com/en-us/library/ms776270(VS.85).aspx You'll need to use ctypes (or write a c extension) to use it. Be aware that if it doesn't succeed you may need to fall back on cp 65001 -- utf8. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: A bit weird dictionary behavior
Hi, [EMAIL PROTECTED] wrote: Tino Wildenhain: Wouldn't len([x for x in iterable if x==y]) or even shorter: iterable.count(y) not work and read better anyway? The first version creates an actual list just to take its length, think about how much memory it may use. yes it seems len() does not alternatively iterate or __len__ of the generator objects don't allow for an optimization yet. This could be improved so len(x for x in iterable ...) would work and save memory. The second version requires the 'iterable' object to have a count() method, and in general this is false. of course this always depends on the usecase. even calculating with boolean values isn't neccessary since 'and' and 'foo if bar else blub' are working much better so the type coalescing bool - int - float can really go away. I don't understand. if you have a operator b and type(a) type(b) then coercing goes on to convert one partner to the type of the other. So bool currently gets upgrated to int (as int is upgraded to float and so on). If this goes away, the type ambiguity is gone. This would result in 1==True - False HTH Tino PS: are you per chance using a news gateway to post? This seems to screw up threading somehow... Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list smime.p7s Description: S/MIME Cryptographic Signature -- http://mail.python.org/mailman/listinfo/python-list
Top Techniques of Money Making INTERNET CASH MAKING SOLUTIONS
Ultimate Destination For All Online Job Seekers. Online cash online money without investments online paid surveys earn money online. Earn with FUN!!! For More Details Check the Links Below: http://www.tips2internetmarketing.blogspot.com/ http://www.80kpermonth.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Top Techniques of Money Making INTERNET CASH MAKING SOLUTIONS
Ultimate Destination For All Online Job Seekers. Online cash online money without investments online paid surveys earn money online. Earn with FUN!!! For More Details Check the Links Below: http://www.tips2internetmarketing.blogspot.com/ http://www.80kpermonth.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Top Techniques of Money Making INTERNET CASH MAKING SOLUTIONS
Ultimate Destination For All Online Job Seekers. Online cash online money without investments online paid surveys earn money online. Earn with FUN!!! For More Details Check the Links Below: http://www.tips2internetmarketing.blogspot.com/ http://www.80kpermonth.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Why are broken iterators broken?
Cameron Simpson wrote: you probably want the consumer thread to block when it catches up with the producer, rather than exit. It sounds like he wants non-blocking behaviour in his consumer. Roy gave an example, he didn't post a requirements specification. A common example is try to gather a lot of stuff into a single packet, but send a smaller packet promptly if there isn't much stuff. that use case is better solved with a plain list object. no need to make things harder than they are. /F -- http://mail.python.org/mailman/listinfo/python-list
Regex Help
Anybody know of a good regex to parse html links from html code? The one I am currently using seems to be cutting off the last letter of some links, and returning links like http://somesite.co or http://somesite.ph the code I am using is regex = r'a href=[|\']([^|\']+)[|\']' page_text = urllib.urlopen('http://somesite.com') page_text = page_text.read() links = re.findall(regex, text, re.IGNORECASE) -- http://mail.python.org/mailman/listinfo/python-list
Re: Regex Help
Support Desk wrote: the code I am using is regex = r'a href=[|\']([^|\']+)[|\']' that's way too fragile to work with real-life HTML (what if the link has a TITLE attribute, for example? or contains whitespace after the HREF?) you might want to consider using a real HTML parser for this task. page_text = urllib.urlopen('http://somesite.com') page_text = page_text.read() links = re.findall(regex, text, re.IGNORECASE) the RE looks fine for the subset of all valid A elements that it can handle, though. got any examples of pages where you see that behaviour? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
On Sep 22, 8:45 am, Tim Rowe [EMAIL PROTECTED] wrote: 2008/9/22 Bruno Desthuilliers [EMAIL PROTECTED]: Sounds to me like a functor, aka a function object: http://en.wikipedia.org/wiki/Function_object Ok, then the simple solution is to implement a callable type (__call__ method), possibly with appropriate support for the descriptor protocol if it's meant to be usable as a method. Yes -- and instantiate the thing and keep the state in the instance, rather than keeping the state in the class, so that it's possible to safely have more than one of them if a later design change calls for it (probably what led people off onto the sidetrack of thinking a singleton was called for). That's the classic way of implementing a class [to be] used as a function. -- Tim Rowe I think you are either looking for a class that has a generator, or a generator that has a reference to itself. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about sorted in Python 3.0rc1
josh logan wrote: Here is a minimal example showing the problematic behavior. class Int(): def __init__(self, i): self.i = i def __cmp__(self, other): return cmp(self.i, other.i) Is = [Int(i) for i in range(8)] Is.sort() # throws TypeError: unorderable types Int() Int() sorted(Is) # ditto, if above not present The 3.0b2 version of LibRef/ Built-in Types/ Comparisions says Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods __cmp__(), __lt__(), __le__(), __gt__(), and __ge__() (in general, either __cmp__() or both __lt__() and __eq__() are sufficient, if you want the conventional meanings of the comparison operators). The notes for Mutable Sequence .sort() say nothing more. So the exception appears to be a bug, perhaps left over from when there was a plan (since aborted) to delete cmp and __cmp__. If the 3.0c1 version of the docs say the same, and no one says otherwise, I would file a report on the tracker at bugs.python.org, using the minimal example above. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
On Sep 21, 3:39 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: I have a class which is not intended to be instantiated. Instead of using the class to creating an instance and then operate on it, I use the class directly, with classmethods. Essentially, the class is used as a function that keeps state from one call to the next. The problem is that I don't know what to call such a thing! Abstract class isn't right, because that implies that you should subclass the class and then instantiate the subclasses. What do you call such a class? -- Steven It actually sounds like you are doing something similar to the monostate pattern. In Java the monostate pattern is usually implemented by creating a class that only has static functions and variables. You _can_ instantiate it, but every instance will share the same state. In that way it is very similar to the Singleton pattern (http://en.wikipedia.org/wiki/Singleton_pattern). In Python I haven't found a need for monostate, since you can override __new__ and return exactly the same instance. However, you you wanted to be able to inherit a monostate object and share some of the state between the class and subclass it might still be useful. Perhaps if you post some example code? Matt -- http://mail.python.org/mailman/listinfo/python-list
Problems running on hp dual core processor
Python help, I have a number of clients running a program built with python 2.5. One has just purchased an HP with a duel core processor, 2.2G with .099g ram. On the new hp, when they try to print they get an import error; File win32ui.pyc line 12, in module File win32ui.pyc, line 10, in _load ImportError: DLL load failed: The specified module could not be found. The file is there The only difference I could find from their other machines is the processor. -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
Steven D'Aprano wrote: Consider a factory function: def factory(x): # a toy example alist = [x] def foo(): return alist return foo Now suppose we instantiate the factory (for lack of a better term): f1 = factory(0) f2 = factory(0) Your factory is returning closures. This is the functional equivalent of a class returning instances. class factory(object): def __init__(self, x): self.alist = [x] def __call__(self): return self.alist Even though f1 and f2 have the same behaviour, they are obviously not the same object. And although both return a list [0], it is not the same list: f1() == f2() == [0] True f1() is f2() False same results They have a (very little) amount of state, which is *not* shared: L = f1() L.append(1) f1() [0, 1] f2() [0] same results But there's only a limited amount of state that functions carry around. That is why Python has class statements. And instances share at least some state, by virtue of having the same class. If the only class attributes are methods and you do mutate the class, then the fact that f1.__class__ is f2.__class__ is not really shared state. [from a later post] But that's precisely what I want to avoid: I don't want the objects to share *any* state, not even their class. Unless you can show how sharing an immutable __class__ attribute is an actual impediment, this strike me as artificial pedantry and unnecessary self handcuffing. And you obviously can make that attribute effectively immutable by ignoring it and also not changing the class itself. It is just internal, implementation-defined bookkeeping. The identity of immutable objects is irrelevant. If part of your 'unshared state' for each instance were a string, and two instances happened to have the same string value, would you be upset because the interpreter happened to use the same string object instead of two string objects with the same value? Ditto for numbers, tuples, and so on. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Problems running on hp dual core processor
Python help, I have a number of clients running a program built with python 2.5. One has just purchased an HP with a duel core processor, 2.2G with .099g ram. On the new hp, when they try to print they get an import error; File win32ui.pyc line 12, in module File win32ui.pyc, line 10, in _load ImportError: DLL load failed: The specified module could not be found. The file is there The only difference I could find from their other machines is the processor. I would appreciate any help Jim-on-linux -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems running on hp dual core processor
On Sep 22, 1:43 pm, jim-on-linux [EMAIL PROTECTED] wrote: Python help, I have a number of clients running a program built with python 2.5. One has just purchased an HP with a duel core processor, 2.2G with .099g ram. On the new hp, when they try to print they get an import error; File win32ui.pyc line 12, in module File win32ui.pyc, line 10, in _load ImportError: DLL load failed: The specified module could not be found. The file is there The only difference I could find from their other machines is the processor. I have people running my compiled python applications on single and dual core processors with no problem. I suspect that you may just need to compile your application with some different switches, such as bundle=3 in py2exe for example. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems running on hp dual core processor
On Sep 22, 1:43 pm, jim-on-linux [EMAIL PROTECTED] wrote: Python help, I have a number of clients running a program built with python 2.5. One has just purchased an HP with a duel core processor, 2.2G with .099g ram. On the new hp, when they try to print they get an import error; File win32ui.pyc line 12, in module File win32ui.pyc, line 10, in _load ImportError: DLL load failed: The specified module could not be found. The file is there The only difference I could find from their other machines is the processor. I should note that I have had issues if I didn't include all the DLLs that were needed. This error doesn't say exactly which DLL is the issue. I recommend downloading Dependency Walker to find out what it is: http://www.dependencywalker.com/ Mike -- http://mail.python.org/mailman/listinfo/python-list
Job queue using xmlrpc and threading
I'm trying to implement an application that will listen for requests, run them when they are present but also be able to add new requests even while it's running. I've tried to do this using the thread and xmlrpc modules - the idea is that an XML-RPC exposed object tell the queue thread object to add a job. If there are no jobs running, it creates a file, adds the new job to the end and then another consumption thread starts working through the jobs in the file. New jobs coming in are just added to the end of the file by the queue thread. Unfortunately, I can't get it to work. The problem is that the consumption thread seems to read the job queue before it gets written, even though I've used a lock. I've also had the application get to the stage where it ignores ctrl-c, which is a little worrying - I fear it doesn't bode well for future stability... I don't have a lot of experience with multi-threaded applications, so I may well have chosen a poor approach. I've posted the code below. It's in three parts, the job queue, the manager that listens for new requests and an application to add jobs to the queue. Sorry for the long listings... Any guidance gratefully received, Peter === testqueue.py: import thread import time import shutil import os class JobQueue: def __init__(self, filename): self.queuefile = filename self.jobthread = 0 # lock for the jobfile queue file self.jfqlock = thread.allocate_lock() def addJob(self, jobfileuri, email): self.jfqlock.acquire() if not self.jobthread: print starting jobfile consumption thread if os.access(self.queuefile, os.R_OK): print cleaning stale jobfile queue file try: os.remove(self.queuefile) except: print problem removing jobfile queue file raise self.jobthread = thread.start_new_thread(self.main, ()) else: print using existing jobfile consumption thread in file, self.queuefile fh = open(self.queuefile, a) # choose as a delimiter print fh, jobfileuri + + email self.jfqlock.release() return 1 def main(self): while 1: self.jfqlock.acquire() rfh = open(self.queuefile, r) # breakpoint() finput = rfh.readline() print found:, finput if not finput: print finished jobfiles. Closing thread rfh.close() self.jobthread = 0 self.jfqlock.release() return else: print found jobfile in queue: attempting to run # most of this is to shift up the lines in the file tmpname = self.queuefile + .tmp wfh = open(tmpname, w) line = rfh.readline() while line: wfh.write(line) line = rfh.readline() wfh.close() rfh.close() shutil.move(tmpname, self.queuefile) self.jfqlock.release() # lop off the trailing line break print print ***run Starting*** try: self.runJob(finput[:-1]) print ***run finished*** except: print ***run failed*** print def runJob(self, job): time.sleep(2.0) print running job, job if not report: print some problem with run. Cannot mail out report return === queuemanager.py from testqueue import JobQueue from SimpleXMLRPCServer import * class QM: def __init__(self, filename): self.jq = JobQueue(queue.txt) def addJob(self, jobname): self.jq.addJob(jobname, [EMAIL PROTECTED]) if __name__==__main__: qm = QM(jobqueue.txt) rpcserver = SimpleXMLRPCServer((localhost, 8000)) rpcserver.register_instance(qm)
Re: What do you call a class not intended to be instantiated
Aaron Castironpi Brady a écrit : On Sep 22, 8:45 am, Tim Rowe [EMAIL PROTECTED] wrote: 2008/9/22 Bruno Desthuilliers [EMAIL PROTECTED]: Sounds to me like a functor, aka a function object: http://en.wikipedia.org/wiki/Function_object Ok, then the simple solution is to implement a callable type (__call__ method), possibly with appropriate support for the descriptor protocol if it's meant to be usable as a method. Yes -- and instantiate the thing and keep the state in the instance, rather than keeping the state in the class, so that it's possible to safely have more than one of them if a later design change calls for it (probably what led people off onto the sidetrack of thinking a singleton was called for). That's the classic way of implementing a class [to be] used as a function. -- Tim Rowe I think you are either looking for a class that has a generator, or a generator that has a reference to itself. ??? Going back to robot-mode, Aaron ? -- http://mail.python.org/mailman/listinfo/python-list
Re: A bit weird dictionary behavior
[EMAIL PROTECTED] a écrit : Pekka Laukkanen: but it still doesn't feel exactly right. Would it be worth submitting a bug? It feels wrong because it is. In a tidier language (Pascal, Java, etc) a boolean and an integer must be different types. Some would argue (and some did by the time Python grew a 'bool' type) that what is wrong is to have a bool type in a language that already have a wider definition of the truth value of an expression... (snip) -- http://mail.python.org/mailman/listinfo/python-list
Re: Job queue using xmlrpc and threading
Try using the Queue module - http://docs.python.org/lib/module-Queue.html. Here is a tutorial with it - http://www.artfulcode.net/articles/multi-threading-python/. -- http://mail.python.org/mailman/listinfo/python-list
pyArkansas Set for October 4th
This is a reminder of the upcoming pyArkansas one-day Python conference being held on the campus of the University of Central Arkansas on Sat Oct 4, 2008. The schedule is pretty much set ( http://pycamp.python.org/Arkansas/Schedule) and has something for anyone interested in Python, from intro workshops to advanced topics. Jeff Rush and Noah Gift are scheduled to present workshops and talks while Dr. Bernard Chen (UCA Faculty) will teach a 3-hour class on Python for the Absolute Beginner. Eggs, pyGame, standard library, Eclipse and OLPC are some of the other talks scheduled. This is a *FREE* event (we have GREAT sponsors), so all you need to bring is yourself. We have over 45 people -- from 4 States -- registered and tons of great swag and giveaways lined up. See our wiki (http://pycamp.python.org/Arkansas/HomePage) for more details and registration info. Greg Lindstrom Python Artists of Arkansas (pyAR^2) -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
On Sep 22, 2:38 pm, Bruno Desthuilliers [EMAIL PROTECTED] wrote: Aaron Castironpi Brady a écrit : On Sep 22, 8:45 am, Tim Rowe [EMAIL PROTECTED] wrote: 2008/9/22 Bruno Desthuilliers [EMAIL PROTECTED]: Sounds to me like a functor, aka a function object: http://en.wikipedia.org/wiki/Function_object Ok, then the simple solution is to implement a callable type (__call__ method), possibly with appropriate support for the descriptor protocol if it's meant to be usable as a method. Yes -- and instantiate the thing and keep the state in the instance, rather than keeping the state in the class, so that it's possible to safely have more than one of them if a later design change calls for it (probably what led people off onto the sidetrack of thinking a singleton was called for). That's the classic way of implementing a class [to be] used as a function. -- Tim Rowe I think you are either looking for a class that has a generator, or a generator that has a reference to itself. ??? Going back to robot-mode, Aaron ? Not getting the same sense of soul as from my usual posts. I guess so. Might even drop the name change, too... while I'm at it. One more word from you about it and I'm starting a thread, and calling it, Python and my sense of 'soul'. Ha ha. -- http://mail.python.org/mailman/listinfo/python-list
Re: Here's something interesting: sympy crashes in Python 2.6 (Windows)
Fredrik Lundh wrote: Mensanator wrote: I'm not the one who wrote sympy, so I guess I'm not the only one who didn't notice it. If it's a well known problem, then sorry I wasted your time. Given that 2.5 explicitly warns about this specific change: as = 1 stdin:1: Warning: 'as' will become a reserved keyword in Python 2.6 it's an unknown issue only for people who has 1) never used their code under 2.5, or 2) never looks at the output produced by their programs. The PEP-5 process guarantees that users will have at least a year to test their programs and migrate them from use of the deprecated construct to the alternative one, and Python 2.5 was released *two* years ago. So it sure looks like the SimPy folks ignored the established process. Why they've done that is probably a more interesting issue than the change itself. No warnings show up when importing the offending module: Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type help, copyright, credits or license for more information. from sympy.mpmath import specfun So what could be suppressing the warning? -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
Aaron Castironpi Brady a écrit : On Sep 22, 2:38 pm, Bruno Desthuilliers [EMAIL PROTECTED] wrote: (snip) Going back to robot-mode, Aaron ? Not getting the same sense of soul as from my usual posts. I guess so. Might even drop the name change, too... Don't !-) while I'm at it. One more word from you about it and I'm starting a thread, and calling it, Python and my sense of 'soul'. Ha ha. Please bear with me - and understand that the above half-backed half-joke was also an implicit aknowledgement of the recent changes in your mode of communication. I should have added a wink, I think... -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems running on hp dual core processor
Dennis Lee Bieber wrote: Interesting... The only win32ui* on my machine (running v2.4) is a win32ui.pyd (D, not C) and it is part of the PythonWin IDE obtained as part of the ActiveState installer for windows. Oh, and /how much RAM/? .099g sounds rather small; my PDA has .5G of RAM and my desktop machine has 2.0G... A .pyd file is a Python dynamic library file. It's a dll with a different extension and a Python specific entry point. Dynamic libraries are OS and CPU architecture dependent. It might be possible that the computer has an incompatible CPU or a 64bit OS. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
On Sep 22, 3:28 pm, Bruno Desthuilliers [EMAIL PROTECTED] wrote: Aaron Castironpi Brady a écrit : On Sep 22, 2:38 pm, Bruno Desthuilliers [EMAIL PROTECTED] wrote: (snip) Going back to robot-mode, Aaron ? Not getting the same sense of soul as from my usual posts. I guess so. Might even drop the name change, too... Don't !-) while I'm at it. One more word from you about it and I'm starting a thread, and calling it, Python and my sense of 'soul'. Ha ha. Please bear with me - and understand that the above half-backed half-joke was also an implicit aknowledgement of the recent changes in your mode of communication. I should have added a wink, I think... I can attribute it to a change in environment. Going back to robot mode would imply one wasn't always in it, and as such I interpreted a tacit compliment. Thank you for the compliment, Bruno. I don't suppose starting a thread is much of a threat, after all... at least in isolation. Regardless, as I've stated, I find the feedback valuable that there seems (to people) to be more than one context that I'm writing from, and I appreciate the chance to learn about it. It's an observation an erst friend made once that one can never perceive oneself directly. (Whether that's a virtue depends on what difference there is between self-conscious, and self-aware.) -- http://mail.python.org/mailman/listinfo/python-list
Tkinter 3000 WCK Install Problem
I'm trying to install WCK. I downloaded and installed the Windows executable for my Python version. It appeared to run OK. I then downloaded the demo files but find that none run due to error: ImportError: No module named _tk3draw. I'm using ActivePython 2.3.5 on Windows XP Home. What can I do to fix this problem? -- http://mail.python.org/mailman/listinfo/python-list
Re: Here's something interesting: sympy crashes in Python 2.6 (Windows)
Robert Kern wrote: No warnings show up when importing the offending module: Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type help, copyright, credits or license for more information. from sympy.mpmath import specfun So what could be suppressing the warning? a bug in Python 2.5, it seems: more f1.py as = 1 as = 2 as = 3 python f1.py f1.py:1: Warning: 'as' will become a reserved keyword in Python 2.6 f1.py:2: Warning: 'as' will become a reserved keyword in Python 2.6 f1.py:3: Warning: 'as' will become a reserved keyword in Python 2.6 more f2.py as = 1 import os as = 3 python f2.py f2.py:1: Warning: 'as' will become a reserved keyword in Python 2.6 A quick look in parsetok.c reveals that it sets a handling_import flag when it stumbles upon an import statement, a flag that's later used to suppress the warning message. The bug is that the flag isn't reset until the parser sees an ENDMARKER token (end of file), instead of when it sees the next NEWLINE token. (if someone wants to submit this to bugs.python.org, be my guest) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter 3000 WCK Install Problem
garyr wrote: I'm trying to install WCK. I downloaded and installed the Windows executable for my Python version. It appeared to run OK. I then downloaded the demo files but find that none run due to error: ImportError: No module named _tk3draw. I'm using ActivePython 2.3.5 on Windows XP Home. What can I do to fix this problem? the error means that the interpreter cannot find the _tk3draw.pyd file. if you use the standard install location, it should be installed under C:\Python23\lib\site-packages you could try this: import FixTk import _tk3draw _tk3draw.__file__ 'C:\\Python23\\lib\\site-packages\\_tk3draw.pyd' if this also gives you an error, search for _tk3draw.pyd on the disk. /F -- http://mail.python.org/mailman/listinfo/python-list
a short-cut command for globals().clear() ??
hi all, forgive me , but the RTFM and Google search approaches are not yielding an answer on this question. I need to know if there's a top level python interpreter command that clears all user variables (not built-ins) from the global namespace. In other words a statement, or some_command_or_function(), that does this: x=3 y=4 z=[] dir() ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] some_command_or_function() dir() ['__builtins__', '__doc__', '__name__'] thanks, 1 desperate snake oil programmer -- http://mail.python.org/mailman/listinfo/python-list
Re: A bit weird dictionary behavior
On Sep 22, 3:43 pm, Bruno Desthuilliers [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] a écrit : Pekka Laukkanen: but it still doesn't feel exactly right. Would it be worth submitting a bug? It feels wrong because it is. In a tidier language (Pascal, Java, etc) a boolean and an integer must be different types. Some would argue (and some did by the time Python grew a 'bool' type) that what is wrong is to have a bool type in a language that already have a wider definition of the truth value of an expression... And some would argue that it was wrong to have such a wide definition for the truth value of an expression in the first place... Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Here's something interesting: sympy crashes in Python 2.6 (Windows)
Fredrik Lundh wrote: Robert Kern wrote: (if someone wants to submit this to bugs.python.org, be my guest) http://bugs.python.org/issue3936 -- http://mail.python.org/mailman/listinfo/python-list
Re: a short-cut command for globals().clear() ??
On Sep 22, 2:31 pm, [EMAIL PROTECTED] wrote: hi all, forgive me , but the RTFM and Google search approaches are not yielding an answer on this question. I need to know if there's a top level python interpreter command that clears all user variables (not built-ins) from the global namespace. In other words a statement, or some_command_or_function(), that does this: x=3 y=4 z=[] dir() ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] some_command_or_function() dir() ['__builtins__', '__doc__', '__name__'] thanks, 1 desperate snake oil programmer I don't think you will find anything. The interpreter is essentially the same whether you are in interactive mode or not. That is, there is very little use for a method that clears globals in general, so why would we add it just so that it could be used by the interpreter. There is almost* nothing available to the interactive interpreter which isn't part of the core language. * The only difference I can think of is the _ variable, which is added to __builtins__ and contains the last value returned in interactive mode. If you have ever tried to run code that uses the locale module from the interpreter you will see why having any differences between the interactive and non-interactive interpreter can be a pain. Matt -- http://mail.python.org/mailman/listinfo/python-list
python timers and COM/directshow
Hey all, So I've written a simple video player using directshow/COM in VC++, and I'm in the process of translating it to python. For example, when the avi starts playing, I have a call media_control.Run() , etc. I'm wondering how I should go about updating my gtk.Hscale widget as a trackbar for the avi player. In C++, I have the following callbacks that update the scrollbar and video position with a timer. void CvideoDlg::OnNMReleasedcaptureSlider1(NMHDR *pNMHDR, LRESULT *pResult) { //Slider event handler LONGLONG lPos = 0; LONGLONG lDuration = 0; KillTimer(101); g_pSeek-GetDuration(lDuration); g_pSeek-GetCurrentPosition(lPos); Videopos= m_slider.GetPos(); //Sets new video position to that of the slider, which user inputs lPos = ((long)Videopos * (lDuration/num_of_frames)); g_pSeek-SetPositions(lPos, AM_SEEKING_AbsolutePositioning,NULL, AM_SEEKING_NoPositioning); *pResult = 0; } void CvideoDlg::OnTimer(UINT nIDEvent) { //Timer event handler. LONGLONG lPos = 0; LONGLONG lDuration = 0; g_pSeek-GetDuration(lDuration); g_pSeek-GetCurrentPosition(lPos); Videopos = (int)(lPos * num_of_frames/ lDuration); m_slider.SetPos(Videopos); if (Videopos==(int)(last_frame)) //If we get to the end of the selection, the video pauses pause(); else{ UpdateData(); //Updates the slider controller and position CDialog::OnTimer(nIDEvent);} } I'm wondering how I would implement similar callbacks in Python for a gtk.Hscale, and some sort of time [I'm not familiar with Pythons timers/threading at all]. -- http://mail.python.org/mailman/listinfo/python-list
Re: Not fully OO ?
Kay Schluehr wrote: On 20 Sep., 23:07, Aaron \Castironpi\ Brady [EMAIL PROTECTED] wrote: On Sep 20, 3:22 pm, Kay Schluehr [EMAIL PROTECTED] wrote: On 20 Sep., 18:33, Bruno Desthuilliers [EMAIL PROTECTED] wrote: The following definitions are AFAIK the only commonly accepted definitions about OO: 1/ an object is defined by identity, state and behaviour 2/ objects interacts by sending messages each other 3/ an OO program is made of interacting objects I let you find out whether Python meets these 3 definitions - and if Java does (hint : in Python, everything you can bind to a name is an object - this is not true in Java or C++). This is correct but it detracts from a more general problem of language paradigms. Assume you type 2+2 4 Now you are free to interpret this as a simple, primitive arithmetic operation but you can also claim that 2 sends an __add__ message to 2. Hereby the state of the 2 objects are not altered but a new 4 object is created. OO babble is more impressive isn't it? Actually it is simply wrong in the mentioned case and here is the proof: def foo(): return 2+2 import dis dis.dis(foo) 2 0 LOAD_CONST 2 (4) 3 RETURN_VALUE OO is a heuristic method used to understand the semantics of a programming language. It can also inspire language design but as you've rightly said: jugde yourself and see how far you get with it. Applying OO on interpreter level is by no means a sign of a high quality implementation whereas structuring programs in the large will likely benefit from class based organization and encapsulation. Of course one can also reverse the value hierarchy and find perverse joy in having a pure OO language but apply monkey patching everywhere. I suppose you know which language I'm talking about... It sounds like you think that you -can- write OO programs in Python, but you don't have to. I agree. The whole point of OO is providing high level ( system level ) not low level ( interpreter level ) semantics. Partitioning a system into isolated and communicating objects is a strong and important metaphor. Recently there were some comments on the web that mentioned Erlang to be pretty much OO in this respect although Erlang is functional and has no base level notion of an object. It's even well known that Joe Armstrong holds low opinions about the entire object business. Notice that I believe that the popular meme that OO is bolted on Python has little if nothing to do with OO itself but with API consistency. When people have to type len(x) instead of x.len() this breaks their expectations on how the language has to behave. x.__len__() -- http://mail.python.org/mailman/listinfo/python-list
Re: a short-cut command for globals().clear() ??
On Sep 22, 5:52 pm, Matimus [EMAIL PROTECTED] wrote: On Sep 22, 2:31 pm, [EMAIL PROTECTED] wrote: hi all, forgive me , but the RTFM and Google search approaches are not yielding an answer on this question. I need to know if there's a top level python interpreter command that clears all user variables (not built-ins) from the global namespace. In other words a statement, or some_command_or_function(), that does this: x=3 y=4 z=[] dir() ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] some_command_or_function() dir() ['__builtins__', '__doc__', '__name__'] thanks, 1 desperate snake oil programmer I don't think you will find anything. The interpreter is essentially the same whether you are in interactive mode or not. That is, there is very little use for a method that clears globals in general, so why would we add it just so that it could be used by the interpreter. There is almost* nothing available to the interactive interpreter which isn't part of the core language. * The only difference I can think of is the _ variable, which is added to __builtins__ and contains the last value returned in interactive mode. If you have ever tried to run code that uses the locale module from the interpreter you will see why having any differences between the interactive and non-interactive interpreter can be a pain. Matt ok. thanks! guess i'll be off to define my own function ... -- http://mail.python.org/mailman/listinfo/python-list
Re: A bit weird dictionary behavior
On 22.09.2008, Carl Banks [EMAIL PROTECTED] wroted: but it still doesn't feel exactly right. Would it be worth submitting a bug? It feels wrong because it is. In a tidier language (Pascal, Java, etc) a boolean and an integer must be different types. Some would argue (and some did by the time Python grew a 'bool' type) that what is wrong is to have a bool type in a language that already have a wider definition of the truth value of an expression... And some would argue that it was wrong to have such a wide definition for the truth value of an expression in the first place... Just out of idle curiosity, what could be the alternatives? Not to evaluate e.g. strings to true? Aren't such conventions as whatever is not empty, is 'true' popular in dynamic langauges? GS -- Grzegorz Staniak gstaniak _at_ wp [dot] pl Nocturnal Infiltration and Accurate Killing -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
On Mon, 22 Sep 2008 19:41:46 +1000, James Mills wrote: On 22 Sep 2008 09:07:43 GMT, Steven D'Aprano But that's precisely what I want to avoid: I don't want the objects to share *any* state, not even their class. I'm not trying for a Borg or Singleton: the user can call the factory as many times as they want, but the objects returned shouldn't share any state. I don't know if what I want has a name. Judging from people's reactions, I'd say probably not. Snce when are users ever involved in programming problems or programming languages ? What an astounding question. Consider a class. There are the programmers who write the class, and there are the programmers (possibly the same people, but not necessarily) who use the class. The second set of people, the programmers who use the class, are *users* of the class. What else would they be? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: a short-cut command for globals().clear() ??
[EMAIL PROTECTED] wrote: forgive me , but the RTFM and Google search approaches are not yielding an answer on this question. I need to know if there's a top level python interpreter command that clears all user variables (not built-ins) from the global namespace. In other words a statement, or some_command_or_function(), that does this: x=3 y=4 z=[] dir() ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] some_command_or_function() dir() ['__builtins__', '__doc__', '__name__'] First, a WARNING to other readers deceived by the subject line. Globals().clear() clears everything and leaves nothing, so Capn... is looking for something that works that is a shortcut for deleting bindings one-by-one. To your question. The short answer is no. In batch mode, only create what you need and delete (unbind) large objects that are not automatically deleted (unbound) when you are done with them. Remember that only reference-counted implementations will guarantee immediate destruction and space-freeing when the last reference goes away. Check the gc module (and some posts in the archives) for more specialized control. In interactive mode, restart the interpreter if you really need a clean slate and have too many bindings that you must delete to do something quick like 'del x,y,z' as in your example above. In IDLE, cntl-F6 restarts the shell with a clean slate. I presume IPython has something similar. tjr -- http://mail.python.org/mailman/listinfo/python-list
Using vObject
I'm brand new to USENET so please bear with me. I'm writing a specialized to-do list app. I'm using Django but this is not a question about Django. It has to have recurring tasks set by the managers for the employees to then check off. I've got pretty much everything in the app worked out, except for one thing: the repeating tasks. I want to have it so that the manager puts in a repeating task with a description and a repeat rule. This rule then generates simpler one-time tasks. These one-time tasks have a description, a time (a datetime.datetime object) and completed boolean. I've looked around and think I have these options: 1. Manually put it all together with another Django model that implements the repeat rules. 2. Do the same thing but use dateutil.rrule to help. 3. Use the icalendar (http://codespeak.net/icalendar/) module to access ICS files. 4. vObject (http://vobject.skyhouseconsulting.com/) to do the same. I think I want to use vObject because it uses dateutil and the management can easily manage tasks from a desktop app. Only thing is that I find vObject's documentation very cryptic and was wondering if anybody here could shed some light on how to use vObject. A simple getting-started tutorial or something similar would be nice. Thanks all! -Josh -- http://mail.python.org/mailman/listinfo/python-list
Python based barcode readers
Does anyone know of any python based barcode readers? I'm looking for something (commercial or open source) that will use some OCR algorithm to read barcodes from an image or ps/pdf file, and ideally will be something along the lines of a callable python script. I have some pretty simple needs, i'm only trying to read code 93 barcodes, so i don't need it to be able to identify multiple symbologies or anything. Any suggestions would be greatly appreciated. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: What do you call a class not intended to be instantiated
On Sep 22, 5:32 pm, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On Mon, 22 Sep 2008 19:41:46 +1000, James Mills wrote: On 22 Sep 2008 09:07:43 GMT, Steven D'Aprano But that's precisely what I want to avoid: I don't want the objects to share *any* state, not even their class. I'm not trying for a Borg or Singleton: the user can call the factory as many times as they want, but the objects returned shouldn't share any state. I don't know if what I want has a name. Judging from people's reactions, I'd say probably not. Snce when are users ever involved in programming problems or programming languages ? What an astounding question. Consider a class. There are the programmers who write the class, and there are the programmers (possibly the same people, but not necessarily) who use the class. The second set of people, the programmers who use the class, are *users* of the class. What else would they be? -- Steven Usegrammers? -- http://mail.python.org/mailman/listinfo/python-list
looper
I was asked by my employer to publish this a bit ago, so here it is: http://stromberg.dnsalias.org/~dstromberg/looper/ It's a multithreaded script for running n POSIX shell commands m at a time with good error checking. It allows for things like stashing in ssh $hostname or rsync $hostname in a convenient way - with pretty complete shell quoting so that your command comes out on the other side of the ssh command the same way it went into looper. It also allow I hope someone finds it useful. I know I have. Followups have been directed to comp.unix.shell. -- http://mail.python.org/mailman/listinfo/python-list
Re: a short-cut command for globals().clear() ??
On Sep 22, 5:44 pm, Terry Reedy [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: forgive me , but the RTFM and Google search approaches are not yielding an answer on this question. I need to know if there's a top level python interpreter command that clears all user variables (not built-ins) from the global namespace. In other words a statement, or some_command_or_function(), that does this: x=3 y=4 z=[] dir() ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] some_command_or_function() dir() ['__builtins__', '__doc__', '__name__'] First, a WARNING to other readers deceived by the subject line. Globals().clear() clears everything and leaves nothing, so Capn... is looking for something that works that is a shortcut for deleting bindings one-by-one. To your question. The short answer is no. In batch mode, only create what you need and delete (unbind) large objects that are not automatically deleted (unbound) when you are done with them. Remember that only reference-counted implementations will guarantee immediate destruction and space-freeing when the last reference goes away. Check the gc module (and some posts in the archives) for more specialized control. In interactive mode, restart the interpreter if you really need a clean slate and have too many bindings that you must delete to do something quick like 'del x,y,z' as in your example above. In IDLE, cntl-F6 restarts the shell with a clean slate. I presume IPython has something similar. tjr I guess you have a few hackish options. 1) Define a wrapper that calls its argument immediately, and use it as you would use anonymous blocks. @call_imm def block( ): code code code @call_imm def block( ): code code code You have no globals when you are done. 2) If you need them to be global, use some introspection, and delete the variables upon exiting the scope. 3) Declare all your variables in a namespace, and just delete the namespace. a= type('blank',(),{})() a.varA= 0 a.varB= 'abc' del a -- http://mail.python.org/mailman/listinfo/python-list
Re: Python based barcode readers
I also forgot to mention that it need not be nearly as robust as something like Jailhelper 2.0, I will not really need to compensate for noise and irregular conditions. All of my barcodes will be scanned in a predictable, and consistent environment (i.e. a scanner), so all i need is some stupid little script that will read the an image in and decode it. -- http://mail.python.org/mailman/listinfo/python-list
Re: looper
Great thanks On 9/22/08, Dan Stromberg [EMAIL PROTECTED] wrote: I was asked by my employer to publish this a bit ago, so here it is: http://stromberg.dnsalias.org/~dstromberg/looper/ It's a multithreaded script for running n POSIX shell commands m at a time with good error checking. It allows for things like stashing in ssh $hostname or rsync $hostname in a convenient way - with pretty complete shell quoting so that your command comes out on the other side of the ssh command the same way it went into looper. It also allow I hope someone finds it useful. I know I have. Followups have been directed to comp.unix.shell. -- http://mail.python.org/mailman/listinfo/python-list -- http://gpirate.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python based barcode readers
This is something I have looked for too but I have not come across a decent barcode reader? On 9/22/08, Robocop [EMAIL PROTECTED] wrote: Does anyone know of any python based barcode readers? I'm looking for something (commercial or open source) that will use some OCR algorithm to read barcodes from an image or ps/pdf file, and ideally will be something along the lines of a callable python script. I have some pretty simple needs, i'm only trying to read code 93 barcodes, so i don't need it to be able to identify multiple symbologies or anything. Any suggestions would be greatly appreciated. Thanks! -- http://mail.python.org/mailman/listinfo/python-list -- http://gpirate.com -- http://mail.python.org/mailman/listinfo/python-list
Re: dict generator question
On Mon, 22 Sep 2008 04:21:12 -0700, bearophileHUGS wrote: Steven D'Aprano: Extending len() to support iterables sounds like a good idea, except that it's not. Python language lately has shifted toward more and more usage of lazy iterables (see range lazy by default, etc). So they are now quite common. So extending len() to make it act like leniter() too is a way to adapt a basic Python construct to the changes of the other parts of the language. I'm sorry, I don't recognise leniter(). Did I miss something? In languages like Haskell you can count how many items a lazy sequence has. But those sequences are generally immutable, so they can be accessed many times, so len(iterable) doesn't exhaust them like in Python. So in Python it's less useful. In Python, xrange() is a lazy sequence that isn't exhausted, but that's a special case: it actually has a __len__ method, and presumably the length is calculated from the xrange arguments, not by generating all the items and counting them. How would you count the number of items in a generic lazy sequence without actually generating the items first? This is a common situation where I can only care of the len of the g group: [leniter(g) for h,g in groupby(iterable)] There are other situations where I may be interested only in how many items there are: leniter(ifilter(predicate, iterable)) leniter(el for el in iterable if predicate(el)) For my usage I have written a version of the itertools module in D (a lot of work, but the result is quite useful and flexible, even if I miss the generator/iterator syntax a lot), and later I have written a len() able to count the length of lazy iterables too (if the given variable has a length attribute/property then it returns that value), I'm not saying that no iterables can accurately predict how many items they will produce. If they can, then len() should support iterables with a __len__ attribute. But in general there's no way of predicting how many items the iterable will produce without iterating over it, and len() shouldn't do that. and I have found that it's useful often enough (almost as the string.xsplit()). But in Python there is less need for a len() that counts lazy iterables too because you can use the following syntax that isn't bad (and isn't available in D): [sum(1 for x in g) for h,g in groupby(iterable)] sum(1 for x in ifilter(predicate, iterable)) sum(1 for el in iterable if predicate(el)) I think the idiom sum(1 for item in iterable) is, in general, a mistake. For starters, it doesn't work for arbitrary iterables, only sequences (lazy or otherwise) and your choice of variable name may fool people into thinking they can pass a use-once iterator to your code and have it work. Secondly, it's not clear what sum(1 for item in iterable) does without reading over it carefully. Since you're generating the entire length anyway, len(list(iterable)) is more readable and almost as efficient for most practical cases. As things stand now, list(iterable) is a dangerous operation, as it may consume arbitrarily huge resources. But len() isn't[1], because len() doesn't operate on arbitrary iterables. This is a good thing. So you and Python designers may choose to not extend the semantics of len() for various good reasons, but you will have a hard time convincing me it's a useless capability :-) I didn't say that knowing the length of iterators up front was useless. Sometimes it may be useful, but it is rarely (never?) essential. [1] len(x) may call x.__len__() which might do anything. But the expected semantics of __len__ is that it is expected to return an int, and do it quickly with minimal effort. Methods that do something else are an abuse of __len__ and should be treated as a bug. -- Steven -- http://mail.python.org/mailman/listinfo/python-list