ANN: Mock 0.5.0 Release
Mock 0.5.0 has just been released. * Mock Homepage http://www.voidspace.org.uk/python/mock/ * Download Mock 0.5.0 release (zip) http://www.voidspace.org.uk/downloads/mock-0.5.0.zip * Mock Documentation as a PDF http://www.voidspace.org.uk/downloads/mock.pdf * Mock entry on PyPI http://pypi.python.org/pypi/mock/ * Repository and Issue Tracker on Google Code http://code.google.com/p/mock/ This *isn't* backwards compatible as it cleans up the API in a few ways, but they're all good changes I promise. One of the new features is that the Mock class now supports wrapping objects; using the ``wraps`` keyword. Mock is a library for the creation of simple mock objects that track how they are used so that you can make assertions. It uses the action - assertion pattern rather than the record - replay pattern. Action - assertion puts your tests after you have used the objects, which seems more natural and means that you can make assertions about only the behavior you are interested in. Mock also contains two decorators (``patch`` and ``patch_object``) which make it easy to safely mock out dependencies in the module under test purely within the scope of the test itself (unpatching is done automatically on exit whether or not the test passes). One of the changes in this release is that these decorators also become context managers allowing them to be used with the 'with statement'. Mock can be installed with: ``easy_install mock`` The changelog for all changes in this release is: * Made DEFAULT part of the public api. * Documentation built with Sphinx. * ``side_effect`` is now called with the same arguments as the mock is called with and if returns a non-DEFAULT value that is automatically set as the ``mock.return_value``. * ``wraps`` keyword argument used for wrapping objects (and passing calls through to the wrapped object). * ``Mock.reset`` renamed to ``Mock.reset_mock``, as reset is a common API name. * ``patch`` / ``patch_object`` are now context managers and can be used with ``with``. * A new 'create' keyword argument to patch and patch_object that allows them to patch (and unpatch) attributes that don't exist. (Potentially unsafe to use - it can allow you to have tests that pass when they are testing an API that doesn't exist - use at your own risk!) * The methods keyword argument to Mock has been removed and merged with spec. The spec argument can now be a list of methods or an object to take the spec from. * Nested patches may now be applied in a different order (created mocks passed in the opposite order). This is actually a bugfix. * patch and patch_object now take a spec keyword argument. If spec is passed in as 'True' then the Mock created will take the object it is replacing as its spec object. If the object being replaced is a class, then the return value for the mock will also use the class as a spec. * A Mock created without a spec will not attempt to mock any magic methods / attributes (they will raise an ``AttributeError`` instead). Many thanks to all those who gave feedback, feature requests and patches! What *isn't* in 0.5.0 is support for mocking magic methods. I do have a technique in mind for this, which I implemented for the container methods. It is very clean, but different from the pattern used to mock out other methods. As I'm not currently using it I'm going to wait until I need it and see if it works well in practise. If you're interested in trying it, the code (with full documentation) in a 'magics branch': * http://code.google.com/p/mock/source/browse/#svn/branches/magics -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
ANN: pyparsing 1.5.2 released!
Well, it has been about 6 months since the release of pyparsing 1.5.1, and there have been no new functional enhancements to pyparsing. I take this as a further sign that pyparsing is reaching a development/ maturity plateau. With the help of the pyparsing community, there are some compatibility upgrades, and few bug fixes. The major news is compatibility with Python 3 and IronPython 2.0.1. Here is the high-level summary of what's new in pyparsing 1.5.2: - Removed __slots__ declaration on ParseBaseException, for compatibility with IronPython 2.0.1. Raised by David Lawler on the pyparsing wiki, thanks David! - Added pyparsing_py3.py module, so that Python 3 users can use pyparsing by changing their pyparsing import statement to: import pyparsing_py3 Thanks for help from Patrick Laban and his friend Geremy Condra on the pyparsing wiki. - Fixed bug in SkipTo/failOn handling - caught by eagle eye cpennington on the pyparsing wiki! - Fixed second bug in SkipTo when using the ignore constructor argument, reported by Catherine Devlin, thanks! - Fixed obscure bug reported by Eike Welk when using a class as a ParseAction with an errant __getitem__ method. - Simplified exception stack traces when reporting parse exceptions back to caller of parseString or parseFile - thanks to a tip from Peter Otten on comp.lang.python. - Changed behavior of scanString to avoid infinitely looping on expressions that match zero-length strings. Prompted by a question posted by ellisonbg on the wiki. - Enhanced classes that take a list of expressions (And, Or, MatchFirst, and Each) to accept generator expressions also. This can be useful when generating lists of alternative expressions, as in this case, where the user wanted to match any repetitions of '+', '*', '#', or '.', but not mixtures of them (that is, match '+++', but not '+-+'): codes = +*#. format = MatchFirst(Word(c) for c in codes) Based on a problem posed by Denis Spir on the Python tutor list. - Added new example eval_arith.py, which extends the example simpleArith.py to actually evaluate the parsed expressions. Download pyparsing 1.5.2 at http://sourceforge.net/projects/pyparsing/. The pyparsing Wiki is at http://pyparsing.wikispaces.com -- Paul Pyparsing is a pure-Python class library for quickly developing recursive-descent parsers. Parser grammars are assembled directly in the calling Python code, using classes such as Literal, Word, OneOrMore, Optional, etc., combined with operators '+', '|', and '^' for And, MatchFirst, and Or. No separate code-generation or external files are required. Pyparsing can be used in many cases in place of regular expressions, with shorter learning curve and greater readability and maintainability. Pyparsing comes with a number of parsing examples, including: - Hello, World! (English, Korean, Greek, and Spanish(new)) - chemical formulas - configuration file parser - web page URL extractor - 5-function arithmetic expression parser - subset of CORBA IDL - chess portable game notation - simple SQL parser - Mozilla calendar file parser - EBNF parser/compiler - Python value string parser (lists, dicts, tuples, with nesting) (safe alternative to eval) - HTML tag stripper - S-expression parser - macro substitution preprocessor -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Python Training in San Diego (USENIX Technical Conference)
Python Training Opportunities In San Diego at the 2009 USENIX Technical Conference June 14-15, 2009 http://www.usenix.org/events/usenix09/training/index.html I'm pleased to announce three Python tutorial sessions to be presented at the 2009 USENIX Technical Conference in San Diego. The Python Programming Language, June 14, 2009 (All Day) - This tutorial provides a comprehensive tour of the Python programming language and shows how it can be used to solve a variety of practical problems. The tutorial will illustrate important concepts through examples that primarily focus on data analysis, systems programming, and system administration. Introduction to Python Concurrency, June 15, 2009 (Morning) --- A overview of the state of concurrent programming in Python. Topics include threads, message passing, multiprocessing, asynchronous I/O, and coroutines. Python Generator Hacking, June 15, 2009 (Afternoon) --- Generators and generator expressions are among the most useful features of Python. Yet many Python programmers are unsure how to apply them to real-world problems. This tutorial presents practical uses of generators, including processing large data files, handling real-time data sequences, parsing, threads, networking, and distributed computing. More information about these courses and the USENIX Tech Conference is available at: http://www.usenix.org/events/usenix09 Hopefully, I'll see a few people in San Diego! Cheers, Dave -- David Beazley (http://www.dabeaz.com) Author Python Essential Reference -- 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.36 Release
Dear Python users, The Elisa team is happy to announce the release of Elisa Media Center 0.5.36, code-named Surfin' Bird. 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 is a lightweight release, meaning it is pushed through our automatic plugin update system. Additionally a windows installer is available for download on our website. This installer fixes various crashers. As usual, for users running a version of Elisa = 0.5.35, the upgrade to 0.5.36 should be done automatically via the plugin repository. As usual, tarballs are provided for distribution packagers. A complete list of the issues fixed can be found at: http://bugs.launchpad.net/elisa/+milestone/0.5.36 This is also summarised in the (attached) release notes. Installers and sources can be downloaded from http://elisa.fluendo.com/download/ Bug reports and feature requests are welcome at http://bugs.launchpad.net/elisa/+filebug Have a media-centered evening, Olivier, for the Elisa team [1] http://www.gstreamer.net/ [2] https://code.fluendo.com/pigment/trac Elisa 0.5.36 Surfin' Bird === This is Elisa 0.5.36, thirty-sixth release of the 0.5 branch. Bugs fixed since 0.5.35: - 307692: [win32] Exotic characters in username prevent elisa from starting - 333925: Black screen without feedback when requesting to play a stream - 340450: [win32] gstreamer crashes while logging - 233724: Youtube plugin should show most viewed today and top rated today 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: - Anna Wojdel - Bruno Dilly - David McLeod - Florian Boucault - Guillaume Emont - Jesús Corrius - Lionel Martin - Loïc Molinari - Marc Garcia - Maxwell Young - 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
Re: The Python standard library and PEP8
On Monday 20 April 2009 01:48:04 Steven D'Aprano wrote: The problem is, I believe, that people wrongly imagine that there is One True Way of a language being object-oriented, and worse, that the OTW is the way Java does it. (If it were Smalltalk, they'd at least be able to make the argument that Smalltalk invented the perfect OO language and every change since then was corruption.) This is of course nonsense, but many people fall for it. The way I'm used to is the One True Way. As far as str.len versus len(str), apart from saving one character, I don't see any advantage to one over the other. It really depends on what you're used to. It also depends on whether you see the length of a data structure as a property of the data, or the result of an operation (counting) on the data structure. We often fall into the trap of saying such things as the string HAS A length of 42 when what we really mean is if you count the elements of the string we find 42 of them. I don't believe that the relationship between strings and length is a has-a relationship. I believe it is a property requiring a function (counting) to emerge, and therefore under OO principles, length should *not* be an attribute and Java et al are guilty of misuse of OO in making length an attribute. This didn't quite make sense. Methods are abilities an object has. Why shouldn't a string be able to compute its length? If you don't agree, consider an analogy: think about what it means to say that Fred has a height, compared to Fred has a left arm. You can point to Fred's left arm, you can surgically remove it, in principle at least you could surgically attach a left arm to somebody who didn't have one. The relationship between Fred and left arm is most certainly a has-a relationship. But the same isn't true for height: you can't surgically remove Fred's height, and you can't even point to the part of Fred that is his height. The length of a string is like height. As noted above, nothing would stop Fred from having the ability to computeHeight(), though. I guess you could say that what I find silly is that String objects have a number of abilities, which: - are more complicated than retrieving their own length - most likely use len() internally anyway And yet, when asked, it's not able to do something as basic as tell its length. This seems inconsistent to me. Cheers, Emm -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python standard library and PEP8
Allowing for procedural-style programming does not mean that a language does not implement (even imperfectly) an OO paradigm. Allowing is the wrong term here. Python absolutely encourages a straightforward procedural style when appropriate; unlike Java, there is no attempt to force object orientation everywhere. Appealing to Python's object-oriented nature when arguing about design decisions and ignoring the other programming styles it supports is an indicator that you don't really know Python very well. I don't pretend to :) Also, my code sample was itself a trick question. Python has *dynamic* object orientation (just as the blurb says), and square() will work on any object with a __mul__() method (through the ``*`` syntax), just as len() works on any object with a __len__() method. So my code demonstrates the way Python's programming styles interleave with each other (throw in a listcomp to complete the set). This is what Carl Banks was saying below (that getting the length of something was generic operation)... Well, I suppose it sorts of make sense. I had the feeling that Python had been moving from a more procedural kind of language to a more object-oriented one (by having the everything be an object). But I'm beginning the see the logic in having a len() function (as opposed to a design wart). Thank you, Emm -- http://mail.python.org/mailman/listinfo/python-list
iterate to make multiple variables?
Hi, I'm somewhat new to programming and especially to python. Today I was attempting to make a sudoku-solver, and I wanted to put numbers into sets call box1, box2, ... box9, so that I could check new values against the boxes I ended up declaring the boxes like this box1 = set([]) box2 = set([]) .. .. box9 = set([]) Is there a way for me instead to generate these variables (box1 to box9) as empty sets instead of just writing them all out? Some way to iterate and generate them? Sorry if this is confusing, thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: iterate to make multiple variables?
Tairic ala...@gmail.com wrote in message news:95ea7bdf-2ae8-4e5e-a613-37169bb36...@w35g2000prg.googlegroups.com... Hi, I'm somewhat new to programming and especially to python. Today I was attempting to make a sudoku-solver, and I wanted to put numbers into sets call box1, box2, ... box9, so that I could check new values against the boxes I ended up declaring the boxes like this box1 = set([]) box2 = set([]) .. .. box9 = set([]) Is there a way for me instead to generate these variables (box1 to box9) as empty sets instead of just writing them all out? Some way to iterate and generate them? This will generate a list of nine unique, empty sets, box[0] through box[8]: box = [set() for i in range(9)] -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python standard library and PEP8
Also, my code sample was itself a trick question. Python has *dynamic* object orientation (just as the blurb says), and square() will work on any object with a __mul__() method (through the ``*`` syntax), just as len() works on any object with a __len__() method. So my code demonstrates the way Python's programming styles interleave with each other (throw in a listcomp to complete the set). This is what Carl Banks was saying below (that getting the length of something was generic operation)... Well, I suppose it sorts of make sense. I had the feeling that Python had been moving from a more procedural kind of language to a more object-oriented one (by having the everything be an object). But I'm beginning the see the logic in having a len() function (as opposed to a design wart). I don't think Python is moving in any direction that pushes it more towards one paradigm or another; it's moving simply from less-Pythonic to more-Pythonic. Early on in the 2.x series that did include a number of major enhancements which sought to unify the difference between types and classes and this was a win for object-oriented programming, but that isn't at all the general goal. Python has also included in recent releases a number of advantages and tools to support a more functional approach, including the numerous additions to the functools modules and itertools modules and the various capabilities that iterators and generators have brought to the language. The question of, Why is the length of a sequence not a method of sequences? is a very common question. The thread has previously linked to the FAQ, but there's also the effbot page at http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm Python doesn't just allow, or support, but encourages you to address the problems you are faced with in a way which works both for you and for the problem at hand. There's times when object oriented is just not the right answer; times when simple procedural is all you need; and times when a functional approach is better. Python chooses not to make a decision on which is right or wrong; the language is object-oriented in that it supports and encourages you to program in an object oriented fashion if you choose to. Guido basically sees what is the length of x as an operation and not a method of a particular class; true a class can set that behavior as it wishes, but as with several other things determining the length of a thing was seen as a fundamental operation. That's why Python has str(object) instead of calling object.toStr() like you would have to with Java. There's many other examples-- even more recently, as the generator.next() method has become next(generator), for example. To try to pidgeon-hole what's right with Python's design with what you perceive to be The Right Way in OO-Languages is flawed. Python is about a more practical approach to problems then a theoretical purity adhering some design principle; what is Pythonic is not definable in any mathematical or analytical sense by any compsci major skilled in all of the theories of design. Its more a gut feeling, and its goals aren't about Correctness. Its about getting the job done, its about making the job approachable, intutiive and comprehensible, and its about getting back to the job later an easy thing to pick up. Python 3.0 included a number of backwards incompatible changes, but they were all (in theory) done for reasons of benefiting the /usage/ of the language and the /experience/ of the process. Clean is a terribly dirty word when talking of this, really. Why not clean ... you ask -- the answer is: how do YOU define clean, and what do YOU have to do to accomodate clean, and why should everyone else change to be clean in your perspective? Making Python cleaner by making this operation more Object-Orienteded by maing it a method is a highly suspect proposition: why is it cleaner to be more object oriented? In Python terms, clean is defined more as Pythonic -- which is a very complex ideal, admittedly. Its an ideal which says its even OK to have completely different coding styles in the standard library, because its more important to keep consistancy with local code then global policy and its more important to not change something just cuz then it is to change something to provide some real benefit to usage or clarity. Is something.len() really anymore clear then len(something)? To the OO-purist, maybe. But the world is bigger. --S -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python standard library and PEP8
Emmanuel Surleau: On an unrelated note, it would be *really* nice to have a length property on strings. Even Java has that! Once you have written a good amount of Python code you can understand that a len() function, that calls the __len__ method of objects, is better. It allows you to write: sorted(seq, key=len) Instead, if you have a len attribute you need: sorted(seq, key=attrgetter(len)) Or even: sorted(seq, key=lambda x: x.len) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
[False,True] and [True,True] -- [True, True]?????
Is there any obvious reason why [False,True] and [True,True] gives [True, True] Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] -- http://mail.python.org/mailman/listinfo/python-list
Re: Non-secure execution environment
If anyone is interested I end up using rexec kinda class with only difference that i am using native __builtin__ and resetting __import__ hook to and from local r_import implementation before and after I am executing code in my environment. Gennadiy -- http://mail.python.org/mailman/listinfo/python-list
Re: Non-secure execution environment
If anyone is interested I end up using rexec kinda class with only difference that i am using native __builtin__ and resetting __import__ hook to and from local r_import implementation before and after I am executing code in my environment. Gennadiy -- http://mail.python.org/mailman/listinfo/python-list
Re: [False,True] and [True,True] -- [True, True]?????
On Mon, Apr 20, 2009 at 9:03 AM, bdb112 boyd.blackw...@gmail.com wrote: Is there any obvious reason why [False,True] and [True,True] gives [True, True] Well, whether the reason is obvious, I do not know, but the way and seems to be implemented is: X and Y = * X if the boolean value of X is false * Y if the boolean value of X is true In this case, bool([False,True]) = true, so the second element is taken. -- André Engels, andreeng...@gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: and [True,True] -- [True, True]?????
On Apr 20, 2:03 am, bdb112 boyd.blackw...@gmail.com wrote: Is there any obvious reason why [False,True] and [True,True] gives [True, True] Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] X and Y == (Y if X else X) X or Y == (X if X else Y) [False, True] is true, so the and operator returns the second argument. -- http://mail.python.org/mailman/listinfo/python-list
Re: [False,True] and [True,True] -- [True, True]?????
En Mon, 20 Apr 2009 04:03:28 -0300, bdb112 boyd.blackw...@gmail.com escribió: Is there any obvious reason why [False,True] and [True,True] gives [True, True] Yes: short-circuit evaluation. [False,True] and [True,True] is *not* an element-by-element operation, it's a simple expression involving two objects (two lists). A and B means: check the boolean value of A; if it's false, return A. Else, return B. A non-empty list has a boolean value of true, so the second list is returned. If you want an element-wise operation: A = [False,True] B = [True,True] result = [a and b for a,b in zip(A,B)] -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python standard library and PEP8
In message mailman.4178.1240170419.11746.python-l...@python.org, Christian Heimes wrote: Neither Java nor Python are pure object oriented languages. That's like saying the Soviet Union was never a pure communist country, or that the US is not a pure capitalist country. Pure, it seems, can be endlessly redefined to exclude any example you might care to name, that you don't happen to like. In short, it's a meaningless adjective. -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python standard library and PEP8
In message gsg2iv$g5...@panix3.panix.com, Aahz wrote: What kind of OO language allows you to do this: def square(x): return x*x for i in range(10): print square(x) Take out the OO qualifier, and the answer is still none: Traceback (most recent call last): File stdin, line 2, in module NameError: name 'x' is not defined -- http://mail.python.org/mailman/listinfo/python-list
Hello everyone!
I'm a newby here, I love python very much. Is there any Chinese here?-- http://mail.python.org/mailman/listinfo/python-list
Re: Can some1 review my code?
zaheer.ag...@gmail.com wrote: When done all this you might feel it is not necessary to review the code any more, which is then is a good moment to actually request a review :-) I'll be happy to have a look at it though you might consider posting it here, more chance of useful feedback ;-) Great, Thanks a lot I will make sure that I complete what ever you have listed here and then request for a review. Well I understand that refusing to post the code here in the mailing list might annoy people and posting code here will only help it making it more robust and clean. I am just being cautious that I don't break any of the laws at my workplace. I would second what another poster recommended. Post snippets. My experience over the last 8 years is that a short post on a single issue elicits very helpful responses. Also these days there many books on Python; find one that suits your learning style. David Lees -- http://mail.python.org/mailman/listinfo/python-list
PEP 401
Are 19 days that I read this PEP; it's all true? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create an unclosed dialog in wxPython?
On 4月18日, 下午9时40分, 书虫 liangguan...@163.com wrote: In wxPython, after I create a wx.Frame, I want to create a modeless and unclosed dialog. Here is my step: app = wx.PySimpleApp() f = wx.Frame(None, -1, Test) d = wx.Dialog(f, -1, Test Dialog, style = wx.CAPTION) f.Show() d.Show() app.MainLoop() As you see, I create a dialog with wx.CAPTION style. And than, there is no close button in this dialog. It seems unclosed dialog, but in fact, if you enter Alt+F4 in this dialog, it will close. How could I do? Binds the wx.EVT_CLOSE event and ignor it in the handle function. -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python standard library and PEP8
On Mon, 20 Apr 2009 19:18:23 +1200, Lawrence D'Oliveiro wrote: In message gsg2iv$g5...@panix3.panix.com, Aahz wrote: What kind of OO language allows you to do this: def square(x): return x*x for i in range(10): print square(x) Take out the OO qualifier, and the answer is still none: Traceback (most recent call last): File stdin, line 2, in module NameError: name 'x' is not defined I can't replicate that error. Did you forget to initialize x before running the code snippet? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python standard library and PEP8
Steven D'Aprano wrote: On Mon, 20 Apr 2009 19:18:23 +1200, Lawrence D'Oliveiro wrote: In message gsg2iv$g5...@panix3.panix.com, Aahz wrote: What kind of OO language allows you to do this: def square(x): return x*x for i in range(10): print square(x) Take out the OO qualifier, and the answer is still none: Traceback (most recent call last): File stdin, line 2, in module NameError: name 'x' is not defined I can't replicate that error. Did you forget to initialize x before running the code snippet? The code as posted had a typo: 'x' instead of the instended 'i'. -- http://mail.python.org/mailman/listinfo/python-list
Re: QT , Wxwidgets are not just UI framework ?
On Sun, 19 Apr 2009 20:32:23 -0700 (PDT), Old Listener bill.hunt.walnutcr...@gmail.com wrote: On Apr 17, 10:20 am, Phil Thompson p...@riverbankcomputing.com wrote: On Fri, 17 Apr 2009 07:04:40 -0700 (PDT), Deep_Feelings doctore...@gmail.com wrote: On Apr 17, 1:52 pm, Diez B. Roggisch de...@nospam.web.de wrote: Deep_Feelings wrote: qt include many libraries : network , threading,database ..etc while Wxwidgets seem similar but with less scope my question is : does these frameworks replace python's (or any other language for that matter) built-in libraries ? or python does not include that sort of libraries ? Some it includes, others it doesn't. And they come with different features. While python comes with a lot of included batteries, for some things you need a more powerful generator - that's where 3rd-party-libraries come into play. There are plenty of discussions about which GUI-toolkit is the best - google this group. However, mostly people agree that Qt is the most powerful, but often was debunked because of it's licensing. This has changed to the much more liberal LGPL for Qt4.5. Now it might be though that you'd still need to buy a license from Phil Thompson for his excellent PyQt-wrapping - but I'd personally say it's more worth than it actually costs given the power of Qt. Diez thank you considering that wxwidget is open source and free do you think that QT lisencing is worth it ? wxWidgets, Qt and PyQt are all open source and free - just not the same open source license. Phil Can PyQt be used in the Qt Creator IDE? I don't know - ask on the PyQt or Creator mailing lists. Phil -- http://mail.python.org/mailman/listinfo/python-list
Re: Equivalent to C bitmasks and enumerations
Ulrich Eckhardt wrote: [how to handle bitfields and enumerations in Python] Thanks to all that answered. The important lessons I learned: * You can modify classes, other than in C++ where they are statically defined. This allows e.g. adding constants. * __repr__ should provide output suitable as input to the Python interpreter if possible. Very interesting! Uli -- Sator Laser GmbH Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 -- http://mail.python.org/mailman/listinfo/python-list
RE: Keyerror addhandler
Hi Diez, I am using 2.4, could that be the cuase of your issue below. Ideally, I would like to stay with the 2.4 version and based on two tutorials, this was what I came up with Steven Steven Macintyre schrieb: Hi all, I'm wondering if anyone can assist me with this as I am very confused about it now. I am getting the following error; Traceback (most recent call last): File /usr/lib/python2.4/logging/config.py, line 191, in fileConfig logger.addHandler(handlers[hand]) KeyError: 'handler_mylogfileHandler' For me, that fails with mac-dir:tmp deets$ python2.5 test.py Traceback (most recent call last): File test.py, line 6, in module logging.config.fileConfig(logging.conf) File /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/logging/con fig.py, line 84, in fileConfig handlers = _install_handlers(cp, formatters) File /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/logging/con fig.py, line 149, in _install_handlers klass = eval(klass, vars(logging)) File string, line 1, in module NameError: name 'RotatingFileHandler' is not defined mac-dir:tmp deets$ Diez -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
best void return of a member function
Hi, I'm writing a native language binding for a library. http://libmsgque.sourceforge.net/ Every native method called by PYTHON have to return a PyObject* even if the function itself does not return anything. I have 2 possibilities for return a PyObject* 1. the first argument of the method function - return self; 2. an entire new empty object - return Py_BuildValue(); Question: what is the best return statement for a void function ? P.S: NULL is not allowed, because NULL is returned in the case of an error mfg Andreas Otto -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a programming language that is combination ofPythonandBasic?
Chris Jones cjns1...@gmail.com wrote: Intellectually, assembler programming is the less demanding since its level of abstraction does not go any further than mapping a few binary numbers to a small set of usually well-chosen mnemonics. This is the surface complexity - it is true that when you write an assembler statement, you know exactly *what* it is going to do. The *why*, however, is not always as obvious, as it entails keeping far more *registers and memory locations* alive in your mind as you go - and the temptation is great, for efficiency's sake, to let a series of calls leave their answers *in place*, ready for the next call to use: call this jc error_handling call that jc error_handling call thenextthing jc error_handling ... This kind of thing is in a way worse than spaghetti, and it is about the hardest thing to understand that I know of. It is also fragile, as you are never sure if you change something, no matter how well documented your individual routines are, what the effect of a change somewhere will have somewhere further down the line, as the parameters are not explicitly named before the calls. I find higher level languages a lot easier to read because of this. You can do the same kind of thing in Python, using globals, and if there are enough of them, it will be just as hard to follow. Unless it features a powerful macro-language that lets the apprentice create his own high-level patois on top of the assembler, that is. This is the fun part of assembly programming - and here again, one has to exercise restraint, or the language becomes baroque. Used correctly, however, it allows you to generate a lot of required boilerplate with very few keystrokes. It is also very useful to create application specific virtual machines with specialised *instruction sets* which can make solving some problems a lot easier. - and that is a level of abstraction that is in a sense orthogonal to the levels of abstraction brought to the party by a high level language that has a simple von Neumann machine as it's base assumption. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: and [True,True] -- [True, True]?????
THanks Gabriel, Now I know about the zip function. Your explanation of Boolean ops on lists was clear. It leads to some intriguing results: bool([False]) -- True I wonder if python 3 changes any of this? A and B means: check the boolean value of A; if it's false, return A. Else, return B. A non-empty list has a boolean value of true, so the second list is returned. If you want an element-wise operation: A = [False,True] B = [True,True] result = [a and b for a,b in zip(A,B)] -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 401
On Sun, 19 Apr 2009 11:02:35 -0700, alessiogiovanni.baroni wrote: Are 19 days that I read this PEP; it's all true? For the benefit of people who are not aware of the tradition of April Fools: http://en.wikipedia.org/wiki/April_fool Look at the date of the PEP and the status. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 401
On Mon, Apr 20, 2009 at 1:22 AM, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: On Sun, 19 Apr 2009 11:02:35 -0700, alessiogiovanni.baroni wrote: Are 19 days that I read this PEP; it's all true? For the benefit of people who are not aware of the tradition of April Fools: http://en.wikipedia.org/wiki/April_fool Look at the date of the PEP and the status. Heck, just look at its number and mentally insert one slash or dash. Cheers, Chris -- I have a blog: http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python standard library and PEP8
On Mon, 20 Apr 2009 03:44:59 -0400, Terry Reedy wrote: Steven D'Aprano wrote: On Mon, 20 Apr 2009 19:18:23 +1200, Lawrence D'Oliveiro wrote: In message gsg2iv$g5...@panix3.panix.com, Aahz wrote: What kind of OO language allows you to do this: def square(x): return x*x for i in range(10): print square(x) Take out the OO qualifier, and the answer is still none: Traceback (most recent call last): File stdin, line 2, in module NameError: name 'x' is not defined I can't replicate that error. Did you forget to initialize x before running the code snippet? The code as posted had a typo: 'x' instead of the instended 'i'. Well duh, that's obvious :) It's such an obvious typo that I wonder what point Lawrence thought he was making to show that it wouldn't run as given. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python standard library and PEP8
On Mon, 20 Apr 2009 19:15:51 +1200, Lawrence D'Oliveiro wrote: In message mailman.4178.1240170419.11746.python-l...@python.org, Christian Heimes wrote: Neither Java nor Python are pure object oriented languages. That's like saying the Soviet Union was never a pure communist country, or that the US is not a pure capitalist country. Pure, it seems, can be endlessly redefined to exclude any example you might care to name, that you don't happen to like. In short, it's a meaningless adjective. Not in the least. There's an accepted definition for objected oriented programming language: a language which provides objects, which are constructs encapsulating both data and routines to operate on that data in a single item. A pure OO language is clearly a language where *everything* is performed using OO techniques on objects. That's in contrast to impure OO languages like Java, which exposes ints and floats as machine primitives, and Python, which allows and encourages non-OO techniques. Purity in object-orientivity is not necessarily a good thing. In fact, we don't even need to know what a pure OO language is to know that Python isn't one. All we need is one feature that all reasonable people agree isn't OO, and we know that Python isn't pure OO. Since Python includes such functional tools as map() and reduce(), and there is no such collection.map() method, we know that Python isn't purely OO. Waiting-for-somebody-to-claim-that-map(alist)-is-object-oriented-ly y'rs, -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: and [True,True] -- [True, True]?????
bdb112 wrote: Your explanation of Boolean ops on lists was clear. It leads to some intriguing results: bool([False]) -- True I wonder if python 3 changes any of this? No. Tests like if items: ... to verify that items is a non-empty list are a widespread idiom in Python. They rely on the behaviour you observe. Peter -- http://mail.python.org/mailman/listinfo/python-list
RE: Keyerror addhandler
Steven Macintyre wrote: Please don't top-post. [Diez B. Roggisch] For me, that fails with NameError: name 'RotatingFileHandler' is not defined [Steven Macintyre] I am using 2.4, could that be the cuase of your issue below. Ideally, I would like to stay with the 2.4 version and based on two tutorials, this was what I came up with It looks like 2.5 has the better error message, but the actual problem is the same for both versions. Try changing mylogfileHandler's class to [handler_mylogfileHandler] class=handlers.RotatingFileHandler Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: please include python26_d.lib in the installer
On 31 mrt, 22:53, Carl Banks pavlovevide...@gmail.com wrote: On Mar 31, 12:50 pm, Compie joh...@gmail.com wrote: On 27 mrt, 17:01, Carl Banks pavlovevide...@gmail.com wrote: OTOH, it's possible that SWIG and Python just happen to use the same macro to indicate debugging mode. So I think you raise a valid point that this can be problematic. Perhaps something like _Py_DEBUG should be used instead. This would be a good solution IMHO. I'm not the only one facing this problem. The internet is full of people looking for this file...http://www.google.com/search?q=python25_d.lib+error+cannot _DEBUG is automatically defined by Visual Studio when you build the Debug version of a project.http://msdn.microsoft.com/en-us/library/0b98s6w8.aspx So I'm proposing: please use _PYTHON_DEBUG for this purpose. Would this cause any problems? Go to bugs.python.org and file a bug report with the conflict it is causing you. (Well, first, make sure no one else has reported it.) I advise you to stress the downfalls of the current approach in a professional, respectful manner. You have been coming off as slightly whiny in this thread, and that'll hurt your chances of getting such a change approved. In particular, don't ask for anything, or ask why it was implemented that way; just report the issue and suggest a fix. I suspect they used _DEBUG deliberately. I disagree with that: a generic symbol like _DEBUG should be avoided in general, and should really be avoided when it entails a change in interface. Carl Banks Yes you are right, whining here won't help, I will file a bug report. But I really needed the discussion here before I could do that. I didn't know all the pros and cons of the current approach. I was just reporting a problem that I (and many others) have with pyconfig.h and Debug mode. But I do recognize that my current approach (how I reported this problem) is not the most effective one. Thanks for the tip. Johan. -- http://mail.python.org/mailman/listinfo/python-list
Re: and [True,True] -- [True, True]?????
Peter Otten wrote: bdb112 wrote: Your explanation of Boolean ops on lists was clear. It leads to some intriguing results: bool([False]) -- True I wonder if python 3 changes any of this? No. Tests like if items: ... to verify that items is a non-empty list are a widespread idiom in Python. They rely on the behaviour you observe. Are they widespread? I haven't noticed, yet. I prefer to write it explicitly: if len(lst) 0: ... if item is None: ... etc. -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python standard library and PEP8
On Mon, 20 Apr 2009 08:05:01 +0200, Emmanuel Surleau wrote: On Monday 20 April 2009 01:48:04 Steven D'Aprano wrote: It also depends on whether you see the length of a data structure as a property of the data, or the result of an operation (counting) on the data structure. We often fall into the trap of saying such things as the string HAS A length of 42 when what we really mean is if you count the elements of the string we find 42 of them. I don't believe that the relationship between strings and length is a has-a relationship. I believe it is a property requiring a function (counting) to emerge, and therefore under OO principles, length should *not* be an attribute and Java et al are guilty of misuse of OO in making length an attribute. This didn't quite make sense. Methods are abilities an object has. Why shouldn't a string be able to compute its length? Nothing. I'm not talking about methods, I'm talking about making length a property (or attribute if you prefer). I must admit a mistake: Java does not treat the length of a string as an attribute, but uses a callable method, String.length(), so I withdraw my accusation of misuse of OO principles. [...] As noted above, nothing would stop Fred from having the ability to computeHeight(), though. I guess you could say that what I find silly is that String objects have a number of abilities, which: - are more complicated than retrieving their own length - most likely use len() internally anyway Advantages of calling a length method: - Consistency with other methods. - Makes it easy to discover by introspection. Disadvantages of calling a length method: - In Python for built-in lists, tuples and strings, it requires at least one extra attribute lookup that the len() function doesn't need. (Java can avoid paying that cost at runtime by doing it at compile time -- this isn't available to Python.) - It makes it more difficult to write functional code such as this: map(len, [seq1, seq2, seq3]) where the various seq* are arbitrary sequences, not necessarily just strings. (Functional in the sense of functional-programming, not in the sense of it works.) - It makes it harder to intercept calls to len() for debugging. I can do this: def len(obj): print called len with arg %r % obj # or log it somewhere return __builtins__.len(obj) and have all the calls to len go through that, without even knowing what type of object is being called. But note that because len() in turn calls obj.__len__ (unless obj is a known built-in like str), you keep all the advantages of OO methods like sub-classing, without any of the disadvantages. And yet, when asked, it's not able to do something as basic as tell its length. This seems inconsistent to me. Well, you can do this: s = abc s.__len__() 3 but if you do it in public, be prepared to have other Python programmers laugh at you. It's just a stylistic difference, it's not a functional difference. Even if there is a genuine, objective advantage to one approach over the other (and I believe that advantage goes to len() as a function), it's quite small and it won't really make that big a difference. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a programming language that is combination of Python and Basic?
Michael Torrie wrote: http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html Somebody better tell the Linux kernel developers about that! They apparently haven't read that yet. Better tell CPU makers too. In assembly it's all gotos. I'm sure you are joking. Using goto for error handling in C is a reasonable practice, Avoiding that for the sake of it would be like, say, avoiding raise in python because a procedure should only have one exit point. -- http://mail.python.org/mailman/listinfo/python-list
Re: best void return of a member function
Andreas Otto wrote: well propable found the answer by my own ... Py_RETURN_NONE should be the best -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 401
On Mon, 20 Apr 2009 01:30:44 -0700, Chris Rebert wrote: Look at the date of the PEP and the status. Heck, just look at its number and mentally insert one slash or dash. Fourth of January? What's special about 4th of Jan? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 401
On Mon, Apr 20, 2009 at 2:28 AM, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: On Mon, 20 Apr 2009 01:30:44 -0700, Chris Rebert wrote: Look at the date of the PEP and the status. Heck, just look at its number and mentally insert one slash or dash. Fourth of January? What's special about 4th of Jan? Curse you L10n! Cheers, Chris -- I have a blog: http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: compiler package vs parser
Kay Schluehr wrote: I realize that I probably ought to be trying this out with the newer ast stuff, but currently I am supporting code back to 2.3 and there's not much hope of doing it right there without using the compiler package. You might consider using the *builtin* parser module and forget about the compiler package if it is broken ( I take your word that it is ) or modern ast representations which aren't really necessary for Python anyway. import parser tree = parser.suite(def foo():\n print 42}\n) code = tree.compile() exec code foo() 42 This is also not 100% reliable ( at least not for all statements in all Python versions ) but it uses the internal parser/compiler and not a standard library compiler package that might not be that well maintained. ... thinking about it I just made the wrong decision back in 2004; we observed a semantic change caused by the new scoping rules and tried to fix using the wrong model; back then we were probably supporting 2.0 as well so the parser module probably wasn't available everywhere anyway; even today the ast stuff isn't available in 2.4. I prefer the ast approach as preppy is effectively indentation free which makes the tree harder to synthesize for the parser tree. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: and [True,True] -- [True, True]?????
On Mon, Apr 20, 2009 at 1:54 AM, Gerhard Häring g...@ghaering.de wrote: Peter Otten wrote: bdb112 wrote: Your explanation of Boolean ops on lists was clear. It leads to some intriguing results: bool([False]) -- True I wonder if python 3 changes any of this? No. Tests like if items: ... to verify that items is a non-empty list are a widespread idiom in Python. They rely on the behaviour you observe. Are they widespread? I haven't noticed, yet. I prefer to write it explicitly: if len(lst) 0: Nope, that's not idiomatic. The simpler `if lst:` version is indeed widespread. ... if item is None: That's pretty common and accepted; comparison to None is something of a special case. Cheers, Chris -- I have a blog: http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
RE: Keyerror addhandler
Hi Peter, It looks like 2.5 has the better error message, but the actual problem is the same for both versions. Try changing mylogfileHandler's class to [handler_mylogfileHandler] class=handlers.RotatingFileHandler Many thanks, this worked for me! Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: and [True,True] -- [True, True]?????
Gerhard Häring wrote: Peter Otten wrote: bdb112 wrote: Your explanation of Boolean ops on lists was clear. It leads to some intriguing results: bool([False]) -- True I wonder if python 3 changes any of this? No. Tests like if items: ... to verify that items is a non-empty list are a widespread idiom in Python. They rely on the behaviour you observe. Are they widespread? I haven't noticed, yet. That is my impression. I prefer to write it explicitly: if len(lst) 0: ... Using google codesearch I get matches search expression ca. 1000 lang:python if items: 216 lang:python if len(items) 0: This could of course mean that people who like 'items' as a list name also like the 'if items:...' idiom or 'items' is a popular name for boolean values or the search result is spammed by a gazillion zope versions... Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a programming language that is combination of Python and Basic?
baykus wrote: those lines as numbered steps or numbered bricks that are sitting on eachother but I see them as timelines or like filmstrips. Anyways it sounds like such a toy programming language does not exists except Arnaud surprisingly efficient code. and I will search my dream somewhere else :) Actually, your dreams have already been implemented in Python. As an april fool's joke. Really. It works, but is so silly and depraved that I'm not going to provide a link. -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 401
Chris Rebert wrote: On Mon, Apr 20, 2009 at 1:22 AM, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: On Sun, 19 Apr 2009 11:02:35 -0700, alessiogiovanni.baroni wrote: Are 19 days that I read this PEP; it's all true? For the benefit of people who are not aware of the tradition of April Fools: http://en.wikipedia.org/wiki/April_fool Look at the date of the PEP and the status. Heck, just look at its number and mentally insert one slash or dash. My first thought was that the PEP number was referring to HTTP 401, i.e. unauthorized. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: and [True,True] -- [True, True]?????
On Mon, 20 Apr 2009 10:54:40 +0200, Gerhard Häring wrote: Peter Otten wrote: bdb112 wrote: Your explanation of Boolean ops on lists was clear. It leads to some intriguing results: bool([False]) -- True I wonder if python 3 changes any of this? No. Tests like if items: ... to verify that items is a non-empty list are a widespread idiom in Python. They rely on the behaviour you observe. Are they widespread? I haven't noticed, yet. I prefer to write it explicitly: if len(lst) 0: Do you also count the length of a list explicitly? n = 0 for item in lst: n += 1 if n 0: ... No? Of course you don't. You understand that lists know how to calculate their own length, and you just ask the list for its length. Great. Well, lists also know whether or not they are empty, without needing to concern yourself with the definition of empty. if lst: # not empty else: # empty All Python objects have an understanding of empty or not empty, and the only time I've seen it cause problems is with iterators, because you can't tell if an iterator is empty until you actually try to access a value. if item is None: ... That's a completely different test. That's testing whether item is the specific singleton None. It is very different from testing bool(item). -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: best void return of a member function
Andreas Otto wrote: well propable found the answer by my own ... Py_RETURN_NONE should be the best You have found the correct answer to your query. :) Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Create standalone Windows program with simple graphics?
I'd like to program and compile a simple graphics program (showing something like a chess board, some numbers and buttons, mouse support) ... 2d or 3d graphics? You could start by looking at pygame and pyopengl. 2D Graphics. ... and provide it as a standalone binary for Windows users. py2exe, althought this is a bit of a PITA. I'd get your game working first and worry about this aspect of the project last. Luckily its more of a simulations - not meant to be nice looking or comfortable. I only need bitmaps positioned like a chess board and also some mouse support. Hope it will work :) -- http://mail.python.org/mailman/listinfo/python-list
Re: best void return of a member function
Andreas Otto writes: I'm writing a native language binding for a library. http://libmsgque.sourceforge.net/ Every native method called by PYTHON have to return a PyObject* even if the function itself does not return anything. [...] Question: what is the best return statement for a void function ? Hmmm, this sounds like your goal is to write an exact 1:1 wrapper of the C library API (for which there are tools like SWIGfriends). If the library happens to have a rather unusual, close-to object oriented, high-level C API, that might work. Otherwise, you might want to try to wrap it in a more Pythonic lookfeel style, that wraps operations and use-cases rather than plain functions. That should make it easier to hide things like memory allocation and other C implementation details from users, and will generally increase the performance of your binding, as it will require less calls for larger operations in C space. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: best void return of a member function
Stefan Behnel wrote: you might want to try to wrap it in a more Pythonic lookfeel style, that wraps operations and use-cases rather than plain functions. That should make it easier to hide things like memory allocation and other C implementation details from users, and will generally increase the performance of your binding, as it will require less calls for larger operations in C space. Here is an example from your web page: Sending data is a sequence of commands to prepare a data-package and one command to send this package. // get the send object from the msgque object struct MqSendS * const send = msgque-send; // init the data-package MqSendSTART (send); // fill the data-package with data MqSendI (send, myInteger); MqSendC (send, myString); // send the data-package to the server MqSendEND (send, IDNT, NULL); A first thought would be a class Connection and a method send_package that takes an arbitrary number of positional arguments, such as connection = some_source.connect() connection.send_package(my_int, myString, end_id=IDNT) In case you do not know the required data type packing (which is explicit in the C example), you can either wrap the types in some kind of typing construct (which might degrade performance, unless you know that you do not need it in most cases), or define message packing formats in advance in some way, e.g. similar to Python's array module. Just an idea. Since you appear to be the main author of that library, I assume that you know best how to make it usable. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a programming language that is combination of Python and Basic?
2009/4/20 Steven D'Aprano st...@remove-this-cybersource.com.au: Sheesh. Talk about cherry-picking data. Go read my post in it's entirety, instead of quoting mining out of context. If you still think I'm unaware of the difference between unstructured GOTOs and structured jumps, or that I'm defending unstructured GOTOs, then you might have something useful to contribute. I wasn't cherry picking data, and I did read the entire post. However, looking back through the message base I see that exactly the same text appears in another posting by you, and the /other/ post makes it clear that you know the difference. Sorry for the confusion. -- Tim Rowe -- http://mail.python.org/mailman/listinfo/python-list
Re: best void return of a member function
Stefan Behnel wrote: define message packing formats in advance in some way, e.g. similar to Python's array module. I (obviously ;) meant the format identifiers in the struct module here. http://docs.python.org/library/struct.html Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: any(), all() and empty iterable
On 2009-04-15, John O'Hagan m...@johnohagan.com wrote: On Tue, 14 Apr 2009, Mark Dickinson wrote: On Apr 14, 7:21 pm, Luis Alberto Zarrabeitia Gomez ky...@uh.cu wrote: It's more than that. Python's following the rules here. Maybe it could be documented better, for those without a background in logic/discrete mathematics, but not changed. Agreed. I'd like to guess that in 93.7% of cases, when a programmer has used all(seq) without having thought in advance about what the right thing to do is when seq is empty, the current behaviour is already the right one. I tried to test this hypothesis, but a Google code search for uses of all() turned up very little besides definitions. For example: if all(t.already_filed() for t in my_tax_forms): go_to_bed_happy() else: file_for_extension() But what about this: if all(evidence): suspect_is_guilty else: suspect_is_innocent even if the evidence is not empty, the above wouldn't be a good test, because you need enough evidence en enough is not implied by all even if all is more than nothing. -- Antoon. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a programming language that is combination of Python and Basic?
When I was at Data General, writing C (and a little C++), we had a set of internal coding conventions that mandated a single return point for a function. Goto's were used during error checks to branch to the function exit; something like this: int frodo() { int rval = 0; if (bilbo() != 0) { rval = -1; goto leave; } if (gandalf() != 0) { rval = -1; goto leave; } /* lot's of code here */ leave: return rval; } Made sense to me. -- david -- http://mail.python.org/mailman/listinfo/python-list
ANN: pyparsing 1.5.2 released!
Well, it has been about 6 months since the release of pyparsing 1.5.1, and there have been no new functional enhancements to pyparsing. I take this as a further sign that pyparsing is reaching a development/ maturity plateau. With the help of the pyparsing community, there are some compatibility upgrades, and few bug fixes. The major news is compatibility with Python 3 and IronPython 2.0.1. Here is the high-level summary of what's new in pyparsing 1.5.2: - Removed __slots__ declaration on ParseBaseException, for compatibility with IronPython 2.0.1. Raised by David Lawler on the pyparsing wiki, thanks David! - Added pyparsing_py3.py module, so that Python 3 users can use pyparsing by changing their pyparsing import statement to: import pyparsing_py3 Thanks for help from Patrick Laban and his friend Geremy Condra on the pyparsing wiki. - Fixed bug in SkipTo/failOn handling - caught by eagle eye cpennington on the pyparsing wiki! - Fixed second bug in SkipTo when using the ignore constructor argument, reported by Catherine Devlin, thanks! - Fixed obscure bug reported by Eike Welk when using a class as a ParseAction with an errant __getitem__ method. - Simplified exception stack traces when reporting parse exceptions back to caller of parseString or parseFile - thanks to a tip from Peter Otten on comp.lang.python. - Changed behavior of scanString to avoid infinitely looping on expressions that match zero-length strings. Prompted by a question posted by ellisonbg on the wiki. - Enhanced classes that take a list of expressions (And, Or, MatchFirst, and Each) to accept generator expressions also. This can be useful when generating lists of alternative expressions, as in this case, where the user wanted to match any repetitions of '+', '*', '#', or '.', but not mixtures of them (that is, match '+++', but not '+-+'): codes = +*#. format = MatchFirst(Word(c) for c in codes) Based on a problem posed by Denis Spir on the Python tutor list. - Added new example eval_arith.py, which extends the example simpleArith.py to actually evaluate the parsed expressions. Download pyparsing 1.5.2 at http://sourceforge.net/projects/pyparsing/. The pyparsing Wiki is at http://pyparsing.wikispaces.com -- Paul Pyparsing is a pure-Python class library for quickly developing recursive-descent parsers. Parser grammars are assembled directly in the calling Python code, using classes such as Literal, Word, OneOrMore, Optional, etc., combined with operators '+', '|', and '^' for And, MatchFirst, and Or. No separate code-generation or external files are required. Pyparsing can be used in many cases in place of regular expressions, with shorter learning curve and greater readability and maintainability. Pyparsing comes with a number of parsing examples, including: - Hello, World! (English, Korean, Greek, and Spanish(new)) - chemical formulas - configuration file parser - web page URL extractor - 5-function arithmetic expression parser - subset of CORBA IDL - chess portable game notation - simple SQL parser - Mozilla calendar file parser - EBNF parser/compiler - Python value string parser (lists, dicts, tuples, with nesting) (safe alternative to eval) - HTML tag stripper - S-expression parser - macro substitution preprocessor -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python standard library and PEP8
In article pan.2009.04.20.08.31...@remove.this.cybersource.com.au, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: On Mon, 20 Apr 2009 03:44:59 -0400, Terry Reedy wrote: Steven D'Aprano wrote: On Mon, 20 Apr 2009 19:18:23 +1200, Lawrence D'Oliveiro wrote: In message gsg2iv$g5...@panix3.panix.com, Aahz wrote: What kind of OO language allows you to do this: def square(x): return x*x for i in range(10): print square(x) Take out the OO qualifier, and the answer is still none: Traceback (most recent call last): File stdin, line 2, in module NameError: name 'x' is not defined I can't replicate that error. Did you forget to initialize x before running the code snippet? The code as posted had a typo: 'x' instead of the instended 'i'. Well duh, that's obvious :) It's such an obvious typo that I wonder what point Lawrence thought he was making to show that it wouldn't run as given. It's called humor. -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ If you think it's expensive to hire a professional to do the job, wait until you hire an amateur. --Red Adair -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP 401
On 20 Apr, 10:22, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: On Sun, 19 Apr 2009 11:02:35 -0700, alessiogiovanni.baroni wrote: Are 19 days that I read this PEP; it's all true? For the benefit of people who are not aware of the tradition of April Fools: http://en.wikipedia.org/wiki/April_fool Look at the date of the PEP and the status. -- Steven Yes, yes, I know it; in Italy its name is pesce d'aprile (April's fish) (we aren't so out of the world ); I haven't read simply the status . Hi to all! -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python standard library and PEP8
Steven D'Aprano wrote: ... There's an accepted definition for objected oriented programming language: a language which provides objects, which are constructs encapsulating both data and routines to operate on that data in a single item. Says you. Roger King wrote a book entitled My Cat is Object-Oriented. His basic premise is that, while everyone understands what you mean when you say something is object-oriented, everyone's understanding is different. --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python standard library and PEP8
On Apr 19, 6:01 pm, Martin P. Hellwig Besides, calling Python Object-Orientated is a bit of an insult :-). I would say that Python is Ego-Orientated, it allows me to do what I want. +1 QOTW -- http://mail.python.org/mailman/listinfo/python-list
when can i expect libraries and third party tools to be updated for python 3 ?
every one is telling dont go with python 3 , 3rd party tools and libraries have no compitability with python 3 so from previous experience : when can i expect libraries and third party tools to be updated for python 3 ? (especially libraries ) -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a programming language that is combination of Python and Basic?
2009/4/20 david youngde...@gmail.com: When I was at Data General, writing C (and a little C++), we had a set of internal coding conventions that mandated a single return point for a function. How long ago was that? Or, more relevant, how old was the rule? Or how long earlier had the person who wrote the rule learned their craft? One reason for mandating single exit points was that early flow graph reducers couldn't handle them, but, because of the GOTO equivalents that you give, graphs with multiple exit points /are/ reducible without the exponential blowup that node splitting can cause, so they've been able to handle multiple exits for many years. Of course, your code is equivalent to: int frodo() { int rval = 0; if (bilbo() != 0) rval = -1 else { if (gandalf() != 0) rval = -1 else { /* lots of code here */ } } return rval; } with not a GOTO in sight, and to my mind much clearer logic. If the nesting meant that the indentation was marching off the side of the page I'd refactor the lots of code here into an inline helper function. And provided bilbo() and gandalf() don't have side effects, I'd probably rewrite it as: int frodo() { int rval = 0; if ((bilbo() == 0) || (gandalf() == 0) { /* lot's of code here */ } else rval = -1; return rval; } I'd be inclined to do it that way even if multiple exits were allowed; it just seems so much clearer. -- Tim Rowe -- http://mail.python.org/mailman/listinfo/python-list
Re: when can i expect libraries and third party tools to be updated for python 3 ?
On 20 Apr, 15:47, Deep_Feelings doctore...@gmail.com wrote: every one is telling dont go with python 3 , 3rd party tools and libraries have no compitability with python 3 so from previous experience : when can i expect libraries and third party tools to be updated for python 3 ? (especially libraries ) When the authors of a every library wants update to 3 :-D. -- http://mail.python.org/mailman/listinfo/python-list
How save clipboard data as bmp file
Hi, I am trying to save my clipboard data (format is CF_ENHMETAFILE) as BitMap file (.BMP). Can any on suggest how to do this. Thanks Regards, Gopal -- http://mail.python.org/mailman/listinfo/python-list
Re: when can i expect libraries and third party tools to be updated for python 3 ?
alessiogiovanni.baroni wrote: On 20 Apr, 15:47, Deep_Feelings wrote: every one is telling dont go with python 3 , 3rd party tools and libraries have no compitability with python 3 so from previous experience : when can i expect libraries and third party tools to be updated for python 3 ? (especially libraries ) When the authors of a every library wants update to 3 :-D. Yes, that is the correct answer. From what I read, I would say that in most projects, work or at least discussion has started regarding Py3 compatibility, but it's not always trivial to get there, so (wo)manpower will often be the limiting factor. This is specifically a problem in C extensions, where running the 2to3 tool is not an option and adding a 'b' in selected places won't do the job. Note, BTW, that you do not have to wait for *all* Python libraries to be ported. Just check when the libraries you require or want to use get ported (or ask the authors or the development communities), and try a switch when it looks like all you need is there. ... or give a hand to the projects you need, if you don't want to sit and wait. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Help improve program for parsing simple rules
On Apr 17, 5:32 pm, Paul McGuire pt...@austin.rr.com wrote: On Apr 17, 2:40 pm, prueba...@latinmail.com wrote: On Apr 17, 11:26 am, Paul McGuire pt...@austin.rr.com wrote: On Apr 16, 10:57 am, prueba...@latinmail.com wrote: Another interesting task for those that are looking for some interesting problem: I inherited some rule system that checks for programmers program outputs that to be ported: given some simple rules and the values it has to determine if the program is still working correctly and give the details of what the values are. If you have a better idea of how to do this kind of parsing please chime in. I am using tokenize but that might be more complex than it needs to be. This is what I have come up so far: I've been meaning to expand on pyparsing's simpleArith.py example for a while, to include the evaluation of the parsed tokens. Here is the online version,http://pyparsing.wikispaces.com/file/view/eval_arith.py, it will be included in version 1.5.2 (coming shortly). I took the liberty of including your rule set as a list of embedded test cases. -- Paul That is fine with me. I don't know how feasible it is for me to use pyparsing for this project considering I don't have admin access on the box that is eventually going to run this. To add insult to injury Python is in the version 2-3 transition (I really would like to push the admins to install 3.1 by the end of the year before the amount of code written by us gets any bigger) meaning that any third party library is an additional burden on the future upgrade. I can't remember if pyparsing is pure Python. If it is I might be able to include it alongside my code if it is not too big.- Hide quoted text - - Show quoted text - It *is* pure Python, and consists of a single source file for the very purpose of ease-of-inclusion. A number of projects include their own versions of pyparsing for version compatibility management, matplotlib is one that comes to mind. The upcoming version 1.5.2 download includes a pyparsing_py3.py file for Python 3 compatibility, I should have that ready for users to download *VERY SOON NOW*! -- Paul Thanks, I will consider it. I have to admit that although it looks like it is a very good solution, it is also longer and more complex than my current code. Having to explicitly define standard python evaluation and semantics is a bit overkill. -- http://mail.python.org/mailman/listinfo/python-list
Re: any(), all() and empty iterable
Raymond Hettinger pyt...@rcn.com writes: FWIW, I wrote the docs. The pure python forms were put in as an integral part of the documentation. The first sentence of prose was not meant to stand alone. It is a lead-in to the code which makes explicit the short-circuiting behavior and the behavior when the input is empty. Someone else seems to have written What's new in Python 2.5 documention which states: Two new built-in functions, any() and all(), evaluate whether an iterator contains any true or false values. any() returns True if any value returned by the iterator is true; otherwise it will return False. all() returns True only if all of the values returned by the iterator evaluate as true. This description of all() doesn't seem to be correct. I will probably leave the lead-in sentence as-is but may add another sentence specifically covering the case for an empty iterable. Does this change cover the documentation returned by help(all) and help(any)? Jani Hakala -- http://mail.python.org/mailman/listinfo/python-list
Re: best void return of a member function
Stefan Behnel wrote: Andreas Otto writes: I'm writing a native language binding for a library. http://libmsgque.sourceforge.net/ Every native method called by PYTHON have to return a PyObject* even if the function itself does not return anything. [...] Question: what is the best return statement for a void function ? Hmmm, this sounds like your goal is to write an exact 1:1 wrapper of the C library API (for which there are tools like SWIGfriends). If the library happens to have a rather unusual, close-to object oriented, high-level C API, that might work. Otherwise, you might want to try to wrap it in a more Pythonic lookfeel style, that wraps operations and use-cases rather than plain functions. That should make it easier to hide things like memory allocation and other C implementation details from users, and will generally increase the performance of your binding, as it will require less calls for larger operations in C space. Stefan Thanks for your help .. I'm almost finished ... it took me ~1week from a non Python developer to: 1. download, install python 2. learn how to use python, syntax, class, objects, protocol, ... 3. learn how to use the native interface, ~hundreds of C functions 4. finally create a project add my native code, compile, build ... test - I just add one extra type I call them PyMqS_type all the special tools are not necessary because if you wrote one language interface you can write every language interface - the tasks are allways the same... just the language-specific-names are changing mfg Andreas Otto -- http://mail.python.org/mailman/listinfo/python-list
Re: when can i expect libraries and third party tools to be updated for python 3 ?
On Apr 20, 9:47 am, Deep_Feelings doctore...@gmail.com wrote: every one is telling dont go with python 3 , 3rd party tools and libraries have no compitability with python 3 so from previous experience : when can i expect libraries and third party tools to be updated for python 3 ? (especially libraries ) I predict: one year. (THIS PREDICTION IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE PREDICTION OR THE USE OR OTHER DEALINGS IN THE PREDICTION.) :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: when can i expect libraries and third party tools to be updated for python 3 ?
Deep_Feelings wrote: every one is telling dont go with python 3 , 3rd party tools and libraries have no compitability with python 3 so from previous experience : when can i expect libraries and third party tools to be updated for python 3 ? (especially libraries ) The problem is: there is no previous experience. At least not in Python-land. Despite its major number, Python 2.0 was not disruptive. -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list
Re: How save clipboard data as bmp file
gopal mishra wrote: Hi, I am trying to save my clipboard data (format is CF_ENHMETAFILE) as BitMap file (.BMP). Can any on suggest how to do this. Sure. Open Paint press ctrl-v and the save as BMP. Regards Tino smime.p7s Description: S/MIME Cryptographic Signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there a programming language that is combination of Python and Basic?
I was at DG in the early nineties. A lot of very smart people devised some of these conventions, from hard-earned experience in the kernel and system-level software. I've never been one for fascist-rules documents, but in DG's case many of the rules made good sense. I'm not advocating one approach over another; just wanted to show an example where some careful thought went into the use of goto. -- david -- http://mail.python.org/mailman/listinfo/python-list
Re: How save clipboard data as bmp file
gopal mishra wrote: I am trying to save my clipboard data (format is CF_ENHMETAFILE) as BitMap file (.BMP). Have a look at PIL's ImageGrab module: http://www.pythonware.com/library/pil/handbook/imagegrab.htm I'm not sure if the current version supports metafiles, but it's easy enough to try. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: when can i expect libraries and third party tools to be updated for python 3 ?
(Is there hope that you could set your ‘From’ field using your real name so we can discuss with a real person instead of a pseudonym?) Deep_Feelings doctore...@gmail.com writes: every one is telling dont go with python 3 , 3rd party tools and libraries have no compitability with python 3 That's a situation that will change over time, of course; *entirely new* code, with no external dependencies, is encouraged to use Python 3.x where feasible, and the number of existing libraries ported to Python 3.x can be expected to increase. so from previous experience : Whose previous experience? Python has never been in such a situation before, so I'm not sure what previous experience you expect to apply. when can i expect libraries and third party tools to be updated for python 3 ? (especially libraries ) That will differ for each and every third party and library, of course. Some will switch rapidly, others slowly, and still others will molder unmaintained and never convert. More to the point, you don't need to know when *every* party switches; just the parties that produce the libraries in which you're interested. Why not ask the parties themselves? -- \ “If we have to give up either religion or education, we should | `\ give up education.” —William Jennings Bryan, 1923-01 | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
out of memory with processing module
I'm using the third-party processing module in Python 2.5, which may have become the multiprocessing module in Python 2.6, to speed up the execution of a computation that takes over a week to run. The relevant code may not be relevant, but it is: q1, q2 = processing.Queue(), processing.Queue() p1 = processing.Process(target=_findMaxMatch, args= (reciprocal, user, clusters[1:(numClusters - 1)/2], questions, copy.copy(maxMatch), q1)) p2 = processing.Process(target=_findMaxMatch, args= (reciprocal, user, clusters[(numClusters - 1)/2:], questions, copy.copy (maxMatch), q2)) p1.start() p2.start() maxMatch1 = q1.get()[0] maxMatch2 = q2.get()[0] p1.join() p2.join() if maxMatch1[1] maxMatch2[1]: maxMatch = maxMatch1 else: maxMatch = maxMatch2 This code just splits up the calculation of the cluster that best matches 'user' into two for loops, each in its own process, rather than one. (It's not important what the cluster is.) The error I get is: [21661.903889] Out of memory: kill process 14888 (python) score 610654 or a child [21661.903930] Killed process 14888 (python) Traceback (most recent call last): ...etc. etc. ... Running this process from tty1, rather than GNOME, on my Ubuntu Hardy system allowed the execution to get a little further than under GNOME. The error was surprising because with just 1 GB of memory and a single for loop I didn't run into the error, but with 5 GB and two processes, I do. I believe that in the 1 GB case there was just a lot of painfully slow swapping going on that allowed it to continue. 'processing' appears to throw its hands up immediately, instead. Why does the program fail with 'processing' but not without it? Do you have any ideas for resolving the problem? Thanks for your help. -- http://mail.python.org/mailman/listinfo/python-list
Re: when can i expect libraries and third party tools to be updated for python 3 ?
On Mon, Apr 20, 2009 at 3:40 PM, Stefan Behnel stefan...@behnel.de wrote: alessiogiovanni.baroni wrote: On 20 Apr, 15:47, Deep_Feelings wrote: every one is telling dont go with python 3 , 3rd party tools and libraries have no compitability with python 3 so from previous experience : when can i expect libraries and third party tools to be updated for python 3 ? (especially libraries ) When the authors of a every library wants update to 3 :-D. ... or give a hand to the projects you need, if you don't want to sit and wait. Stefan -- http://mail.python.org/mailman/listinfo/python-list I think this is the key, really. I see a lot of people asking about when libraries will get ported to python 3, and it seems to me like a lot of people could just do a little reading on the tools provided for migrating, pull the dev version of the library, and take a crack at it. I'm sure the various library authors would be appreciative. Of course, it's probably hard for a lot of people to find time to do so (this does not exclude the library authors), and a good amount of the people asking probably aren't quite to the point that they could just dive in to an unfamiliar codebase. I would say that porting libraries to 3 would probably be a decent way of improving ones python chops though. -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python standard library and PEP8
On Mon, Apr 20, 2009 at 2:18 PM, Scott David Daniels scott.dani...@acm.orgwrote: Steven D'Aprano wrote: ... There's an accepted definition for objected oriented programming language: a language which provides objects, which are constructs encapsulating both data and routines to operate on that data in a single item. Says you. Roger King wrote a book entitled My Cat is Object-Oriented. His basic premise is that, while everyone understands what you mean when you say something is object-oriented, everyone's understanding is different. --Scott David Daniels scott.dani...@acm.org -- http://mail.python.org/mailman/listinfo/python-list Also see http://c2.com/cgi/wiki?NobodyAgreesOnWhatOoIs -- http://mail.python.org/mailman/listinfo/python-list
What is a real name, round 668 (was Re: when can i expect libraries and third party tools to be updated for python 3 ?)
In article 87tz4jl66c@benfinney.id.au, Ben Finney ben+pyt...@benfinney.id.au wrote: (Is there hope that you could set your From field using your real name so we can discuss with a real person instead of a pseudonym?) Could you define what a real name is? (If you think the above sounds annoyed, you are certainly correct; I have little patience for this nonsense.) -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ If you think it's expensive to hire a professional to do the job, wait until you hire an amateur. --Red Adair -- http://mail.python.org/mailman/listinfo/python-list
Re: best void return of a member function
Propable you can help me with an other problem ... the following code crash with: ==31431== Process terminating with default action of signal 11 (SIGSEGV) ==31431== General Protection Fault ==31431==at 0x4EA5151: PyObject_GenericGetAttr (object.c:982) ==31431==by 0x4EF1FBD: PyEval_EvalFrameEx (ceval.c:1941) ==31431==by 0x4EF5261: PyEval_EvalCodeEx (ceval.c:2869) ==31431==by 0x4E91618: function_call (funcobject.c:628) ==31431==by 0x4E6C7AC: PyObject_Call (abstract.c:2161) ==31431==by 0x4E8055A: method_call (classobject.c:323) ==31431==by 0x4E6C7AC: PyObject_Call (abstract.c:2161) ==31431==by 0x4E6DFFE: PyObject_CallFunctionObjArgs (abstract.c:2392) ==31431==by 0x6B8A43B: Python_pymsgque_pCallVoidMethod (pymisc.c:36) ==31431==by 0x6B8991D: PythonChildCreate (pymsgque.c:89) ==31431==by 0x6D9E15F: pTokenCheckSystem (token.c:547) ==31431==by 0x6DA5110: pReadHDR (read.c:385) with the following scenario 1. I have an object on an class 2. this object has a callable method context-config 3. I create an additional object of the same class 4. now I want to bind the context-config to the new object 5. I use: context-config = PyMethod_New(PyMethod_GET_FUNCTION(context-config), (PyObject*)context-self); 6. but call this object with PyObject_CallFunctionObjArgs create a crash this is my C code with some helper if (context-self == NULL) { context-self = PyObject_New(PyMqS_Obj,(PyTypeObject*)context-class); M0 printO(PyMethod_Function(context-config)) if (context-config != NULL) context-config = PyMethod_New(PyMethod_GET_FUNCTION(context-config), (PyObject*)context-self); M1 if (context-create != NULL) context-create = PyMethod_New(PyMethod_GET_FUNCTION(context-create), (PyObject*)context-self); M2 printO(context-config) printO(PyObject_Type(context-config)) } // 4. set the 'hdl' context-self-msgque = msgque; // 5. init the new object M3 if (msgque-config.server == MQ_YES context-config != NULL) { switch (NS(pCallVoidMethod)(msgque, context-config, NULL)) { case MQ_OK: break; case MQ_CONTINUE: case MQ_ERROR:goto error; } } M4 this is the output: output from the first object without error: configO - bound method Server.config of __main__.Server object at 0x2acee8eb7830 PyObject_Type(configO) - class 'method' PythonChildCreate(pymsgque.c:87) - 3 PythonChildCreate(pymsgque.c:95) - 4 output from the second object with the crash: PythonChildCreate(pymsgque.c:71) - 0 PyMethod_Function(context-config) - function config at 0x2acee8ead8d0 PythonChildCreate(pymsgque.c:75) - 1 PythonChildCreate(pymsgque.c:78) - 2 context-config - bound method Server.config of __main__.Server object at 0x2acee8a67b20 PyObject_Type(context-config) - class 'method' PythonChildCreate(pymsgque.c:87) - 3 -- http://mail.python.org/mailman/listinfo/python-list
Re: best void return of a member function
Andreas Otto wrote: if you wrote one language interface you can write every language interface This is like saying: if you used one programming language, you can use every programming language. Use is different from master or appreciate. - the tasks are allways the same... just the language-specific-names are changing That's the typical SWIG problem: you can generate wrappers for tons of languages, mostly automatically. But none of them will feel 'native' to the users of each of the target languages (well, possibly excluding C and Java here). As the author, you write a wrapper once (and maybe keep maintaining it), but every user of the wrapper will have to get along with its API that was copied into his/her language from another one. And there are usually a lot more users than authors. I'm not undervaluing your work. It's good to have many, many library bindings for Python. But having a good one would be even nicer. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: out of memory with processing module
On 20 Apr, 17:03, Brian knair...@yahoo.com wrote: I'm using the third-party processing module in Python 2.5, which may have become the multiprocessing module in Python 2.6, to speed up the execution of a computation that takes over a week to run. The relevant code may not be relevant, but it is: q1, q2 = processing.Queue(), processing.Queue() p1 = processing.Process(target=_findMaxMatch, args= (reciprocal, user, clusters[1:(numClusters - 1)/2], questions, copy.copy(maxMatch), q1)) p2 = processing.Process(target=_findMaxMatch, args= (reciprocal, user, clusters[(numClusters - 1)/2:], questions, copy.copy (maxMatch), q2)) p1.start() p2.start() maxMatch1 = q1.get()[0] maxMatch2 = q2.get()[0] p1.join() p2.join() if maxMatch1[1] maxMatch2[1]: maxMatch = maxMatch1 else: maxMatch = maxMatch2 This code just splits up the calculation of the cluster that best matches 'user' into two for loops, each in its own process, rather than one. (It's not important what the cluster is.) The error I get is: [21661.903889] Out of memory: kill process 14888 (python) score 610654 or a child [21661.903930] Killed process 14888 (python) Traceback (most recent call last): ...etc. etc. ... Running this process from tty1, rather than GNOME, on my Ubuntu Hardy system allowed the execution to get a little further than under GNOME. The error was surprising because with just 1 GB of memory and a single for loop I didn't run into the error, but with 5 GB and two processes, I do. I believe that in the 1 GB case there was just a lot of painfully slow swapping going on that allowed it to continue. 'processing' appears to throw its hands up immediately, instead. Why does the program fail with 'processing' but not without it? Do you have any ideas for resolving the problem? Thanks for your help. If your program crashes with more of one process, maybe you handle the Queue objects not properly? If you can, post the code of _findMaxMatch. -- http://mail.python.org/mailman/listinfo/python-list
Re: unpythonic use of property()?
Carl Banks pavlovevide...@gmail.com writes: On Apr 17, 4:00 pm, Scott David Daniels scott.dani...@acm.org wrote: Carl Banks wrote: On Apr 17, 10:21 am, J Kenneth King ja...@agentultra.com wrote: Consider: code: class MyInterface(object): def __get_id(self): return self.__id id = property(fget=__get_id) def __init__(self, id, foo): self.__id = id self.foo = foo class MyInterface2(object): def __init__(self, id, foo): self._id = id self.foo = foo @property def id(self): return self._id ... I was recently informed that it was 'unpythonic' and have since been a little confused by the term. I've heard it bandied about before but never paid much attention. What is 'unpythonic'? What about this example is unpythonic? There are different reasons someone might have said it. ... Some people think attribute name-mangling is unpythonic. It's true that people sometimes mistakenly treat it a solid information hiding mechanism, but I wouldn't call its usage unpythonic when used as intended: as a way to avoid name-collisions. If you think it's worthwhile to protect an attribute from being overwritten, you might as well guard against accidental conflict with the underlying name. Here you are assuming that a user of your class could not possibly have a valid reason for getting to the underlying variable. Don't make those decisions for someone else, in Python, we are all adults here. They can use the demangled name of the internal variable if they want access to it. Finally, some people think read-only attributes are unpythonic. I think that's ridiculous, although in general I'd advise against making attributes read-only willy-nilly. But there's a time and place for it. Generally, properties are for doing some form of calculation, not for making things read-only. That might be how properties are generally used, but if for some reason I wanted a read-only attribute, that's how I'd do it. [snip strawman stuff] It is not your job to protect those users who do not use your code properly from themselves; that way lies madness. I'm sorry, but the universe is not as simple as you are making it out to be. Blanket statements like the one you just gave here are not something that should ever be blindly adhered to. If, in my judgment, users would be prone to overwrite one of my attributes, and if I designed the system to rely on that attribute, and if the results of changing it are bad enough, then by golly I'm going to make the attribute harder than usual to modify. And yes, that is my job. Users who want to change it anyway can curse me and then go demangle the name themselves. Carl Banks Thanks for all the replies -- While greatly simplified, the reason for desiring read-only attributes in this case is that the interface is to a remote server whose policy relies on data objects represented by this class to have a few values which never change or are managed by the server and not the end user. Changing the ID value would break things on the server, so I wanted to write the interface class to respect those conventions. I'm well aware that if a developer really wanted to, they could get around it no matter what I did, but I figure that if I at least make it really difficult it will be obvious that they're really going into dangerous territory. Further (and this might just be a tad paranoid), user interface code which might use this API might be dangerous. It's one thing for a developer to break the rules when they need to, but a user shouldn't be able to. By enforcing read-only on the API it ensure (at least in my world view) that a developer writing a user interface against it won't have to code defensively against malicious input. However, since the difference between the two is simply attribute name-mangling it's practically a pedantic issue. I guess there might be some hyper-specific scenario where MyInterface would still be useful, but this one might not be it. Again, thanks. :) -- http://mail.python.org/mailman/listinfo/python-list
Python and GMP.
There are reasons why Python not used the GMP library for implementing its long type? -- http://mail.python.org/mailman/listinfo/python-list
Re: unpythonic use of property()?
On Apr 17, 7:21 pm, J Kenneth King ja...@agentultra.com wrote: Consider: code: class MyInterface(object): def __get_id(self): return self.__id id = property(fget=__get_id) def __init__(self, id, foo): self.__id = id self.foo = foo I use the double underscore/name mangling mechanism only if I am sure that the __xxx attribute will be overridden in subclasses, and overriding without protection will cause issues. Otherwise I don't bother, I use a single underscore. In my mind it is obvious that a private attribute _xxx attribute should not be overridden in subclasses without care. The double underscore instead says you can override me freely, don't worry and I reserve it for attributes which *should* be overridden. -- http://mail.python.org/mailman/listinfo/python-list
Re: and [True,True] -- [True, True]?????
On 20 Apr 2009 09:26:34 GMT, Steven D'Aprano wrote: On Mon, 20 Apr 2009 10:54:40 +0200, Gerhard Häring wrote: [snip] I prefer to write it explicitly: if len(lst) 0: Do you also count the length of a list explicitly? n = 0 for item in lst: n += 1 if n 0: ... No? Of course you don't. You understand that lists know how to calculate their own length, and you just ask the list for its length. Great. Well, lists also know whether or not they are empty, without needing to concern yourself with the definition of empty. if lst: # not empty else: # empty All Python objects have an understanding of empty or not empty, and the only time I've seen it cause problems is with iterators, because you can't tell if an iterator is empty until you actually try to access a value. Like Gerhard, I prefer the construction that explicitly says, This is a list, and this is what I'll do if it's not empty. To me, and I suspect to a great many programmers, if x: does *not* mean if x is not empty, it means if x is (in some sense) True, including the possibility that x is an object from which a True or False value must be extracted by means that might not be at all obvious. For an object lesson in the perils of said extraction, see the recent thread on [False,True] and [True,True] == [True,True]. People much smarter than me will no doubt rush to point out that if I were alert, I would know from the context that x is a list, and if I were thoroughly familiar with Python, I would know that when x is a list, if x: means not empty. True, but this is all the brain I got, so when I come back in two months, pathetically disoriented, to peer at this line of code through my senescent blear, I hope I'll see, This, Peter, is a list, and this is what I'll do . . . The not empty interpretation is a cute shortcut. But somebody's gotta put up some resistance to cute shortcuts, or we'll find ourselves back with Perl. -- To email me, substitute nowhere-spamcop, invalid-net. -- http://mail.python.org/mailman/listinfo/python-list
python-magic with python2.6
Is there any way to use python-magic(http://pypi.python.org/pypi/python-magic/0.1) with python2.6? Or do somebody know something similar to this what is running on 2.6? -- Gabriel -- http://mail.python.org/mailman/listinfo/python-list
sorting two corresponding lists?
Hello all, I wonder if someone could help me with sorting two corresponding lists. For instance the first list contains some items, and the second list contains their value (higher is better) items = [apple, car, town, phone] values = [5, 2, 7, 1] I would like to sort the 'items' list based on the 'values' list so that I end up with the following two list: items = [town, apple, car, phone] values = [7, 5, 2, 1] So I would like to keep the corresponding value still corresponding after the sorting. Is there an easy/nice/Pythonic way to do this? Thanks, Esmail -- http://mail.python.org/mailman/listinfo/python-list
Re: any(), all() and empty iterable
On Mon, 20 Apr 2009, Antoon Pardon wrote: On 2009-04-15, John O'Hagan m...@johnohagan.com wrote: On Tue, 14 Apr 2009, Mark Dickinson wrote: [...] I'd like to guess that in 93.7% of cases, when a programmer has used all(seq) without having thought in advance about what the right thing to do is when seq is empty, the current behaviour is already the right one. I tried to test this hypothesis, but a Google code search for uses of all() turned up very little besides definitions. For example: if all(t.already_filed() for t in my_tax_forms): go_to_bed_happy() else: file_for_extension() But what about this: if all(evidence): suspect_is_guilty else: suspect_is_innocent even if the evidence is not empty, the above wouldn't be a good test, because you need enough evidence en enough is not implied by all even if all is more than nothing. One should probably file for an extension until one gets some new tax forms, too, for that matter. It was just a facetious way of suggesting that it could be seen as counter-intuitive to say that no evidence is all true (you trimmed my smiley). evidence=() all(i is True for i in evidence) True all(i is False for i in evidence) True all(i is blue for i in evidence) True However don't worry, I've been thoroughly convinced that this behaviour is the way it is (and should be) done, if for no other reason than that the alternatives are even weirder! John -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting two corresponding lists?
Esmail wrote: Hello all, I wonder if someone could help me with sorting two corresponding lists. For instance the first list contains some items, and the second list contains their value (higher is better) items = [apple, car, town, phone] values = [5, 2, 7, 1] I would like to sort the 'items' list based on the 'values' list so that I end up with the following two list: items = [town, apple, car, phone] values = [7, 5, 2, 1] So I would like to keep the corresponding value still corresponding after the sorting. Is there an easy/nice/Pythonic way to do this? items = zip(*sorted(zip(values, items)))[1] To better understand this please note that a = [1, 2] b = [3, 4] zip(*zip(a, b)) == a, b or, in other words, zip(*argument) is the inverse of an argument created by zip (under the assumption the a and b have equal length) Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and GMP.
alessiogiovanni.bar...@gmail.com wrote: There are reasons why Python not used the GMP library for implementing its long type? Any reason it should? I don't know GMP (only that it exists), but adding binary dependencies is always a tricky and in need of careful weighting thing to do. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: sorting two corresponding lists?
On Apr 20, 12:10 pm, Esmail ebo...@hotmail.com wrote: Hello all, I wonder if someone could help me with sorting two corresponding lists. For instance the first list contains some items, and the second list contains their value (higher is better) items = [apple, car, town, phone] values = [5, 2, 7, 1] I would like to sort the 'items' list based on the 'values' list so that I end up with the following two list: items = [town, apple, car, phone] values = [7, 5, 2, 1] So I would like to keep the corresponding value still corresponding after the sorting. Is there an easy/nice/Pythonic way to do this? Thanks, Esmail Why not use a dictionary instead of two lists? Then you can sort the dictionary by value -- e.g. d = dict(zip(items, values)) sorted_items = sorted(d.iteritems(), key=lambda (k,v): (v,k)) This produces a list of pairs, but demonstrates the general idea. -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python standard library and PEP8
Emmanuel Surleau wrote: Hi there, Exploring the Python standard library, I was surprised to see that several packages (ConfigParser, logging...) use mixed case for methods all over the place. I assume that they were written back when the Python styling guidelines were not well-defined. Given that it's rather irritating (not to mention violating the principle of least surprise) to have this inconsistency, wouldn't it make sense to clean up the API by marking old-style, mixed-case methods as deprecated (but keep them around anyway) and add equivalent methods following the lowercase_with_underscores convention? On an unrelated note, it would be *really* nice to have a length property on strings. Even Java has that! Why not anySequence.len()? Colin W. PS Yes, I know this has been flogged before. Cheers, Emm -- http://mail.python.org/mailman/listinfo/python-list
Re: and [True,True] -- [True, True]?????
Peter Pearson ppear...@nowhere.invalid writes: The not empty interpretation is a cute shortcut. But somebody's gotta put up some resistance to cute shortcuts, or we'll find ourselves back with Perl. + QOTW -- http://mail.python.org/mailman/listinfo/python-list
Re: [ANN] pyxser-0.2r --- Python XML Serialization
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Stefan Behnel wrote: Daniel Molina Wegener wrote: Sorry, it appears that I've misunderstand your question. By /unicode objects/ I mean /python unicode objects/ aka /python unicode strings/. Yes, that's exactly what I'm talking about. Maybe you should read up on what Unicode is. OK, seems that the better option is to return both types in different functions, then it will allow the user to choice to fit the development needs. Most of them can be reencoded into /latin*/ strings and then /ascii/ strings if is that what you want. But for most communications, suchs as Java systems, utf-8 encoding goes as default. Well, then do not output a Python unicode string, but a UTF-8 encoded byte string as the default. Except for a couple of cases, Python unicode strings are very inconvenient for serialised XML. OK, good point, I must take a look on the implementation, and as I've said, I will implement both returns in different functions to allow a user choice, and document the impact of using python unicode strings. Thanks for your feedback :D Stefan Best regards, - -- .O.| Daniel Molina Wegener | C/C++ Developer ..O| dmw [at] coder [dot] cl | FreeBSD Linux OOO| http://coder.cl/| Standards Basis -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.9 (GNU/Linux) iQIcBAEBAgAGBQJJ7KMSAAoJEHxqfq6Y4O5NxXcQALZCT+mpjXv2My2XV6VdNAdd rd2W3q4ZLWdFdawvPwBWIzsoyAWIq1fU5tsZ4gywGesZFF2dbh6QJA7WvsqNaOXp wraeN0A3uWIwxAQEtHXu/vmO68CskVBxKZOrwjFOFoH3CoDqj0cdltKtddNkjHjl sxR91bK8lsBtYleQvng5oVjDouTvzSZEj9Lz2EbgjGIe+UKB8cQDLpT5CqF/whW7 kPmmbMJz195dyPTHstTy7BaZTJu/zgA3aNrbl4/QQ9B97dO5oMO3JEQgpTv4KSWn prpFo447HxYCChd+3wYyEx4tjMfnFezreuWxymKU9BP9Bk6yAcBFfdIDqBvUTDIw HF24n8NkesoHnoyQ1vf474fyIQ8NT28MQaBZXYntTTx1h015UB7vRMF0L3EttLRy VdpoRvlVAp01Z+7fdUjIRszveC5OCp1a4ZRmptcrZmIQM83Z/HZDBwjRO0zVuIqM 5qFmhERvgHSEl3cpdANznHZBKEEB9dqmAv9/XV5n5lUMg5Hn6d8yBkiwr5lRJ9eK 0n0602EuiPxgaP5cAbYF0MJGs3c+YNK9eIAmZC9++Fcg6lOlDSwS3RTQMsCi+Rvo k6gI0YNA9N19zbBfQippf1SGrmGrfPk141gNuXGW2HjIuTF9t3IAUZ/bgpWI74L/ 69u5ugNM+ERRnxpgIHLV =P88y -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: out of memory with processing module
On Apr 20, 9:18 am, alessiogiovanni.bar...@gmail.com wrote: On 20 Apr, 17:03, Brian knair...@yahoo.com wrote: I'm using the third-party processing module in Python 2.5, which may have become the multiprocessing module in Python 2.6, to speed up the execution of a computation that takes over a week to run. The relevant code may not be relevant, but it is: q1, q2 = processing.Queue(), processing.Queue() p1 = processing.Process(target=_findMaxMatch, args= (reciprocal, user, clusters[1:(numClusters - 1)/2], questions, copy.copy(maxMatch), q1)) p2 = processing.Process(target=_findMaxMatch, args= (reciprocal, user, clusters[(numClusters - 1)/2:], questions, copy.copy (maxMatch), q2)) p1.start() p2.start() maxMatch1 = q1.get()[0] maxMatch2 = q2.get()[0] p1.join() p2.join() if maxMatch1[1] maxMatch2[1]: maxMatch = maxMatch1 else: maxMatch = maxMatch2 This code just splits up the calculation of the cluster that best matches 'user' into two for loops, each in its own process, rather than one. (It's not important what the cluster is.) The error I get is: [21661.903889] Out of memory: kill process 14888 (python) score 610654 or a child [21661.903930] Killed process 14888 (python) Traceback (most recent call last): ...etc. etc. ... Running this process from tty1, rather than GNOME, on my Ubuntu Hardy system allowed the execution to get a little further than under GNOME. The error was surprising because with just 1 GB of memory and a single for loop I didn't run into the error, but with 5 GB and two processes, I do. I believe that in the 1 GB case there was just a lot of painfully slow swapping going on that allowed it to continue. 'processing' appears to throw its hands up immediately, instead. Why does the program fail with 'processing' but not without it? Do you have any ideas for resolving the problem? Thanks for your help. If your program crashes with more of one process, maybe you handle the Queue objects not properly? If you can, post the code of _findMaxMatch. Thanks for your interest. Here's _findMaxMatch: def _findMaxMatch(reciprocal, user, clusters, sources, maxMatch, queue): for clusternumminusone, cluster in enumerate(clusters): clusterFirstData, clusterSecondData = cluster.getData(sources) aMatch = gum.calculateMatchGivenData(user.data, None, None, None, user2data=clusterSecondData)[2] if reciprocal: maxMatchB = gum.calculateMatchGivenData(clusterFirstData, None, None, None, user2data=user.secondUserData)[2] aMatch = float(aMatch + maxMatchB) / 2 if aMatch maxMatch[1]: maxMatch = [clusternumminusone + 1, aMatch] queue.put([maxMatch]) -- http://mail.python.org/mailman/listinfo/python-list
Re: out of memory with processing module
On Apr 20, 9:18 am, alessiogiovanni.bar...@gmail.com wrote: On 20 Apr, 17:03, Brian knair...@yahoo.com wrote: I'm using the third-party processing module in Python 2.5, which may have become the multiprocessing module in Python 2.6, to speed up the execution of a computation that takes over a week to run. The relevant code may not be relevant, but it is: q1, q2 = processing.Queue(), processing.Queue() p1 = processing.Process(target=_findMaxMatch, args= (reciprocal, user, clusters[1:(numClusters - 1)/2], questions, copy.copy(maxMatch), q1)) p2 = processing.Process(target=_findMaxMatch, args= (reciprocal, user, clusters[(numClusters - 1)/2:], questions, copy.copy (maxMatch), q2)) p1.start() p2.start() maxMatch1 = q1.get()[0] maxMatch2 = q2.get()[0] p1.join() p2.join() if maxMatch1[1] maxMatch2[1]: maxMatch = maxMatch1 else: maxMatch = maxMatch2 This code just splits up the calculation of the cluster that best matches 'user' into two for loops, each in its own process, rather than one. (It's not important what the cluster is.) The error I get is: [21661.903889] Out of memory: kill process 14888 (python) score 610654 or a child [21661.903930] Killed process 14888 (python) Traceback (most recent call last): ...etc. etc. ... Running this process from tty1, rather than GNOME, on my Ubuntu Hardy system allowed the execution to get a little further than under GNOME. The error was surprising because with just 1 GB of memory and a single for loop I didn't run into the error, but with 5 GB and two processes, I do. I believe that in the 1 GB case there was just a lot of painfully slow swapping going on that allowed it to continue. 'processing' appears to throw its hands up immediately, instead. Why does the program fail with 'processing' but not without it? Do you have any ideas for resolving the problem? Thanks for your help. If your program crashes with more of one process, maybe you handle the Queue objects not properly? If you can, post the code of _findMaxMatch. Thanks for your interest. Here's _findMaxMatch: def _findMaxMatch(reciprocal, user, clusters, sources, maxMatch, queue): for clusternumminusone, cluster in enumerate(clusters): clusterFirstData, clusterSecondData = cluster.getData(sources) aMatch = gum.calculateMatchGivenData(user.data, None, None, None, user2data=clusterSecondData)[2] if reciprocal: maxMatchB = gum.calculateMatchGivenData(clusterFirstData, None, None, None, user2data=user.secondUserData)[2] aMatch = float(aMatch + maxMatchB) / 2 if aMatch maxMatch[1]: maxMatch = [clusternumminusone + 1, aMatch] queue.put([maxMatch]) -- http://mail.python.org/mailman/listinfo/python-list
efficiently checking for string.maketrans conflicts?
Hi everyone: I'm using translation in the sense of string.maketrans here. I am trying to efficiently compare if two string translations conflict -- that is, either they differently translate the same letter, or they translate two different letters to the same one. Here are some examples: # no conflict - equal t1 = Translation('ab', 'cd') t2 = Translation('ab', 'cd') # no conflict - inverses t1 = Translation('ab', 'cd') t2 = Translation('cd', 'ab') # conflict - same key, different value t1 = Translation('ab', 'cd') t2 = Translation('ab', 'ce') # conflict - different key, same value t1 = Translation('ab', 'cd') t2 = Translation('xy', 'cd') This conflict-checking is the bottleneck of my program, and the obvious way to implement it -- looping through the translations and explicitly checking for the above conditions -- is much slower than I'd like. Is there a more efficient, Pythonic way of checking if two translations conflict? Sincerely, Saketh -- http://mail.python.org/mailman/listinfo/python-list