ANN: Simulation package SimPy -- release 2.0 beta
We are happy to announce the release of SimPy 2.0 beta, a major release. Download from: https://sourceforge.net/project/showfiles.php?group_id=62366release_id=6374 17 Feedback (errors found, proposals for changes, etc.) is requested, using the SimPy Users Mailing List (mailto:simpy-users atlists.sourceforge.net). The new version has been largely developed by What is SimPy? -- SimPy is a process-based discrete-event simulation language based on standard Python and released under the GNU LGPL. It provides the modeller with components of a simulation model. These include processes, for active components like customers, messages, and vehicles, and resources, for passive components that form limited capacity congestion points like servers, checkout counters, and tunnels. It also provides monitor variables to aid in gathering statistics. What is new in SimPy 2.0? - In addition to its existing API, SimPy now also has an object oriented API. The additional API - allows running SimPy in parallel on multiple processors or multi-core CPUs, using Parallel Python. - supports better structuring of SimPy programs, - allows easy extension of model classes by sub-classing, thus providing a capability for developing application libraries, - allows subclassing of class *Simulation* and thus provides users with the capability of creating new simulation modes/libraries like *SimulationTrace*, and - reduces the total amount of SimPy code, thereby making it easier to maintain. Note that the OO API is in addition to the old API. SimPy 2.0 is fully backward compatible. SimPy's documentation has been restructured and processed by the Sphinx documentation generation tool. This has generated one coherent, well structured document which can be easily browsed. A search capability is included. Acknowledgments --- SimPy 2.0 has been primarily developed by Stefan Scherfke and Ontje Lünsdorf, starting from SimPy 1.9. Their work has resulted in a most elegant combination of an object oriented API with the existing API, maintaining full backward compatibility. It has been quite easy to integrate their product into the existing SimPy code and documentation environment. Thanks, guys, for this great job! SimPy 2.0 is dedicated to you! The many contributions of the SimPy user and developer communities are of course also gratefully acknowledged. Download, test, enjoy and give us feedback! Happy SimPying! Klaus MullerTony Vignaux attachment: winmail.dat-- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
IMDbPY 3.8
IMDbPY 3.8 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. With this release, it's possible to access the data in the sql database using both the SQLObject and SQLAlchemy ORMs. Many bugs were also fixed. 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. -- 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.17 Release
Dear Python users, The Elisa team is happy to announce the release of Elisa Media Center 0.5.17, code-named Dazed And Confused. Elisa is a cross-platform and open-source Media Center written in Python. It uses GStreamer [1] for media playback and pigment [2] to create an appealing and intuitive user interface. This release brings its usual lot of bug fixes and important performance improvements. A complete list of the new features and bugs fixed by this release is available at: https://bugs.launchpad.net/elisa/+milestone/0.5.17 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 [1] http://www.gstreamer.net/ [2] https://code.fluendo.com/pigment/trac Elisa 0.5.17 Dazed And Confused = This is Elisa 0.5.17, seventeenth release of the 0.5 branch. Bugs fixed since 0.5.16: - 289901: audio icon missing - 291183: Regression: the player cannot display popups - 293186: Multiple widgets give wrong visual focus information - 278953: .po files are not compilable as shipped in the tarballs - 290012: PPA package for 0.5.16 error: python 2.4 invalid syntax - 291479: [linux] Coherence plugin fails to load because of a dependency on httpd - 287506: [win32] installer shouldn't update the c libraries if it's not needed - 291553: Media scanner stop() dbus method does not return when not running Download You can find source releases of Elisa on the download page: http://elisa.fluendo.com/download Elisa Homepage More details can be found on the project's website: http://elisa.fluendo.com Support and Bugs We use Launchpad for bug reports and feature requests: https://bugs.launchpad.net/elisa/+filebug Developers All code is in a Bazaar branch and can be checked out from there. It is hosted on Launchpad: https://code.launchpad.net/elisa Contributors to this release: - Alessandro Decina - Benjamin Kampmann - David McLeod - Florian Boucault - Guido Amoruso - Guillaume Emont - Jesús Corrius - Lionel Martin - Olivier Tilloy - Philippe Normand -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Bulova Marine Star Mens Watch 96B98 Collection
Bulova Marine Star Mens Watch 96B98 Collection Watches Collection Site : http://www.watches-collection.com/ Bulova Marine Star Mens Watch 96B98 View Full : http://bulova.watches-collection.com/Bulova-Marine-Star-Mens-Watch-96B98.html Bulova Marine Star Mens Watch 96B98 AdditionalInfo : Brand : Bulova ( http://bulova.watches-collection.com/ ) Gender : Mens Code : Bulova-96B98 Also Called : $ Movement :Quartz Bezel : Fixed Case Material :Stainless Steel Case Diameter : Dial Color : White Crystal : Mineral Clasp : Stainless Steel Water Resistant : 100m/330ft Stainless Steel Case and bracelet. White patterned dial. Chronograph Functions. Tachometer. Alarm. Luminous hands and markers. Domed crystal. Stainless steel case and bracelet. Screw back. Fold-over buckle with lock. Water resistant to 100 meters/330 feet. BRDimensions: 41mm The Bulova Watches Collection Series : Bulova Diamond Watches Collection : http://bulova.watches-collection.com/bulova-diamond-watches.html Bulova Bracelet Watches Collection : http://bulova.watches-collection.com/bulova-bracelet-watches.html Bulova Crystal Watches Collection : http://bulova.watches-collection.com/bulova-crystal-watches.html Bulova Bangle Watches Collection : http://bulova.watches-collection.com/bulova-bangle-watches.html Bulova 14kt Gold Watches Collection : http://bulova.watches-collection.com/bulova-14kt-gold-watches.html Bulova Marine Star Watches Collection : http://bulova.watches-collection.com/bulova-marine-star-watches.html Bulova Brilliants Watches Collection : http://bulova.watches-collection.com/bulova-brilliants-watches.html Bulova Maestro Watches Collection : http://bulova.watches-collection.com/bulova-maestro-watches.html Bulova Millennia Watches Collection : http://bulova.watches-collection.com/bulova-millennia-watches.html Bulova Precious Watches Collection : http://bulova.watches-collection.com/bulova-precious-watches.html Bulova Overture Watches Collection : http://bulova.watches-collection.com/bulova-overture-watches.html Bulova Strap Watches Collection : http://bulova.watches-collection.com/bulova-strap-watches.html Hard to Find Bulova Watches Collection : http://bulova.watches-collection.com/hard-to-find-bulova-watches.html Bulova Clocks Collection : http://bulova.watches-collection.com/bulova-clocks.html -- http://mail.python.org/mailman/listinfo/python-list
Re: push-style templating - an xml-like way to process xhtml
On 2 Nov, 14:06, Tino Wildenhain [EMAIL PROTECTED] wrote: An opposite approach to this form of dynamic HTML production is called push-style templating, as coined by Terence Parr: Hm. a href=$attr.url$$attr.title$/a $if(attr.active)$ $attr.submenu:menuItem()$ $endif$ This looks ugly to me. It also looks like an embedded mini-language to me. At any rate, I think making a 'push/pull' distinction misses the point. There are basically three approaches a templating system can use: 1. embed your control logic in your presentation markup, 2. embed your presentation markup in your control logic, or 3. keep the two separate and transform the presentation markup into some sort of DOM that can then be manipulated by the control code. What's significant here is the division of labour within the overall program. With the first two approaches, the templating engine handles both presentation and control (i.e. pretty much the entire View layer). The third approach only provides the presentation part, and does and says nothing about how the control part is implemented. So you can't really make a direct comparison of, say, Cheetah against PyMeld, as they don't cover the same amount of ground. Instead, you ought to consider how the entire View layer is put together in each case: - A Cheetah-based View is implemented as an HTML file with all of the required control code embedded in it. - A PyMeld-based View is implemented as an HTML file with id attributes that indicate which HTML elements should be converted into object model nodes, *plus* a Python module containing the control code that manipulates those nodes when rendering a finished document. Once you do compare like with like, the 'push/pull' distinction becomes somewhat irrelevant, as the control code for a PyMeld-based View could be pushing or it could be pulling. It's up to each program's developer to decide which way they want to do it - and in a proper MVC design it should always be pulling. ... A more useful distinction to make is between templating systems that combine appearance and control, and those that keep them separate, as this has significant implications when considering which type of templating system to choose, e.g.: - how complex the interface is, e.g. Cheetah's interface is larger and more complex than PyMeld's (even though they do the same thing), which means a longer learning curve - how clean the division of responsibility is, e.g. PyMeld separates HTML markup from Python code, which provides an obvious advantage if you've got a web designer handling one task and a Python programmer handling the other, or a likely disadvantage if both tasks are being handled by a relatively non-technical web designer - how abstract the program's View implementation is, e.g. a PyMeld- based View is more abstract than a Cheetah one, as markup and code are physically separate and are only combined in memory, which means the logic developer has to work harder in mentally modelling their View layer's structure and behaviour. HTH has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: how to call this dll in python
Shark schrieb: I have a windows dll1.dll with a export function: int f1(char filename,char **buf,int *bufLen) { int len; //got the length of file anyway,such as 100 len = 100;//len = getLen(filename); *buf = (char*)calloc(100); *bufLen = len; return 0; } then how can I call the f1 function with python. thanks for your response. If the above is *really* what you want to access from python, you shouldn't bother write it new in python itself. You could either use bufLen = len(open(filename).read()) or make a os.stat-call. If it serves only as a rather ugly illustrative example, then you should investigate the ctypes-module of python, which is made for accessing arbitrary dlls from python. Diez -- http://mail.python.org/mailman/listinfo/python-list
wrapping a method function call?
I am instantiating a class A (which I am importing from somebody else, so I can't modify it) into my class X. Is there a way I can intercept or wrape calls to methods in A? I.e., in the code below can I call x.a.p1() and get the output X.pre A.p1 X.post Many TIA! Mark class A: # in my real application, this is an imported class # that I cannot modify def p1(self): print 'A.p1' class X: def __init__(self): self.a=A() def pre(self): print 'X.pre' def post(self): print 'X.post' x=X() x.a.p1() -- Mark Harrison Pixar Animation Studios -- http://mail.python.org/mailman/listinfo/python-list
Re: wrapping a method function call?
[EMAIL PROTECTED] schrieb: I am instantiating a class A (which I am importing from somebody else, so I can't modify it) into my class X. Is there a way I can intercept or wrape calls to methods in A? I.e., in the code below can I call x.a.p1() and get the output X.pre A.p1 X.post Many TIA! Mark class A: # in my real application, this is an imported class # that I cannot modify def p1(self): print 'A.p1' class X: def __init__(self): self.a=A() def pre(self): print 'X.pre' def post(self): print 'X.post' x=X() x.a.p1() There are a few ways to accompish this. First of all, Python allows monkey-patching. That means you *can* modify it: import sys class X(object): def foo(self): print foo X.foo = lambda self: sys.stdout.write(more than foo) x = X() x.foo() You can of course wrap the old foo instead of replacing it, with something like def foowrapper(old_foo): def _w(self, *args, **kwargs): print wrapped return old_foo(self, *args, **kwargs) return _w X.foo = foowrapper(X.foo) Alternatively, you can wrap the whole of X into a proxy, based on __getattr__ that will allow you do intercept all delegate calls. class Wrapper(object): def __init__(self, delegate): self._delegate = delegate def __getattr__(self, name): print accessing, name return getattr(self._delegate, name) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does numpy.array(a[0],b[0]) have this meaning?
On Sun, 02 Nov 2008 23:26:24 -0800, Rick Giuly wrote: Case 1 This generates an error, which makes sense because the argument should be a list of numbers: numpy.array(10,10) Case 2 This does not generate an error and the result is an array with a single element: a = numpy.array([10]) b = numpy.array([10]) numpy.array(a[0],b[0]) The only different I see here between the numpy.array call in the cases is that a[0] is a numpy int32 10 is an int Why would this minor difference in integer types cause a totally different result for the two cases - or is something else causing the difference in results? From the `numpy.array` docstring: Inputs: object - an array, any object exposing the array interface, any object whose __array__ method returns an array, or any (nested) sequence. And `numpy.int32` instances have an `__array__()` method: In [225]: ten = numpy.int32(10) In [226]: ten.__array__() Out[226]: array(10) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Simplifying anonymous inner classes?
Tim Chase [EMAIL PROTECTED] wrote: def __init__(self, ...): self.parser = optparse.OptionParser(...) def __call__(self, argv): # argv is a list like sys.argv options, args = self.parser.parse_args(argv) # do something with options/args So that background provided, the original question was more about how to create anonymous sub-classes with overridden methods so my Backend objects' code namespaces weren't littered with objects that were only defined to be instantiated once in exactly the location they were defined. I think Martin v. Löwis expanded sufficiently on the idea of using decorators, so I'll just point out one problem you may run into: the pseudo-code you posted will create callable attributes on the class, but unless you also implement the descriptor protocol they won't act like methods. i.e. you won't get any reference to the instance on which you called load/run/frob or whatever. Of course the decorator solution has the opposite problem: you get a reference to your Backend instance but not to the decorated function itself. That probably shouldn't matter: what you wrote above looks to me like you just do: class DatabaseBackend: @Action(...) def load(self, options, args): ... and the parse_args call is something done in the decorator rather than repeated in each and every method that follows this pattern. Or even better make the options parse to specific keyword arguments so you can test an option directly inside the method rather than having to look it up in a dictionary. class DatabaseBackend: @Action(load a thang into memory). add_option(-f, --file, help=load from file, default=None). add_option(--frobnify, help=frobnify the thang, default=False, action=store_true) def load(self, file, frobnify, args): ... -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to make money with Python!
Grant Edwards wrote: On 2008-10-31, Duncan Booth [EMAIL PROTECTED] wrote: If that subject line didn't trip everyone's killfiles, see http://pythonide.blogspot.com/2008/10/how-to-make-money-with-free-software.html for a fantastic story involving Python. Doh! The very clever pun went right past me several times before I finally caught on (with some help from a poster on /.) beautiful work of art -- http://mail.python.org/mailman/listinfo/python-list
Re: wrapping a method function call?
On Mon, 03 Nov 2008 08:17:02 +, mh wrote: I am instantiating a class A (which I am importing from somebody else, so I can't modify it) into my class X. Is there a way I can intercept or wrape calls to methods in A? I.e., in the code below can I call x.a.p1() and get the output X.pre A.p1 X.post Possibly you can do it with some metaclass magic. You might like to search for Eiffel-style pre- and post-conditions using a metaclass, although I warn you, many people consider metaclasses deep voodoo. Here's one way using decorators: # Define two decorator factories. def precall(pre): def decorator(f): def newf(*args, **kwargs): pre() return f(*args, **kwargs) return newf return decorator def postcall(post): def decorator(f): def newf(*args, **kwargs): x = f(*args, **kwargs) post() return x return newf return decorator Now you can monkey patch class A if you want. It's probably not a great idea to do this in production code, as it will effect class A everywhere. def pre(): print 'X.pre' def post(): print 'X.post' from module import A A.p1 = precall(pre)(postcall(post)(A.p1)) Here's another way: class A: # in my real application, this is an imported class # that I cannot modify def p1(self): print 'A.p1' class WrapA: def __init__(self, ainstance, xinstance): self._a = ainstance self._x = xinstance def p1(self): # Delegate calls as needed. self._x.pre() self._a.p1() self._x.post() class X: def __init__(self): self.a = WrapA(A(), self) def pre(self): print 'X.pre' def post(self): print 'X.post' There are probably many other ways to accomplish the same thing, depending on your exact requirements. You should be able to combine the decorator technique and the delegation technique to leave class A untouched outside of class X, but wrapped inside of X. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
length of a tuple or a list containing only one element
Hi everybody, I have a question about the difference of behavior of len when applied on tuples or on lists. I mean: $ len( ( 'foo', 'bar' ) ) 2 $ len( ( 'foo' ) ) 3 $ len( [ 'foo', 'bar' ] ) 2 $ len( [ 'foo' ] ) 1 Why this behavior for the length computation of a tuple? For my application, I prefer the behavior of length for a list. If I want to store some values in a tuple because they should not be modified, the case where the tuple contains only one element bothers me. Thanks Julien -- python -c print ''.join([chr(154 - ord(c)) for c in '*9(9(18%.91+,\'Z (55l4(']) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong. (first law of AC Clarke) -- http://mail.python.org/mailman/listinfo/python-list
Simple textual calendar
Hello everyone, please, I need your help. I'm a beginner in python and this is probably elemental to you, but represents quote a goggle for me. I'm trying to write out a calendar for a year, in this form (imaginary month below): 2008, February Mon Tue Wed Thu Fri Sat Sun 01 02 03 04 05 06 07 08 09 10 11 ... et cetera 2008, March ... ... ... (same as above, only for march) (don't know how this will come up in your newsreaders, but you get the general idea). I discovered datetime module, but I'm not sure how to do the actual calendar writeout (formatting). Please, if you could throw a tip or two, I'd be very grateful. Ostra p.s. This is not homework or anything in that direction. It's just I'm not a programmer, and so this and everything is still new to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple textual calendar
ostra pikula [EMAIL PROTECTED] writes: Hello everyone, please, I need your help. I'm a beginner in python and this is probably elemental to you, but represents quote a goggle for me. I'm trying to write out a calendar for a year, in this form (imaginary month below): 2008, February Mon Tue Wed Thu Fri Sat Sun 01 02 03 04 05 06 07 08 09 10 11 ... et cetera 2008, March ... ... ... (same as above, only for march) (don't know how this will come up in your newsreaders, but you get the general idea). I discovered datetime module, but I'm not sure how to do the actual calendar writeout (formatting). Please, if you could throw a tip or two, I'd be very grateful. Ostra p.s. This is not homework or anything in that direction. It's just I'm not a programmer, and so this and everything is still new to me. Have your looked at the calendar module? http://www.python.org/doc/2.5.2/lib/module-calendar.html HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
How to protect website from access without authentication?
Dear All, We are developing a website and would like to password protect the whole site. If any user visit our site using ip address or using the http link, he/she will be asked for login password and then granted the access to whole site based on the correct password. Help will be appreciated. Thank Regards, Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Structures
Paulo J. Matos: Since Python focus on having one way to do it and structures are something like classes with only public methods, if I want structures that's what I should use. Is that right? Yes, it is. On the other hand in Python 2.6 there's something that helps you build one of such classes in a standard and handy way: see namedtuple in the standard collections module. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Efficient way to remove objects from a list
一首诗 wrote: Hi all, Today I wrote some code like this: for m in self.messages: if not m.finished: continue #process the message fini = [m for m in self.messages if m.finished] for m in fini: self.messages.remove(m) As you can, I want to find these finished messages in self.messages, process them, and then remove them from the list. Because a list can not be modified while iterating it, I have to use a list fini to accomplish the target. I found a smell of bad performance here. Is there any faster ways? I'm not getting what your code really wants to do - you are iterating over messages, and if its not finished, skip over it and process all which are finished. (If they are finished, why process them?) Wouln't it make more sense to call the process where you process the messages? And you could just pop() the list or use some of the queue implementations for better performance. e.g. def enqueue_messages(self,msg): self.messages.append(msg) def process_messages(self): if self.messages: msg=self.messages.pop(0) process(msg) if you want some post processing, its really like you are acting in different stages, so you could just have two lists for your messages: one for the messages in phase1, one for the messages passed phase1 and now in phase2 and work over them in the way shown above. Regards Tino -- http://mail.python.org/mailman/listinfo/python-list smime.p7s Description: S/MIME Cryptographic Signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Exact match with regular expression
On Sat, Nov 1, 2008 at 1:57 AM, Lawrence D'Oliveiro [EMAIL PROTECTED] wrote: In message [EMAIL PROTECTED], Rob Williscroft wrote: Read (and bookmark) this: http://www.python.org/doc/2.5.2/lib/re-syntax.html Funny how you never get a thank-you when you tell people to RTFM. My fault :\ I said thank you to Rob, but I just sent a private message. It's just that I did a reply and not reply to all. Anyway, I RTFM and solved my problem :) Thanks again, Bye -- http://mail.python.org/mailman/listinfo/python-list
Re: Efficient way to remove objects from a list
M.-A. Lemburg wrote: The typical way to do this is to iterate over the list in reverse order and then using the item index as basis for removing the item: for i, item in enumerate(reversed(mylist)): # process item del mylist[i] Sorry, the above should read: for i, item in reversed(enumerate(mylist)): # process item del mylist[i] It's harder to get right than it might first appear: reversed(enumerate([])) Traceback (most recent call last): File stdin, line 1, in module TypeError: argument to reversed() must be a sequence I think simplest approach is for index in reversed(range(len(mylist))): item = mylist[index] ... But I usually build a new list. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple textual calendar
On Mon, 03 Nov 2008 14:14:00 +0100, ostra pikula [EMAIL PROTECTED] wrote: Hello everyone, please, I need your help. I'm a beginner in python and this is probably elemental to you, but represents quote a goggle for me. I'm trying to write out a calendar for a year, in this form (imaginary month below): 2008, February Mon Tue Wed Thu Fri Sat Sun 01 02 03 04 05 06 07 08 09 10 11 ... et cetera 2008, March ... ... ... (same as above, only for march) My mistake here (well, whose else would it be ?!); it's supposed to go 2008, February 2008, March Months are supposed to go, one after the other in a row, not in a column. Ostra -- http://mail.python.org/mailman/listinfo/python-list
Re: length of a tuple or a list containing only one element
For making a literal tuple, parentheses are irrelevant; only the commas matter: I don't think I'd go so far as to say that the parentheses around tuples are *irrelevant*...maybe just relevant in select contexts def foo(*args): ... for i, arg in enumerate(args): ... print i, arg ... foo(1,2) 0 1 1 2 foo((1,2)) # these parens are pretty important :) 0 (1, 2) pedantically-grinning-ducktyping-and-running-ly yers, -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Efficient way to remove objects from a list
Chris Rebert wrote: On Mon, Nov 3, 2008 at 1:40 AM, 一首诗 [EMAIL PROTECTED] wrote: Hi all, Today I wrote some code like this: Build a new list as you go, then overwrite the old list with it. unfinished = [] for m in self.messages: if not m.finished: unfinished.append(m) continue #process the message Remove the following code fini = [m for m in self.messages if m.finished] for m in fini: self.messages.remove(m) self.messages[:] = unfinished Just self.messages = unfinished if also OK unless you have multiple references to the self.messages list. This way you aren't calling .remove() multiple times and only iterate through the list once. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple textual calendar
On Mon, 03 Nov 2008 13:25:44 +, Arnaud Delobelle [EMAIL PROTECTED] wrote: Have your looked at the calendar module? http://www.python.org/doc/2.5.2/lib/module-calendar.html HTH Hello Arnaud, thank you for replying. Yes, I saw the calendar module, but, as I said, this isn't homework or something like that. It is an example which I've setted myself to try to solve to see how it would go. Calendar just gives me the solution :-( Ostra -- http://mail.python.org/mailman/listinfo/python-list
Re: wrapping a method function call?
Steven D'Aprano [EMAIL PROTECTED] wrote: Now you can monkey patch class A if you want. It's probably not a great idea to do this in production code, as it will effect class A everywhere. This is perfect for me. The code in question is basically a protocol translator... it receives requests over the network, makes some calls, and returns the result translated back to the original protocol, so there's a single instance of each A,B, etc. A.p1 = precall(pre)(postcall(post)(A.p1)) Is there a way to do this for all callable methods of A? e.g. for x in callable_methods(A): x = precall(pre)(postcall(post)(x)) Thanks! Mark -- Mark Harrison Pixar Animation Studios -- http://mail.python.org/mailman/listinfo/python-list
Re: Efficient way to remove objects from a list
On 2008-11-03 12:12, M.-A. Lemburg wrote: 一首诗 wrote: Hi all, Today I wrote some code like this: for m in self.messages: if not m.finished: continue #process the message fini = [m for m in self.messages if m.finished] for m in fini: self.messages.remove(m) As you can, I want to find these finished messages in self.messages, process them, and then remove them from the list. Because a list can not be modified while iterating it, I have to use a list fini to accomplish the target. I found a smell of bad performance here. Is there any faster ways? The typical way to do this is to iterate over the list in reverse order and then using the item index as basis for removing the item: for i, item in enumerate(reversed(mylist)): # process item del mylist[i] Sorry, the above should read: for i, item in reversed(enumerate(mylist)): # process item del mylist[i] -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Nov 03 2008) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 -- http://mail.python.org/mailman/listinfo/python-list
Re: Efficient way to remove objects from a list
On Mon, Nov 3, 2008 at 1:40 AM, 一首诗 [EMAIL PROTECTED] wrote: Hi all, Today I wrote some code like this: Build a new list as you go, then overwrite the old list with it. unfinished = [] for m in self.messages: if not m.finished: unfinished.append(m) continue #process the message Remove the following code fini = [m for m in self.messages if m.finished] for m in fini: self.messages.remove(m) self.messages[:] = unfinished This way you aren't calling .remove() multiple times and only iterate through the list once. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com As you can, I want to find these finished messages in self.messages, process them, and then remove them from the list. Because a list can not be modified while iterating it, I have to use a list fini to accomplish the target. I found a smell of bad performance here. Is there any faster ways? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple textual calendar
ostra It is an example which I've setted myself to try to solve to see ostra how it would go. An even simpler solution is the cal command on Unix systems: % cal 2009 2009 JanFebMar S M Tu W Th F SS M Tu W Th F SS M Tu W Th F S 1 2 31 2 3 4 5 6 71 2 3 4 5 6 7 4 5 6 7 8 9 108 9 10 11 12 13 148 9 10 11 12 13 14 11 12 13 14 15 16 17 15 16 17 18 19 20 21 15 16 17 18 19 20 21 18 19 20 21 22 23 24 22 23 24 25 26 27 28 22 23 24 25 26 27 28 25 26 27 28 29 30 31 29 30 31 AprMayJun S M Tu W Th F SS M Tu W Th F SS M Tu W Th F S 1 2 3 4 1 2 1 2 3 4 5 6 5 6 7 8 9 10 113 4 5 6 7 8 97 8 9 10 11 12 13 12 13 14 15 16 17 18 10 11 12 13 14 15 16 14 15 16 17 18 19 20 19 20 21 22 23 24 25 17 18 19 20 21 22 23 21 22 23 24 25 26 27 26 27 28 29 30 24 25 26 27 28 29 30 28 29 30 31 JulAugSep S M Tu W Th F SS M Tu W Th F SS M Tu W Th F S 1 2 3 4 1 1 2 3 4 5 5 6 7 8 9 10 112 3 4 5 6 7 86 7 8 9 10 11 12 12 13 14 15 16 17 189 10 11 12 13 14 15 13 14 15 16 17 18 19 19 20 21 22 23 24 25 16 17 18 19 20 21 22 20 21 22 23 24 25 26 26 27 28 29 30 31 23 24 25 26 27 28 29 27 28 29 30 30 31 OctNovDec S M Tu W Th F SS M Tu W Th F SS M Tu W Th F S 1 2 31 2 3 4 5 6 7 1 2 3 4 5 4 5 6 7 8 9 108 9 10 11 12 13 146 7 8 9 10 11 12 11 12 13 14 15 16 17 15 16 17 18 19 20 21 13 14 15 16 17 18 19 18 19 20 21 22 23 24 22 23 24 25 26 27 28 20 21 22 23 24 25 26 25 26 27 28 29 30 31 29 30 27 28 29 30 31 :-) If you really want to write something yourself take a look at the datetime module. Here's a trivial (untested) example: import datetime date = datetime.datetime(2009, 1, 1) end = datetime.datetime(2010, 1, 1) oneday = datetime.timedelta(days=1) while date end: print date.date() date += oneday Correctness, formatting and efficiency are left as an exercise for the reader. ;-) -- Skip Montanaro - [EMAIL PROTECTED] - http://www.webfast.com/~skip/ -- http://mail.python.org/mailman/listinfo/python-list
Re: length of a tuple or a list containing only one element
[EMAIL PROTECTED] wrote: [...] Where OR, AND, XOR, NOT, SHL, SHR are the bitwise operators. Having to type (| |) often is less handy, for example this code: Which is precisely why bare parentheses are used. And remember, you often don't need to put the parentheses in. While this kind of beginner mistake is common it isn't one that's frequently repeated once the learner understands the syntax. regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Efficient way to remove objects from a list
Thanks! That's a more clear way! On Nov 3, 9:38 pm, Peter Otten [EMAIL PROTECTED] wrote: Chris Rebert wrote: On Mon, Nov 3, 2008 at 1:40 AM, 一首诗 [EMAIL PROTECTED] wrote: Hi all, Today I wrote some code like this: Build a new list as you go, then overwrite the old list with it. unfinished = [] for m in self.messages: if not m.finished: unfinished.append(m) continue #process the message Remove the following code fini = [m for m in self.messages if m.finished] for m in fini: self.messages.remove(m) self.messages[:] = unfinished Just self.messages = unfinished if also OK unless you have multiple references to the self.messages list. This way you aren't calling .remove() multiple times and only iterate through the list once. -- http://mail.python.org/mailman/listinfo/python-list
Re: CAD.py
Hello, I have pondered this notion of a 3d sketcher a bit myself. Before I go on, here is a quote from writer Neil Gaiman, author of some very good books: Every Published writer has had it - the people who come up to you and tell you that they've Got An Idea. And boy, is it a Doozy. It's such a Doozy that they want to Cut You In On It. The proposal is always the same - they'll tell you the idea (the hard bit), you write it down and turn it into a novel (the easy bit), the two of you split the money fifty-fifty In this spirit, let me offer the following observations/suggestions: Mayavi, the open source data visualization system from enthought.com, does a very nice job of high-level wrapping of The Visualization Toolkit. VTK has both high-level wrappings of OpenGL for display, as well as many modules to import/export various 3D file formats, merging or clipping 3D objects, constructive solid geometry, etc. All of the lower-level VTK routines can be accessed through the traited VTK wrapper (TVTK) from enthought. Once you have a Mayavi scene, it is a simple matter to add anything to it, or to modify any of the objects in the scene. Although Mayavi has evolved to be reasonably backend independent, the current version interacts most easily with the wxpython GUI toolkit. Given that they work well together, I would say that a combination of wxpython, Mayavi, and enthought Traits (recent stable versions and Python 2.5) could lead to a very interesting 3d sketching application. If you install the wxpython demos and samples (an absolute necessity if you program with wxpython), you can dig through the installation directory and find a samples subdirectory, and in there you can find another folder called pySketch. This app is a nice 2D sketching program with everything I really need for simple 2D sketches, except rotating objects (and I had to hack it to get a button to save an image and copy to clipboard) - it could probably also use buttons for various common drawing objects. If nothing else, this example might give an idea of a possible layout, and source for how to set it up. For the 3d sketching, you would have to have some buttons for object creation (various polyhedra, sphere, ellipse, arbitrary explicit function, implicit function, constructive solid geometry surface, maybe a library of predefined widgets), extruding, surfaces of rotations, button or menu for importing/exporting an object, some buttons for clipping and merging objects (additive and subtractive merges), some buttons for object transformations (scaling, rotations, precise placement in a scene, parametric stretching, twisting/turning, mirroring objects), button for duplications, and buttons for setting object materials/colors/properties. There are many examples of embedding a mayavi scene in other applications given in the examples directory at the mayavi/tvtk developer repository. Also, I have come to appreciate very much the wxpython AUI managed frame, which lets you move panels, toolbars, whatever, to pretty much any location within your frame. This means that anyone using your application can customize their layout with trivial effort. I doubt that I can get around to any of this until late next year, but I would be happy to assist if you want to take a shot at it... Cheers, Eric Carlson -- http://mail.python.org/mailman/listinfo/python-list
Re: Efficient way to remove objects from a list
一首诗 wrote: Hi all, Today I wrote some code like this: for m in self.messages: if not m.finished: continue #process the message fini = [m for m in self.messages if m.finished] for m in fini: self.messages.remove(m) As you can, I want to find these finished messages in self.messages, process them, and then remove them from the list. Because a list can not be modified while iterating it, I have to use a list fini to accomplish the target. I found a smell of bad performance here. Is there any faster ways? The typical way to do this is to iterate over the list in reverse order and then using the item index as basis for removing the item: for i, item in enumerate(reversed(mylist)): # process item del mylist[i] -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Nov 03 2008) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 -- http://mail.python.org/mailman/listinfo/python-list
Re: How to uninstall setuptools
Roger Erens wrote: On my Ubuntu8.04 box I installed python-all and subsequently setuptools for both 2.4 and 2.5 interpreters. To make a clean upgrade to 8.10 I need to uninstall setuptools. Any hints for doing that? It sounds as if you installed it using debian package management. Then you can just deinstall with that (or better yet upgrade). If you installed manually, it should suffice to rip out /usr/lib/python2.*/site-packages/[setuptools*|easy-install*] and /usr/bin/easy_install*. Diez -- http://mail.python.org/mailman/listinfo/python-list
encoding in lxml
Hey, I have a problem with character encoding in LXML. Here's how it goes: I read an HTML document from a third-party site. It is supposed to be in UTF-8, but unfortunately from time to time it's not. I parse the document like this: html_doc = HTML(string_with_document) Then I retrieve some info from the document with XPath: xpath_nodes = html_doc('/html/body/something') Now I'm guaranteed that the xpath_nodes list contains only one element. So I read it's content: xpath_nodes[0].text And I get exception here. The exception is coming from the text property of an Element object. The problem is that the text contains a non-utf8 character. LXML seems to be using strict decoding and I can't find a way to make it ignore the error. Is there anything I can do to retrieve the text without getting an exception? Regards, Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: wrapping a method function call?
On Mon, Nov 3, 2008 at 1:57 AM, [EMAIL PROTECTED] wrote: Steven D'Aprano [EMAIL PROTECTED] wrote: Now you can monkey patch class A if you want. It's probably not a great idea to do this in production code, as it will effect class A everywhere. This is perfect for me. The code in question is basically a protocol translator... it receives requests over the network, makes some calls, and returns the result translated back to the original protocol, so there's a single instance of each A,B, etc. A.p1 = precall(pre)(postcall(post)(A.p1)) Is there a way to do this for all callable methods of A? e.g. for x in callable_methods(A): x = precall(pre)(postcall(post)(x)) for name, attr in A.__dict__.iteritems(): if callable(attr): A.__dict__[name] = precall(pre)(postcall(post)(attr)) Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com Thanks! Mark -- Mark Harrison Pixar Animation Studios -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Structures
Paulo J. Matos wrote: Hi all, I am a Python beginner, reading through 2.6 tutorial. I am wondering where are structures? On the other hand, I think I might have the answer. Since Python focus on having one way to do it and structures are something like classes with only public methods, if I want structures that's what I should use. Is that right? yes regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: length of a tuple or a list containing only one element
Steve Holden: While this kind of beginner mistake is common it isn't one that's frequently repeated once the learner understands the syntax. You may be right, but I don't have to like it. When you teach programming to people that have never done it before, and you use Python, they spot similar inconsistences in the blink of an eye and often look annoyed. They want a clean language, so you have to explain them the difference between a practical engineering system (like Python/Scheme or on the opposite C++) and an abstract system that you can use to reason (like some parts of mathematics they know). The good thing is that Python3 fixes some of those things :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: CAD.py
On Nov 3, 8:29 am, Eric Carlson [EMAIL PROTECTED] wrote: Hello, I have pondered this notion of a 3d sketcher a bit myself. Before I go on, here is a quote from writer Neil Gaiman, author of some very good books: Every Published writer has had it - the people who come up to you and tell you that they've Got An Idea. And boy, is it a Doozy. It's such a Doozy that they want to Cut You In On It. The proposal is always the same - they'll tell you the idea (the hard bit), you write it down and turn it into a novel (the easy bit), the two of you split the money fifty-fifty In this spirit, let me offer the following observations/suggestions: Mayavi, the open source data visualization system from enthought.com, does a very nice job of high-level wrapping of The Visualization Toolkit. VTK has both high-level wrappings of OpenGL for display, as well as many modules to import/export various 3D file formats, merging or clipping 3D objects, constructive solid geometry, etc. All of the lower-level VTK routines can be accessed through the traited VTK wrapper (TVTK) from enthought. Once you have a Mayavi scene, it is a simple matter to add anything to it, or to modify any of the objects in the scene. Although Mayavi has evolved to be reasonably backend independent, the current version interacts most easily with the wxpython GUI toolkit. Given that they work well together, I would say that a combination of wxpython, Mayavi, and enthought Traits (recent stable versions and Python 2.5) could lead to a very interesting 3d sketching application. If you install the wxpython demos and samples (an absolute necessity if you program with wxpython), you can dig through the installation directory and find a samples subdirectory, and in there you can find another folder called pySketch. This app is a nice 2D sketching program with everything I really need for simple 2D sketches, except rotating objects (and I had to hack it to get a button to save an image and copy to clipboard) - it could probably also use buttons for various common drawing objects. If nothing else, this example might give an idea of a possible layout, and source for how to set it up. For the 3d sketching, you would have to have some buttons for object creation (various polyhedra, sphere, ellipse, arbitrary explicit function, implicit function, constructive solid geometry surface, maybe a library of predefined widgets), extruding, surfaces of rotations, button or menu for importing/exporting an object, some buttons for clipping and merging objects (additive and subtractive merges), some buttons for object transformations (scaling, rotations, precise placement in a scene, parametric stretching, twisting/turning, mirroring objects), button for duplications, and buttons for setting object materials/colors/properties. There are many examples of embedding a mayavi scene in other applications given in the examples directory at the mayavi/tvtk developer repository. Also, I have come to appreciate very much the wxpython AUI managed frame, which lets you move panels, toolbars, whatever, to pretty much any location within your frame. This means that anyone using your application can customize their layout with trivial effort. I doubt that I can get around to any of this until late next year, but I would be happy to assist if you want to take a shot at it... Cheers, Eric Carlson i don't see the gui as a problem, and i think using a toolkit would be a good idea at this point to get things going quickly. i have looked at vtk and it looks promising. -- http://mail.python.org/mailman/listinfo/python-list
Re: Executing a hidden/background program
On Nov 2, 6:32 am, [EMAIL PROTECTED] wrote: On Nov 2, 3:59 am, Mike Driscoll [EMAIL PROTECTED] wrote: You probably want to create a Windows service with Python. There are various ways to accomplish this. Was considering a Windows service too, however would like to avoid that as non-Admin users may not be able to do that. While I'm not familiar with threading, I'm considering starting a seperate thread and use a function such as os.pexec that hangs until the external daemon .exe exists. Check out the wx.lib.delayedresults option in the demo. Since wx.App needs to run as the main thread, you might be able to run your as the 'delayedresult'. As for the main frame of your app, simply Hide()/Show() when it needs to be visible. When the wx.App closes, the thread running the service will automatically shut down. Other than that ... I think it is a bit more complicated and will probably require asyncore and/or asynchat. g. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple textual calendar
Yes, I saw the calendar module, but, as I said, this isn't homework or something like that. It is an example which I've setted myself to try to solve to see how it would go. Calendar just gives me the solution :-( Part of the answer to a problem is knowing when not to duplicate effort that's already been exerted tested... :) However, yes, several of my mini apps have wanted to print decorated calendars on the command-line so I've had to rehash this logic. The code in the calendar.py can be instructive, and it's not to complex to use the calendar.monthcalendar(year, month) function to draw these calendars: from calendar import monthcalendar, month_name year = 2008 for month in range(1,13): print year, month_name[month] for i,week in enumerate(monthcalendar(year, month)): print Week %i % (i+1), for day in week: print %02i % day, print (adjust for special handling of day=0) -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie - merging xls files using xldt and xlwt
Mr Roskam, We have interacted before on the SPSS listserve, you have helped me out fair few times! I need a helping hand again, do you have the final solution to this problem, mergin xls from a given directory? Also where do I download the relevant modules from? Cheers Jigs 2008/10/15 Albert-jan Roskam [EMAIL PROTECTED] Hi John, Thanks! Using a higher xlrd version did the trick! Regarding your other remarks: -yep, input files with multiple sheets don't work yet. I kinda repressed that ;-) Spss outputs only single-sheet xls files, but I agree it's nicer if the programs works in other cases too. -and no, I don't intend to use data fields. Wouldn't it be easier to convert those to string values if I ever came across them? Thanks again! Albert-Jan --- On Wed, 10/15/08, John Machin [EMAIL PROTECTED] wrote: From: John Machin [EMAIL PROTECTED] Subject: Re: newbie - merging xls files using xldt and xlwt To: python-list@python.org Date: Wednesday, October 15, 2008, 3:14 PM On Oct 15, 9:16 pm, Albert-jan Roskam [EMAIL PROTECTED] wrote: Hi, I wrote the program below to merge all xls files in a given directory into one multisheet xls file. It uses xlwt and xlrd. The xls files I use for input are generated by Spss. When I open and re-save the files in Excel, the program works, but when I use the xls files as they were created by Spss, the program returns an error message (see below). Some details: Python 2.4, xlwt version 0.7.0, xlrd version 0.5.2, Win NT. Any ideas? The version of xlrd that you are using is an antique. Go to http://pypi.python.org/pypi/xlrd and get the latest version. If that doesn't work, send me a copy of one of the files that is displaying this problem. Thanks in advance! Albert-Jan Merge all xls files in a given directory into one multisheet xls file. The sheets get the orginal file name, without the extension. File names should not exceed 31 characters, as this is the maximum sheet name length import xlrd, xlwt import glob, os.path def merge_xls (in_dir, out_file=d:/merged_output.xls): xls_files = glob.glob(in_dir + *.xls) sheet_names = [] merged_book = xlwt.Workbook() [sheet_names.append(os.path.basename(v)[:-4]) for k, v in enumerate(xls_files)] Wah! Try this: sheet_names = [os.path.basename(v)[:-4]) for v in xls_files] for k, xls_file in enumerate(xls_files): if len (sheet_names[k]) = 31: book = xlrd.open_workbook(xls_file) ws = merged_book.add_sheet(sheet_names[k]) for sheetx in range(book.nsheets): sheet = book.sheet_by_index(sheetx) for rx in range(sheet.nrows): for cx in range(sheet.ncols): ws.write(rx, cx, sheet.cell_value(rx, cx)) I presume that you're not too worried about any date data. If an input file has more than 1 sheet, you are creating only one sheet in the output file, and overwriting cells. else: [snip] merge_xls(in_dir=d:/temp/) *** WARNING: OLE2 inconsistency: SSCS size is 0 but SSAT size is non-zero *** put_cell 0 1 Traceback (most recent call last): [snip] self._cell_types[rowx][colx] = ctype IndexError: list assignment index out of range Yeah, symptom of an xls file with a DIMENSIONS records that lies ... xlrd has like Excel become more resilient over time :-) BTW, consider joining the python-excel group at http://groups.google.com/group/python-excel Cheers, John -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: How to protect website from access without authentication?
This isn't really a Python question -- it's a Web development question. The easy answer is to just password protect the directory all the pages are stored in, and require a password. This can be set up using Apache or IIS. If what you really meant to ask was how to prevent anyone from accessing certain functionality, then you should look into using sessions, and write the pages you're worried about to require an authenticated session. This is better than the solution above for several reasons: You can grant different levels of permission to different users, you can revoke permission from some users while allowing it for others, and you can allow your users to each have their own password. Plus, you'll be able to log which user did what. If this wasn't helpful, please be much more specific in restating your question. Shawn On Mon, Nov 3, 2008 at 8:30 AM, Good Z [EMAIL PROTECTED] wrote: Dear All, We are developing a website and would like to password protect the whole site. If any user visit our site using ip address or using the http link, he/she will be asked for login password and then granted the access to whole site based on the correct password. Help will be appreciated. Thank Regards, Mike -- http://mail.python.org/mailman/listinfo/python-list -- http://i203.photobucket.com/albums/aa74/harrowlawl/sciencevsreligion.jpg -- http://mail.python.org/mailman/listinfo/python-list
Re: Decorator for validation - inefficient?
Steven D'Aprano wrote: On Sun, 02 Nov 2008 09:33:41 -0800, Bryan wrote: I'm coming from a .Net background, and yes, one of the reasons I did not consider raising exceptions was to avoid the overhead of an exception handler clause, which in .Net land is expensive. Actually catching an exception in Python is expensive, so I wouldn't recommend you use exceptions for message-passing in time-critical code. As I understand it, in your case you actually need to stop for user-input if the user's data fails the validation. If that's the case, an extra few milliseconds to catch an exception isn't going to matter much. some more thought on this: If I were going to be checking for validity during a property setter, I would probably raise an exception there, because the essence of what a client was requesting is set property, and an invalid value precludes this action from happening. However, hoping to make client code cleaner and to avoid setter functions doing expensive db lookup validations, I do not validate during the setter, but instead defer it until the client explicitly asks for the validity of the business object. Presumably if they *don't* explicitly ask, you validate anyway at some point? So the essence of the client's request at that point is what are the invalid values for the object, and an exception should only be raised if there was something stopping this request from being served. Invalid business object field values do not stop the functionality of the invalid() method. If I had a validation function that checked the db for a duplicate primary key, then the invalid() function should raise an exception if the db could not be contacted. Yes! A client should be on the lookout for that type of exception, but to throw a bunch of exceptions back at a client who simply requested a list of things that need to be fixed seems heavy. We would essentially be using Exceptions as an expected return value of a function. So a doc string would explain: Returns None for a valid object, and Exceptions for an invalid object. Should exceptions be an expected return value from a function? Am I still using my .Net brain? Because exceptions are first-class objects just like lists, ints and strings, there is a difference between *returning* an exception and *raising* an exception. E.g.: def build_exception(n): if n 0: raise ValueError('unexpected negative code') else: exc = TypeError('error code #%d' % n) exc.foo = More info here return exc try: obj = build_exception(57) print obj.foo another_obj = build_exception(-1) print We never get here except ValueError, e: print Failed with error message:, e.message Making the exception part of your code's API is perfectly legitimate and I would recommend it. The docstring could say this: Return None for a valid object, otherwise raises InvalidDataException (subclass of ValueError). You can get a list of errors from the exception's errorlist attribute. Here's a minimal way to generate the exception: class InvalidDataException(ValueError): pass and then in your validation code: def validate(obj): print Testing many things here e = InvalidDataException(failed because of %d errors) % 4 e.errorlist = [ too many questions, too few answers, not enough respect, and your query's hair is too long (damn hippy)] raise e That's one way. There are others. Have a browse through the standard library or the Python docs and see how other exceptions are used. But now that I have a better picture of your use-case, I'm leaning towards a completely different model. Rather than testing if the business object is valid, and raising an error if it isn't, you test it for errors, returning an empty list if there aren't any. def check_for_errors(obj): errorlist = [] print Testing many things here if too_many_questions(): errorlist.append(too many questions) # and any others return errorlist I've used strings as errors, but naturally they could be any object that makes sense for your application. -- Steven I like the errorlist attribute on the exception, I think I have a place for that in my project. Thanks for all the help, now the next thing I want to investigate is how I can write my validation code once and make it work both on my objects, and on webforms that edit those objects. I will always have strict validation in the object model that will be checked on the server side, but it would be convenient for the user if they were warned before making a round trip to the server that the values they entered are probably not correct. This project is using Pylons, so I'm off to investigate the possibilities. Bryan -- http://mail.python.org/mailman/listinfo/python-list
How to select text of text field in pythonCard
Hi, I need to select a text of text field! Which function is used for selection of text of text field? Sonia, _ Connect to the next generation of MSN Messenger http://imagine-msn.com/messenger/launch80/default.aspx?locale=en-ussource=wlmailtagline-- http://mail.python.org/mailman/listinfo/python-list
Re: length of a tuple or a list containing only one element
TP: This is actually the length of a bracketed string, not a tuple. Tuple's are defined by the existence of a comma...try: len(('foo',)) 1 Time ago I have suggested to change the tuple literal, to avoid the warts of the singleton and empty tuple, that may lead to bugs. But using ASCII alone it's not easy to find something suitable and nice. One of the suggestions of mine was to use (|...|) or [| x, ... |] to denote tuples. This may lead to problems with the bitwise operators, so the following two tuples: t1 = () t2 = (x | y,) Become (Fortress language uses similar liters, I think): t1 = (||) t2 = (| x OR y |) Or this: t1 = [||] t2 = [| x OR y |] Where OR, AND, XOR, NOT, SHL, SHR are the bitwise operators. Having to type (| |) often is less handy, for example this code: def divmod(a, b): return a // b, a % b d, r = divmod(10, 7) becomes: def divmod(a, b): return (| a // b, a % b |) (|d, r|) = divmod(10, 7) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Simplifying anonymous inner classes?
Is there a more Pythonic way to instantiate sub-classes and provide instance-specific implementations without the overhead of an unused anonymous class cluttering my code/namespace? I agree with Carl Banks that what you do is already fairly Pythonic: explicit is better than implicit, and simple is better than complex. What you do *is* simple, and easy to read - no magic involved. You wish it to be more concise - but I think that would make *less* pythonic, not more. After playing with the various solutions (hurray for version-control), I find myself back where I started, agreeing with Carl Martin for the most part. Everything else ended up looking so baroque that it made matters worse. Even the extra del statements for cleaning up the namespace were extra clutter in the code, so I didn't bother tidying the namespace. I did switch from do_foo = _Foo(args) do_bar = _Bar(args) to having each backend contain a list of available actions, so I simply maintain self.actions = set([ _Foo(args), _Bar(args), _Baz(args), ]) (each Action knows how to hash itself for entry in a set) and then descendants of Backend (such as DBBackend) simply add to this set of actions in their own __init__ call. The final product is what I'd call a most understandable/least convoluted solution which, in the big picture, seems to be a good part of pythonicity. Until such time as Python offers anonymous classes natively :) Thanks to all who offered suggestions. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: How to make money with Python!
On 31 Okt., 15:30, Duncan Booth [EMAIL PROTECTED] wrote: If that subject line didn't trip everyone's killfiles, see http://pythonide.blogspot.com/2008/10/how-to-make-money-with-free-sof... for a fantastic story involving Python. -- Duncan Boothhttp://kupuguy.blogspot.com Masterpiece. I dare to say it's much better than SPE ... -- http://mail.python.org/mailman/listinfo/python-list
How to uninstall setuptools
On my Ubuntu8.04 box I installed python-all and subsequently setuptools for both 2.4 and 2.5 interpreters. To make a clean upgrade to 8.10 I need to uninstall setuptools. Any hints for doing that? Thanks, Roger -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows DOS box redirection
On Fri, 31 Oct 2008 18:35:25 +0100, Stef Mientki wrote: Bill McClain wrote: On 2008-10-31, Tim Golden [EMAIL PROTECTED] wrote: You've got a few options. Ok, thanks! It is a small hobbyist community. I'll just document it and tell them life is hard for Windows users. Well I don't know any Windows users that still use DOS-boxes ;-) cheers, Stef -Bill Well, that is because newer Windows version (NT-family) no longer have DOS boxes. The black window in NT-family Windows are command prompt and is different from a real DOS box in previous Windows (non-NT-family). Anyway, I do use command prompts quite regularly, usually for simple pings and other simple commands like chkdsk, defrag, attrib, etc. Yes, I do know that each of these have GUI-equivalents. -- http://mail.python.org/mailman/listinfo/python-list
Re: Unyeilding a permutation generator
Steve Holden wrote: [EMAIL PROTECTED] wrote: Anyway what I want to do is experiment with code similar to this (i.e. same algorithm and keep the recursion) in other languages, particularly vbscript and wondered what it would look like if it was rewritten to NOT use the yield statement - or at least if it was amended so that it can be easily translated to other languages that dont have python's yield statement. I think the statement for perm in all_perms(str[1:]): will be hardest to replicate in a recursive vbscript program for example. There are various approaches you could use, the simplest of which is to provide a callback function as an additional argument to the all_perms function, and call it with the permutation as an argument in place of the yield statement. I had thought of three ways to avoid yield, that makes a fourth. Summary: 1. Think of generator function as an abbreviated iterator class and unabbreviate by writing a full iterator class with .__next__ (3.0). + Transparent to caller - Will often have to re-arrange code a bit to save locals values as attributes before returning. If there is an inner loop, efficiency may require copying attributes to locals. 2. Add to collection rather than yield, then return collection rather than raise StopIteration. + Transparent to caller; small change to function. - Returned collection can be arbitrarily large and take an arbitrarily long time to collect. 3. Add callback parameter and change 'yield value' to 'callback(value)'. + Minor change to generator function. - Minor to major change to caller to turn consumer code into a callback that somehow gets result of callback to where it is needed. (Avoiding the major changes sometimes needed was one of the motivations for generators.) 4. Combine caller and generator code by inlining one into or around the other. + Neither code will change much. - Loss benefit of modularity and reuse without cut-and-paste, which is subject to error. I have not thought through yet how well each of these work with recursive generators. Conclusion: Generators with yield make Python a great language for expressing combinatorial algorithms. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Unyeilding a permutation generator
On Nov 2, 10:34 pm, [EMAIL PROTECTED] wrote: Anyway what I want to do is experiment with code similar to this (i.e. same algorithm and keep the recursion) in other languages, particularly vbscript and wondered what it would look like if it was rewritten to NOT use the yield statement - or at least if it was amended so that it can be easily translated to other languages that dont have python's yield statement. I think the statement for perm in all_perms(str[1:]): will be hardest to replicate in a recursive vbscript program for example. Thanks for any constructive help given. Here is a solution which does not use yield, translittered from some Scheme code I have: def perm(lst): ll = len(lst) if ll == 0: return [] elif ll == 1: return [lst] else: return [[el] + ls for el in lst for ls in perm([e for e in lst if not e==el])] if __name__ == '__main__': print perm('abcd') -- http://mail.python.org/mailman/listinfo/python-list
Re: split() and string.whitespace
Steven D'Aprano wrote: On Fri, 31 Oct 2008 12:18:32 -0700, Chaim Krause wrote: I have arrived here while attempting to break down a larger problem. I got to this question when attempting to split a line on any whitespace character so that I could then add several other characters like ';' and ':'. Ultimately splitting a line on any char in a union of string.whitespace and some pre-designated chars. I am now beginning to think that I have outgrown split() and must move up to regular expressions. If that is the case, I will go off and RTFM on RegEx. Or just do this: s = the quickbrown\tdog\njumps over\r\n\t the lazy dog s = s.replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') s.split(' ') or even simpler: s.split() Or, for faster per-repetition (blending in to your use-case): import string SEP = string.maketrans('abc \t', ' ') ... parts = 'whatever, abalone dudes'.translate(SEP).split() print parts ['wh', 'tever,', 'lone', 'dudes'] --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Efficient way to remove objects from a list
Hi all, Today I wrote some code like this: for m in self.messages: if not m.finished: continue #process the message fini = [m for m in self.messages if m.finished] for m in fini: self.messages.remove(m) As you can, I want to find these finished messages in self.messages, process them, and then remove them from the list. Because a list can not be modified while iterating it, I have to use a list fini to accomplish the target. I found a smell of bad performance here. Is there any faster ways? -- http://mail.python.org/mailman/listinfo/python-list
Problem using urllib to download images
I am using Python 2.6 on Mac OS 10.3.9. I have been trying to use: image = urllib.URLopener() image.retrieve(url, filename) to download images from websites. I am able to do so, and end up with the appropriate file. However, when I try to open the file, I get an error message. It's something about corrupted data, and an unrecognised file. Anyone know what I'm talking about/had similar experiences? -Taidgh -- http://mail.python.org/mailman/listinfo/python-list
Structures
Hi all, I am a Python beginner, reading through 2.6 tutorial. I am wondering where are structures? On the other hand, I think I might have the answer. Since Python focus on having one way to do it and structures are something like classes with only public methods, if I want structures that's what I should use. Is that right? Cheers, -- Paulo Jorge Matos - pocmatos at gmail.com Webpage: http://www.personal.soton.ac.uk/pocm -- http://mail.python.org/mailman/listinfo/python-list
Re: Structures
Paulo J. Matos [EMAIL PROTECTED] writes: I am a Python beginner, reading through 2.6 tutorial. I am wondering where are structures? I'm wondering a more fundamental question: What are structures? That is, what do *you* mean by that term; without knowing that, an answer isn't likely to be meaningful. […] structures are something like classes with only public methods Care to say more about what they are, not what they're like? -- \ “Pinky, are you pondering what I'm pondering?” “Yes Brain, but | `\if our knees bent the other way, how would we ride a bicycle?” | _o__) —_Pinky and The Brain_ | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Tktable on 3.0rc1
Has anyone used Tktable on python 3.0 ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem using urllib to download images
On Nov 3, 11:48 am, [EMAIL PROTECTED] wrote: I am using Python 2.6 on Mac OS 10.3.9. I have been trying to use: image = urllib.URLopener() image.retrieve(url, filename) to download images from websites. I am able to do so, and end up with the appropriate file. However, when I try to open the file, I get an error message. It's something about corrupted data, and an unrecognised file. Anyone know what I'm talking about/had similar experiences? -Taidgh Please show an actual program, complete with error messages. import urllib image = urllib.URLopener() image.retrieve(http://www.python.org/images/success/nasa.jpg;, NASA.jpg) Works for me. -- http://mail.python.org/mailman/listinfo/python-list
Re: length of a tuple or a list containing only one element
[EMAIL PROTECTED] writes: Steve Holden: While this kind of beginner mistake is common it isn't one that's frequently repeated once the learner understands the syntax. You may be right, but I don't have to like it. When you teach programming to people that have never done it before, and you use Python, they spot similar inconsistences in the blink of an eye and often look annoyed. [...] You can teach them that the comma is a terminator rather than a separator (no more inconsistencies), but that the python parser is forgiving and understands when the last comma is missing if the expression is not already meaningful. I.e. one should write (1, 2, 3,) But python, being nice, understands when you write (1, 2, 3) Now consider this: 3 * (1 + 2) What interpretations should python take of the brackets? The good thing is that Python3 fixes some of those things :-) And introduces some new inconsistencies for newcomers, e.g. s = {1, 2, 3} # A set with 3 elements s = {1} # A set with one element s = {} # Surely, this should be an empty set!! -- Arnaud -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: length of a tuple or a list containing only one element
On Nov 3, 9:08 pm, TP [EMAIL PROTECTED] wrote: I have a question about the difference of behavior of len when applied on tuples or on lists. I mean: $ len( ( 'foo' ) ) 3 This is actually the length of a bracketed string, not a tuple. Tuple's are defined by the existence of a comma...try: len(('foo',)) 1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does numpy.array(a[0],b[0]) have this meaning?
Rick Giuly wrote: Hello All, Case 1 This generates an error, which makes sense because the argument should be a list of numbers: numpy.array(10,10) Case 2 This does not generate an error and the result is an array with a single element: a = numpy.array([10]) b = numpy.array([10]) numpy.array(a[0],b[0]) The only different I see here between the numpy.array call in the cases is that a[0] is a numpy int32 10 is an int Why would this minor difference in integer types cause a totally different result for the two cases - or is something else causing the difference in results? The second argument is for a dtype. Basically, we'll accept anything there that can be coerced to a dtype using numpy.dtype(). For some reason, we have an undocumented feature where dtype(some_array_or_numpy_scalar) will return the dtype of that value. Plain Python ints and floats don't have a dtype attached to them, so we raise an exception. If you have more numpy questions, please join us on the numpy-discussion mailing list. http://www.scipy.org/Mailing_Lists -- 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
Tiny yet useful utility
Process Manager for Windows (http:// processpriority.wiki.sourceforge.net/) It has always been a pain to use applications like Office/Outlook/Matlab/Delphi/Mozilla...Image editing s/w ...video editing s/w They take huge memory... they eat up half of your CPU and when you wanna close them, then also they take huge time . to get rid off all these... Arif has developed this small utility so now ... you can just right click on any application in taskbar and say Kill... Also if you wanna increase/decrease the priority of any application, then all you have to do is just one click on the application in the taskbar and say increase/decrease priority... He hopes public will like it and encourage him to add more features... You may check out the list of upcoming features click here Click here to download 300+ people are using Process Manager. If you like Process Manager leave a comment on Process Manger's blog -- http://mail.python.org/mailman/listinfo/python-list
Replacing cmp with key for sorting
I want to sort sequences of strings lexicographically but those with longer prefix should come earlier, e.g. for s = ['a', 'bc', 'bd', 'bcb', 'ba', 'ab'], the sorted sequence is ['ab', 'a', 'ba', 'bcb', 'bc', 'bd']. Currently I do it with: s.sort(cmp=lambda x,y: 0 if x==y else -1 if x.startswith(y) else +1 if y.startswith(x) else cmp(x,y)) Can this be done with an equivalent key function instead of cmp ? George -- http://mail.python.org/mailman/listinfo/python-list
Re: Tiny yet useful utility
Mariyam Process Manager for Windows Mariyam (http://processpriority.wiki.sourceforge.net/) It has always Mariyam been a pain to use applications like Mariyam Office/Outlook/Matlab/Delphi/Mozilla...Image editing s/w Mariyam ...video editing s/w What is the connection with Python? S -- http://mail.python.org/mailman/listinfo/python-list
Re: Tiny yet useful utility
On Nov 3, 12:55 pm, [EMAIL PROTECTED] wrote: Mariyam Process Manager for Windows Mariyam (http://processpriority.wiki.sourceforge.net/) It has always Mariyam been a pain to use applications like Mariyam Office/Outlook/Matlab/Delphi/Mozilla...Image editing s/w Mariyam ...video editing s/w What is the connection with Python? None, just a lame spamming attempt (well not totally lame, I clicked just in case it was written in Python). -- http://mail.python.org/mailman/listinfo/python-list
Re: push-style templating - an xml-like way to process xhtml
On approximately 11/3/2008 12:20 AM, came the following characters from the keyboard of has: On 2 Nov, 14:06, Tino Wildenhain [EMAIL PROTECTED] wrote: An opposite approach to this form of dynamic HTML production is called push-style templating, as coined by Terence Parr: Hm. a href=$attr.url$$attr.title$/a $if(attr.active)$ $attr.submenu:menuItem()$ $endif$ This looks ugly to me. It also looks like an embedded mini-language to me. At any rate, I think making a 'push/pull' distinction misses the point. There are basically three approaches a templating system can use: 1. embed your control logic in your presentation markup, 2. embed your presentation markup in your control logic, or 3. keep the two separate and transform the presentation markup into some sort of DOM that can then be manipulated by the control code. What's significant here is the division of labour within the overall program. With the first two approaches, the templating engine handles both presentation and control (i.e. pretty much the entire View layer). The third approach only provides the presentation part, and does and says nothing about how the control part is implemented. So you can't really make a direct comparison of, say, Cheetah against PyMeld, as they don't cover the same amount of ground. Instead, you ought to consider how the entire View layer is put together in each case: - A Cheetah-based View is implemented as an HTML file with all of the required control code embedded in it. - A PyMeld-based View is implemented as an HTML file with id attributes that indicate which HTML elements should be converted into object model nodes, *plus* a Python module containing the control code that manipulates those nodes when rendering a finished document. It would be nicest to keep the two separate... such that the HTML could be directly displayed in a browser, albeit with placeholder data items. The StringTemplate approach of nested, inherited subtemplates probably provides more power, and less cut-n-paste redundancy in development, but provides nothing for the designer to preview until the whole application is complete and specific data generated. It also results a view-independent superstructure from which it may be possible to generate other textual views without total recoding. One question is if designers come understanding multiple views, or if one has HTML-only designers, and other-modality-only designers, and that they don't speak enough of each others modalities to appreciate the view-independent superstructures enough to learn the mini-language that abstracts it. Even if there is a single view modality to be targeted, as is usually the case, if the cost to use a system that allows other modalities to be targeted, it is not an uncommon follow-on requirement to provide other view modalities. Systems that don't provide such wind up getting screen-scraped, which is a pitiful solution, although sometimes cost-effective. Unfortunately, keeping the two languages separate adds significantly to the burden of figuring out how to mix them together. Intermingled/embedded control and presentation (either embedded print statements, or templating systems), have become popular (in my opinion) because they do solve the problem of figuring out how do the mix. Terence Parr's more formal research into this topic, and his attempts to enforce separation between Model, View, Controller, and the new concept of Renderer, embodied in StringTemplate, may help to prove that these 4 items can be separated, which is architecturally good... but does little or nothing to make the mixing of languages less ugly. I took a brief look at the PyMeld approach, and it seems that the HTML file, while providing all the HTML syntax necessary for the project, leaves all decisions about what items should be replicated, and how and when to replicate them, to the controller. The use of Python (hey, I don't mind using Python!) as the language (together with an API) for the controller, though, does seem to avoid enforcement of the separation between view and model; there is nothing to prevent Python from massaging the model data in whatever manner it likes, being a general purpose language. Likewise, the controller can manipulate the presentation data, potentially in ways other than simply replicating an item. Apparently it can insert and delete items from the presentation at will. Hence, this avoids the enforcement of the separation between the view and the controller. So while PyMeld is no doubt a rich templating system, and allows a way of implementing separated MVC items, it is apparently not attempting to enforce that separation, as StringTemplate does. While the ID attribute is intended (in the HTML spec) to uniquely identify a particular item, its use to identify items for PyMeld manipulation may or may not conflict with other desired uses. There is nothing in the HTML
Re: Problem using urllib to download images
Then perhaps it's a problem with my os. [TERMINAL SESSION] [18:16:33 Mon Nov 03] python Python 2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04) [GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin Type help, copyright, credits or license for more information. import urllib url = 'http://www.google.com/webhp?hl=en' filename = 'logo.gif' image = urllib.URLopener() image.retrieve(url, filename) ('logo.gif', httplib.HTTPMessage instance at 0x5196e8) [/TERMINAL SESSION] And here's the error message I get when I try to open it: File Error: Couldn't open the file. It may be corrupt or a file format that Preview doesn't recognize.. I have had a similar result trying to open it with other programs. -Taidgh -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacing cmp with key for sorting
On Nov 3, 6:49 pm, George Sakkis [EMAIL PROTECTED] wrote: I want to sort sequences of strings lexicographically but those with longer prefix should come earlier, e.g. for s = ['a', 'bc', 'bd', 'bcb', 'ba', 'ab'], the sorted sequence is ['ab', 'a', 'ba', 'bcb', 'bc', 'bd']. Currently I do it with: s.sort(cmp=lambda x,y: 0 if x==y else -1 if x.startswith(y) else +1 if y.startswith(x) else cmp(x,y)) Can this be done with an equivalent key function instead of cmp ? George Your input and output: s = ['a', 'bc', 'bd', 'bcb', 'ba', 'ab'] r = ['ab', 'a', 'ba', 'bcb', 'bc', 'bd'] To me your lambda looks like an abuse of the inline if expression. So I suggest to replace it with a true function, that is more readable: def mycmp(x, y): if x == y: return 0 elif x.startswith(y): return -1 elif y.startswith(x): return +1 else: return cmp(x, y) print sorted(s, cmp=mycmp) It's a peculiar cmp function, I'm thinking still in what situations it can be useful. To use the key argument given a cmp function I use the simple code written by Hettinger: def cmp2key(mycmp): Converts a cmp= function into a key= function class K: def __init__(self, obj, *args): self.obj = obj def __cmp__(self, other): return mycmp(self.obj, other.obj) return K print sorted(s, key=cmp2key(mycmp)) Now I'll look for simpler solutions... Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: length of a tuple or a list containing only one element
Arnaud Delobelle: And introduces some new inconsistencies for newcomers, e.g. s = {1, 2, 3} # A set with 3 elements s = {1} # A set with one element s = {} # Surely, this should be an empty set!! Are you able to list other inconsistencies? Python3 introduces one or two warts, but removes many more inconsistencies, so for me it's a net gain. So far for me, beside the one you have shown, there's only another detail I don't like of Python3 (the removal of tuple unpaking in function calls). Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacing cmp with key for sorting
George Sakkis wrote: s.sort(cmp=lambda x,y: 0 if x==y else -1 if x.startswith(y) else +1 if y.startswith(x) else cmp(x,y)) Probably not what you had in mind ... s ['a', 'bc', 'bd', 'bcb', 'ba', 'ab'] maxlen = max(len(si) for si in s) def k(si): return si+'z'*(maxlen-len(si)) ... sorted(s,key=k) ['ab', 'a', 'ba', 'bcb', 'bc', 'bd'] Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacing cmp with key for sorting
George Sakkis [EMAIL PROTECTED] writes: I want to sort sequences of strings lexicographically but those with longer prefix should come earlier, e.g. for s = ['a', 'bc', 'bd', 'bcb', 'ba', 'ab'], the sorted sequence is ['ab', 'a', 'ba', 'bcb', 'bc', 'bd']. Currently I do it with: s.sort(cmp=lambda x,y: 0 if x==y else -1 if x.startswith(y) else +1 if y.startswith(x) else cmp(x,y)) Can this be done with an equivalent key function instead of cmp ? Here's an idea: sorted(s, key=lambda x: x+'z'*(3-len(s))) ['ab', 'a', 'ba', 'bcb', 'bc', 'bd'] The 3 above is the length of the longest string in the list Here's another idea, probably more practical: sorted(s, key=lambda x: tuple(256-ord(l) for l in x), reverse=True) ['ab', 'a', 'ba', 'bcb', 'bc', 'bd'] HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem using urllib to download images
On Mon, Nov 3, 2008 at 2:21 PM, [EMAIL PROTECTED] wrote: Then perhaps it's a problem with my os. [TERMINAL SESSION] [18:16:33 Mon Nov 03] python Python 2.6 (trunk:66714:66715M, Oct 1 2008, 18:36:04) [GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin Type help, copyright, credits or license for more information. import urllib url = 'http://www.google.com/webhp?hl=en' That's not the URL of an image file. Maybe you're looking for url = 'http://www.google.com/intl/en_ALL/images/logo.gif' filename = 'logo.gif' image = urllib.URLopener() image.retrieve(url, filename) ('logo.gif', httplib.HTTPMessage instance at 0x5196e8) [/TERMINAL SESSION] And here's the error message I get when I try to open it: File Error: Couldn't open the file. It may be corrupt or a file format that Preview doesn't recognize.. I have had a similar result trying to open it with other programs. That's because you downloaded some HTML and saved it in a file named logo.gif. That's unlikely to work in any image viewing program. Try opening the file you downloaded in a text editor and you'll see. -- Jerry -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacing cmp with key for sorting
Alan G Isaac: Probably not what you had in mind ... ... maxlen = max(len(si) for si in s) def k(si): return si+'z'*(maxlen-len(si)) This looks a little better: assert isinstance(s, str) sorted(s, key=lambda p: p.ljust(maxlen, \255)) If the string is an unicode that may not work anymore. I don't know if there are better solutions. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: encoding in lxml
Hi Mike, I read an HTML document from a third-party site. It is supposed to be in UTF-8, but unfortunately from time to time it's not. There will be host of more lightweight solutions, but you can opt to sanizite incominhg HTML with HTML Tidy (python binding available). It will replace invalid UTF-8 bytes with U+FFFD. It will not guess a better encoding to use. If you are sure you don't have HTML sloppiness to correct but only the occasional wrong byte, even decoding (with fallback) and encoding using the standard codec package will do. Regards, Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: wrapping a method function call?
On Nov 3, 3:57 am, [EMAIL PROTECTED] wrote: Steven D'Aprano [EMAIL PROTECTED] wrote: Now you can monkey patch class A if you want. It's probably not a great idea to do this in production code, as it will effect class A everywhere. This is perfect for me. The code in question is basically a protocol translator... it receives requests over the network, makes some calls, and returns the result translated back to the original protocol, so there's a single instance of each A,B, etc. A.p1 = precall(pre)(postcall(post)(A.p1)) Is there a way to do this for all callable methods of A? e.g. for x in callable_methods(A): x = precall(pre)(postcall(post)(x)) Thanks! Mark -- Mark Harrison Pixar Animation Studios Hi, that sounds like metaclasses. from types import * def pre( self, *ar, **kwar ): print 'in pre' def post( self, *ar, **kwar ): print 'in post' class metacls(type): def __new__(mcs, name, bases, dict): for k, x in dict.items(): if isinstance( x, FunctionType ): def modx( f ): def _mod( *arg, **kwarg ): pre( *arg, **kwarg ) retval= f( *arg, **kwarg ) post( *arg, **kwarg ) return retval return _mod dict[ k ]= modx( x ) return type.__new__(mcs, name, bases, dict) class A( object ): __metaclass__= metacls def f( self ): print 'in f' a= A() a.f() /Output: in pre in f in post -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem using urllib to download images
That's because you downloaded some HTML and saved it in a file named logo.gif. That's unlikely to work in any image viewing program. Try opening the file you downloaded in a text editor and you'll see. -- Jerry Aha, so the first param is the file, and second is the name you save the files as. Thankyou, for pointing out my stupid mistake. I was confused by trying to replicate a program called 'comicdownloader.py' off of uselesspython.com. I thought that the first param was the page containing the file, and the second was the file. And that the file would simply be saved as it's name on the website. Thanks again. -Taidgh -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacing cmp with key for sorting
[EMAIL PROTECTED] writes: Arnaud Delobelle: Here's another idea, probably more practical: sorted(s, key=lambda x: tuple(256-ord(l) for l in x), reverse=True) Nice. A variant that probably works with unicode strings too: print sorted(s, key=lambda x: [-ord(l) for l in x], reverse=True) Of course that's better! (although mine will work with unicode if yours does). It's funny how the obvious escapes me so often. Still I think the idea of the 'double reverse' (one letterwise, the other listwise) was quite good. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacing cmp with key for sorting
Arnaud Delobelle: Here's another idea, probably more practical: sorted(s, key=lambda x: tuple(256-ord(l) for l in x), reverse=True) Nice. A variant that probably works with unicode strings too: print sorted(s, key=lambda x: [-ord(l) for l in x], reverse=True) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the instance reference of an object
On Nov 2, 10:13 pm, Steven D'Aprano [EMAIL PROTECTED] wrote: On Sun, 02 Nov 2008 13:23:11 -0800, Aaron Brady wrote: But, doing so, an object is not the same as a reference to it, and all Python does is pass and copy references. No, that's what at least one particular implementation of Python does. That's not what Python does. The Python VM doesn't have any concept of values or references or values which are actually references in disguise. The Python VM knows about *names in namespaces* and *objects*. -- Steven I think we can conclude that Python passes by reference, since a function can modify objects that were passed in to it. -- http://mail.python.org/mailman/listinfo/python-list
Re: length of a tuple or a list containing only one element
TP [EMAIL PROTECTED] writes: Hi everybody, I have a question about the difference of behavior of len when applied on tuples or on lists. I mean: $ len( ( 'foo', 'bar' ) ) 2 $ len( ( 'foo' ) ) 3 $ len( [ 'foo', 'bar' ] ) 2 $ len( [ 'foo' ] ) 1 For making a literal tuple, parentheses are irrelevant; only the commas matter: type( ('foo', 'bar') ) type 'tuple' type( ('foo',) ) type 'tuple' type( ('foo') ) type 'str' However, for making a literal list, the brackets do matter: type( ['foo', 'bar'] ) type 'list' type( ['foo',] ) type 'list' type( ['foo'] ) type 'list' -- \ “The way to build large Python applications is to componentize | `\ and loosely-couple the hell out of everything.” —Aahz | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
redirection in a file with os.system
Hi everybody, The following code does not redirect the output of os.system(ls) in a file: import sys, os saveout = sys.stdout fd = open( 'toto', 'w' ) sys.stdout = fd os.system( ls ) sys.stdout = saveout fd.close() Whereas the following works: old_stdout = os.dup( sys.stdout.fileno() ) fd = os.open( 'bar', os.O_CREAT | os.O_WRONLY ) os.dup2( fd, sys.stdout.fileno() ) os.system( ls ) os.close( fd ) os.dup2( old_stdout, sys.stdout.fileno() ) Why? I have another question: with this last code using os.open, the problem is that the file 'bar' is not removed before being written. So, it could lead to errors: the file 'bar' is overwritten, but extra lines from previous executions could remain. Am I compelled to use os.unlink (or os.remove) before calling os.system(ls)? Thanks Julien -- python -c print ''.join([chr(154 - ord(c)) for c in '*9(9(18%.91+,\'Z (55l4(']) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong. (first law of AC Clarke) -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacing cmp with key for sorting
Arnaud Delobelle: It's funny how the obvious escapes me so often. In this case it's a well known cognitive effect: the mind of humans clings to first good/working solution, not allowing its final tuning. For that you may need to think about something else for a short time, and then look at your solution with a little fresher mind. This (ugly) translation into D + my functional-style libs shows why Python syntax is a good idea: import d.all; void main() { auto txt = a bc bd bcb ba ab.split(); putr( sorted(txt, (string s){ return map((char c){return - cast(int)c;}, s);} ).reverse ); } Long Live To Python! :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: redirection in a file with os.system
TP [EMAIL PROTECTED] writes: Hi everybody, The following code does not redirect the output of os.system(ls) in a file: import sys, os saveout = sys.stdout fd = open( 'toto', 'w' ) sys.stdout = fd os.system( ls ) sys.stdout = saveout fd.close() Whereas the following works: old_stdout = os.dup( sys.stdout.fileno() ) fd = os.open( 'bar', os.O_CREAT | os.O_WRONLY ) os.dup2( fd, sys.stdout.fileno() ) os.system( ls ) os.close( fd ) os.dup2( old_stdout, sys.stdout.fileno() ) Why? I have another question: with this last code using os.open, the problem is that the file 'bar' is not removed before being written. So, it could lead to errors: the file 'bar' is overwritten, but extra lines from previous executions could remain. Am I compelled to use os.unlink (or os.remove) before calling os.system(ls)? Do you have to use low level os functions? Why not use the subprocess module? E.g subprocess.call('ls', stdout=open('toto', 'w') HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
script that parses command line, and execfile('')
Hello, I have a script that uses the optparse package to parse the command line. For example: $ script.py --help # displays help about script.py Is this possible to call such a script with execfile('') once in the Python interactive shell? execfile( 'script.py' ) I get errors because there is no argv dictionary when used with execfile. How to solve this problem, so that I am able to use script.py in command line as well as with execfile? Thanks Julien -- python -c print ''.join([chr(154 - ord(c)) for c in '*9(9(18%.91+,\'Z (55l4(']) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong. (first law of AC Clarke) -- http://mail.python.org/mailman/listinfo/python-list
Re: script that parses command line, and execfile('')
TP [EMAIL PROTECTED] writes: Hello, I have a script that uses the optparse package to parse the command line. For example: $ script.py --help # displays help about script.py Is this possible to call such a script with execfile('') once in the Python interactive shell? execfile( 'script.py' ) I get errors because there is no argv dictionary when used with execfile. How to solve this problem, so that I am able to use script.py in command line as well as with execfile? Have you tried setting sys.argv manually? e.g. import sys sys.argv = ['--help'] execfile('script.py') But I have to say I have never felt the need to use execfile() this way. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: 2.6, 3.0, and truly independent intepreters
On Oct 30, 11:09 pm, alex23 [EMAIL PROTECTED] wrote: On Oct 31, 2:05 am, Andy O'Meara [EMAIL PROTECTED] wrote: I don't follow you there. If you're referring to multiprocessing, our concerns are: - Maturity (am I willing to tell my partners and employees that I'm betting our future on a brand-new module that imposes significant restrictions as to how our app operates?) - Liability (am I ready to invest our resources into lots of new python module-specific code to find out that a platform that we want to target isn't supported or has problems?). Like it not, we're a company and we have to show sensitivity about new or fringe packages that make our codebase less agile -- C/C++ continues to win the day in that department. I don't follow this...wouldn't both of these concerns be even more true for modifying the CPython interpreter to provide the functionality you want? A great point, for sure. So, basically, the motivation and goal of this entire thread is to get an understanding for how enthusiastic/ interested the CPython dev community is at the concepts/enhancements under discussion and for all of us to better understand the root issues. So my response is basically that it was my intention to seek official/sanctioned development (and contribute developer direct support and compensation). My hope was that the increasing interest and value associated with flexible, multi-core/free-thread support is at a point where there's a critical mass of CPython developer interest (as indicated by various serious projects specifically meant to offer this support). Unfortunately, based on the posts in this thread, it's becoming clear that the scale of code changes, design changes, and testing that are necessary in order to offer this support is just too large unless the entire community is committed to the cause. Meanwhile, as many posts in the thread have pointed out, issues such as free threading and easy/clean/compartmentalized use of python are of rising importance to app developers shopping for an interpreter to embed. So unless/until CPython offers the flexibility some apps require as an embedded interpreter, we commercial guys are unfortunately forced to use alternatives to python. I just think it'd be huge win for everyone (app developers, the python dev community, and python proliferation in general) if python made its way into more commercial and industrial applications (in an embedded capacity). Andy -- http://mail.python.org/mailman/listinfo/python-list
Re: length of a tuple or a list containing only one element
Tim Chase wrote: For making a literal tuple, parentheses are irrelevant; only the commas matter: I don't think I'd go so far as to say that the parentheses around tuples are *irrelevant*...maybe just relevant in select contexts def foo(*args): ... for i, arg in enumerate(args): ... print i, arg ... foo(1,2) 0 1 1 2 foo((1,2)) # these parens are pretty important :) 0 (1, 2) pedantically-grinning-ducktyping-and-running-ly yers, I'll see your pedantry and raise you one: foo() foo(()) 0 () --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: script that parses command line, and execfile('')
TP schrieb: Hello, I have a script that uses the optparse package to parse the command line. For example: $ script.py --help # displays help about script.py Is this possible to call such a script with execfile('') once in the Python interactive shell? execfile( 'script.py' ) I get errors because there is no argv dictionary when used with execfile. How to solve this problem, so that I am able to use script.py in command line as well as with execfile? Don't use execfile. Make script.py like this: ... def main(argv=None): if argv is None: argv = sys.argv[1:] ... Then just do import script script.main(arguments) instead. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: length of a tuple or a list containing only one element
For making a literal tuple, parentheses are irrelevant; only the commas matter: I don't think I'd go so far as to say that the parentheses around tuples are *irrelevant*...maybe just relevant in select contexts def foo(*args): ... for i, arg in enumerate(args): ... print i, arg ... foo(1,2) 0 1 1 2 foo((1,2)) # these parens are pretty important :) 0 (1, 2) pedantically-grinning-ducktyping-and-running-ly yers, I'll see your pedantry and raise you one: foo() foo(()) 0 () And just because another tuples without parens case exists: foo(,) File stdin, line 1 foo(,) ^ SyntaxError: invalid syntax To maintain the poker theme, I'd say You raised, and I call but my call fails :-P -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: encoding in lxml
jasiu85 wrote: I have a problem with character encoding in LXML. Here's how it goes: I read an HTML document from a third-party site. It is supposed to be in UTF-8, but unfortunately from time to time it's not. You can instantiate your own HTML parser and pass encoding=utf-8. That way, when it's not UTF-8, you will get an exception at parse time, which allows you to reparse the document with another encoding (say, ISO-8859-1) to get the correct content. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacing cmp with key for sorting
On Nov 3, 1:51 pm, [EMAIL PROTECTED] wrote: Arnaud Delobelle: Here's another idea, probably more practical: sorted(s, key=lambda x: tuple(256-ord(l) for l in x), reverse=True) Nice. A variant that probably works with unicode strings too: print sorted(s, key=lambda x: [-ord(l) for l in x], reverse=True) Bye, bearophile Awesome! I tested it on a sample list of ~61K words [1] and it's almost 40% faster, from ~1.05s dropped to ~0.62s. That's still 15 times slower than the default sorting (0.04s) but I guess there's not much more room for improvement. George [1] http://www.cs.pitt.edu/~kirk/cs1501/Pruhs/Spring2006/assignments/boggle/5desk.txt -- http://mail.python.org/mailman/listinfo/python-list
How do I find the memory used by a python process
I'm trying to create a python unit-test which will test a complex program which includes a number of functions which have been implemented in C or C++. The unit-test needs to check that after the functions have been run a few thousand times all of the memory used by those functions has been un-allocated, i.e. that there are no memory leaks. I was wondering if there is some way of finding out how much memory the current thread is using. I would like some kind of simple function call that gives me the current memory usage of the current process or thread. So each test would check the amount of memory available, call the function N times and then check the amount of memory available afterwards. If the amount of memory before and after changes by a certain amount then the test is failed. All of our unit-tests are single threaded processes. We run Windows and Python 2.4. Any suggestions? Thanks! Sal -- http://mail.python.org/mailman/listinfo/python-list
Re: Structures
On Mon, Nov 3, 2008 at 12:32 PM, Ben Finney [EMAIL PROTECTED] wrote: Paulo J. Matos [EMAIL PROTECTED] writes: I am a Python beginner, reading through 2.6 tutorial. I am wondering where are structures? I'm wondering a more fundamental question: What are structures? That is, what do *you* mean by that term; without knowing that, an answer isn't likely to be meaningful. […] structures are something like classes with only public methods Care to say more about what they are, not what they're like? Well, I guess that everyone pretty much gets since it exists in every other language as struct, or define-structure, or whatever is the syntax. Still, answering your rhetoric question, a structure is way to gather information by fields and those fields are referenced by name. The fact that python 2.6 has now named tuples is a breath of fresh air! -- \ Pinky, are you pondering what I'm pondering? Yes Brain, but | `\if our knees bent the other way, how would we ride a bicycle? | _o__) —_Pinky and The Brain_ | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list -- Paulo Jorge Matos - pocmatos at gmail.com Webpage: http://www.personal.soton.ac.uk/pocm -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I find the memory used by a python process
So each test would check the amount of memory available, call the function N times and then check the amount of memory available afterwards. If the amount of memory before and after changes by a certain amount then the test is failed. Please take a look at the muppy package: http://pypi.python.org/pypi/muppy Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the instance reference of an object
On Nov 3, 2008, at 12:00 PM, Aaron Brady wrote: I think we can conclude that Python passes by reference, since a function can modify objects that were passed in to it. Then please write the Python equivalent of the Swap methods shown at http://www.strout.net/info/coding/valref/ (or at http://javadude.com/articles/passbyvalue.htm , for that matter). And no fair wrapping the two parameters up in an object or using tuple packing/unpacking -- the point is to demonstrate that you can change the two parameters themselves, not some object that contains them or return them a different order. And by the way, if mutating an object a parameter refers to qualifies as pass by reference, then Java, VB.NET/REALbasic (in ByVal mode), and C/C++ all pass by reference too. That'll be quite a surprise to their compiler authors! (I should know, as I'm one of them.) Best, - Joe -- http://mail.python.org/mailman/listinfo/python-list
Re: Unyeilding a permutation generator
On Sun, 2 Nov 2008 14:09:01 -0800 (PST), Aaron Brady [EMAIL PROTECTED] wrote: On Nov 2, 3:34 pm, [EMAIL PROTECTED] wrote: ... for x in all_permx(ABCD): print x ... I think multi-threading is the truest to the original. You might develop a framework to set events when particular generators are to take a turn, place their yields, per se, in a particular place, set the return event, etc., and reuse it. Of course, starting threads in VBS might be another matter. Why multi-threading? I see no concurrency in the original algorithm. There is, in my mind, nothing concurrent about 'yield'. /Jorgen -- // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.se R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple textual calendar
On Mon, 03 Nov 2008 09:17:25 -0600, Tim Chase [EMAIL PROTECTED] wrote: Yes, I saw the calendar module, but, as I said, this isn't homework or something like that. It is an example which I've setted myself to try to solve to see how it would go. Calendar just gives me the solution :-( Part of the answer to a problem is knowing when not to duplicate effort that's already been exerted tested... :) But this one is a good intellectual exercise which combines puzzle elements and outside requirements (i.e. what a calendar looks like). And besides, someone has to write those modules, you know ;-) I'd start with just one month, and a piece of paper. Assuming Sunday starts the week: s m t w t f s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . It's obvious that worst-case you need six rows. Then I'd pretend that the day-of-week of the 1st, and the number of days in the month are inputs to the problem so I don't have to worry about them. And I'd pretend that the output is just a list of 7*6 numbers, with 0 for the unused days (or None, or ''). def month(weekday1, days): # - list of 42 numbers pass Then I'd pick an example: a month with the 1st on Tuesday (2) and 30 days. That would be [0]*2 + [1 .. 30] + [0]*10. And that more or less makes the solution (of this sub-problem) obvious. I'd implement it, write unit tests, and move on to the next part of the problem with a bit more confidence. /Jorgen -- // Jorgen Grahn grahn@Ph'nglui mglw'nafh Cthulhu \X/ snipabacken.se R'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding the instance reference of an object
On Nov 3, 2:44 pm, Joe Strout [EMAIL PROTECTED] wrote: On Nov 3, 2008, at 12:00 PM, Aaron Brady wrote: I think we can conclude that Python passes by reference, since a function can modify objects that were passed in to it. Then please write the Python equivalent of the Swap methods shown at http://www.strout.net/info/coding/valref/ (or at http://javadude.com/articles/passbyvalue.htm , for that matter). And no fair wrapping the two parameters up in an object or using tuple packing/unpacking -- the point is to demonstrate that you can change the two parameters themselves, not some object that contains them or return them a different order. And by the way, if mutating an object a parameter refers to qualifies as pass by reference, then Java, VB.NET/REALbasic (in ByVal mode), and C/C++ all pass by reference too. That'll be quite a surprise to their compiler authors! (I should know, as I'm one of them.) Best, - Joe Python can do the swap operation on mutable types, for example. By-Value and By-Reference are not the only passing methods. True or False? -- http://mail.python.org/mailman/listinfo/python-list
Re: Structures
Paulo J. Matos [EMAIL PROTECTED] writes: On Mon, Nov 3, 2008 at 12:32 PM, Ben Finney [EMAIL PROTECTED] wrote: I'm wondering a more fundamental question: What are structures? That is, what do *you* mean by that term; without knowing that, an answer isn't likely to be meaningful. Well, I guess that everyone pretty much gets since it exists in every other language as struct, or define-structure, or whatever is the syntax. Take care with broad sweeping statements about “every other language”, or even “most other languages”. They are usually flat-out wrong: there is a stunning variety of different approaches and concepts in programming languages, with very little common to even a majority of them. So no, the question was entirely honest and not a rhetorical device. Still, answering your rhetoric question, a structure is way to gather information by fields and those fields are referenced by name. Okay, you're talking about ‘struct’ from the C language. That helps answer the question. In Python, the way to do that is with a dict. A class can be used, but is often overkill if one doesn't need customised behaviour. The fact that python 2.6 has now named tuples is a breath of fresh air! That works also, but a dict will be more broadly useful; and compatible with any Python version. -- \ “Creativity can be a social contribution, but only in so far as | `\society is free to use the results.” —Richard Stallman | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I find the memory used by a python process
Salim Fadhley [EMAIL PROTECTED] writes: The unit-test needs to check that after the functions have been run a few thousand times all of the memory used by those functions has been un-allocated, i.e. that there are no memory leaks. This is a great test case, thanks. I must add it to my store of generally-applicable unit test cases. However, I wonder why you specify the need to run the function *thousands* of times to test whether it releases memory. Surely your code unit is deterministic and will release memory (or not) the same way with the same inputs each time? -- \ “The right to use [strong cryptography] is the right to speak | `\ Navajo.” —Eben Moglen | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list