PyQt 4.0beta1 Released
Riverbank Computing is pleased to announce the release of PyQt v4.0beta1 available from http://www.riverbankcomputing.co.uk/pyqt/. PyQt is a comprehensive set of Qt bindings for the Python programming language and supports the same platforms as Qt (Windows, Linux and MacOS/X). Like Qt, PyQt is available under the GPL and a commercial license. PyQt v4 supports Qt v4 (http://www.trolltech.com/products/qt/index.html). PyQt v3 is still available to support earlier versions of Qt. PyQt v4 is implemented as a set of 8 extension modules containing approximately 400 classes and 6,000 functions and methods. QtCore The non-GUI infrastructure including event loops, threads, i8n, Unicode, signals and slots, user and application settings. QtGui A rich collection of GUI widgets. QtNetwork A set of classes to support TCP and UDP socket programming and higher level protocols (eg. HTTP). QtOpenGL A set of classes that allows PyOpenGL to render onto Qt widgets. QtSql A set of classes that implement SQL data models and interfaces to industry standard databases. Includes an implementation of SQLite. QtSvg A set of classes to render SVG files onto Qt widgets. QtXML A set of classes that implement DOM and SAX parsers. QtAssistant A set of classes that enables the Qt Assistant online help browser to be integrated with an application. A Windows installer is provided for the GPL version of PyQt to be used with the GPL version of Qt v4 (http://www.trolltech.com/download/qt/windows.html). It enabes a complete PyQt environment to be installed on Windows without the need for a C++ compiler. PyQt includes the pyuic utility which generates Python code to implement user interfaces created with Qt Designer in the same way that the uic utility generates C++ code. It is also able to load Designer XML files dynamically. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Summer of Code mailing list
There's a new SoC mailing list. [EMAIL PROTECTED] You can sign up here: http://mail.python.org/mailman/listinfo/soc2006 This list is for any SoC discussion: mentors, students, idea, etc. Student can submit applications starting May 1, so now is the time to get students interested in your ideas! Please pass this information along. Cheers, n -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
python-dev Summary for 2006-01-16 through 2006-01-31
Sorry the summaries are so late. We were late already, and it's taken me a bit of time to get set up with the new python.org site. But I should be all good now, and hopefully we'll get caught up with all the summaries by the end of May. Hope you all weren't too depressed without your bi-weekly python-dev updates! ;-) python-dev Summary for 2006-01-16 through 2006-01-31 .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-01-16_2006-01-31] = Announcements = - Google summer internships - Google is looking to fill an unprecedented number of `student intern positions`_ this (US) summer, at several US locations (Mountain View, Santa Monica, Kirkland (Wash.), and New York). The perks are incredible, and Google is not just looking for software development interns - there are also product management positions, and UI design and usability analyst positions. Contributing thread: - `Know anyone interested in a Google internship? http://mail.python.org/pipermail/python-dev/2006-January/060047.html`__ .. _student intern positions: http://www.google.com/jobs/intern.html [TAM] --- Possible Summer of PyPy --- Armin Rigo announced the possibility of a Summer of PyPy, which would follow the style of Google's Summer of Code in funding students to work on various aspects of PyPy. The possibility has not been confirmed yet, but we'll let you know when there's more info. Contributing thread: - `Summer of PyPy http://mail.python.org/pipermail/python-dev/2006-January/059820.html`__ [SJB] = Summaries = --- Integers and strings in different bases --- Alex Martelli requested the inverse of ``int(string, base)`` that would convert an int into a string with digits in the appropriate base. There was a lot of discussion of exactly where such functionality should go. Among the suggested locations were: * The str constructor, e.g. ``str(number, base)`` * A str classmethod, e.g. ``str.from_int(number, base)`` * An encoding method, e.g. ``str(number).encode(basebase)`` * A method on ints, e.g. ``number.to_base(base)`` * A format code, e.g. ``%baseb % number`` * A builtin function, e.g. ``base(number, base)`` * A function in the math module, e.g. ``math.base(number, base)`` People seemed generally to like the builtin function or math module function options, though there was some debate as to the best name for the function. Guido suggested letting the proposal sit for a week or two to see if anyone could come up with a better name or suggest a better location for the function. (However, he seemed generally in favor of the proposal, suggesting that hex() and oct() should be deprecated and removed in a future version of Python.) No decisions had been made at the time this summary was written. Contributing threads: - `str with base http://mail.python.org/pipermail/python-dev/2006-January/059789.html`__ [SJB] PEP 355: Path - Object oriented filesystem paths Björn Lindqvist resuscitated the idea of incorporating a Path class based on Jason Ordenorff's path module to the standard library by creating `PEP 355`_. There was some general discussion (and corresponding PEP changes), with much discussion centred on the use of / as a join-with-separator operator, which was eventually dropped from the PEP. More discussion considered whether Path should subclass string or not. Subclassing string provides the advantage that Paths can be used in the majority of places where strings are currently used, without modification. However, there are many methods of strings that do not seem appropriate for Path objects. Jason Orendorff would prefer for Paths to not subclass strings, and a new format specifier (e.g. for PyArg_ParseTuple()) be created for use with Paths. There was general agreement that the utility of the module would be highest when Path objects could be seamlessly used where string paths were previous used. The debate centred on whether subclassing string was the best way to do this or not. Path objects clearly are not string objects (e.g. __iter__ and join() are nonsensical with paths). Changing the C API so that Paths are accepted where necessary was the suggested solution, although the PEP (at the time of writing the summary) still subclasses Path from string. Changing the methods from the names used by the os module and Jason's module to ones that conform to PEP 8 was recommended. Jason explained that the reason that there is so much cruft in his path module is that the design is heavily skewed toward people already familiar with the existing standard library equivalents. He feels that a standard
python-dev Summary for 2006-03-01 through 2006-03-15
python-dev Summary for 2006-03-01 through 2006-03-15 .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-03-01_2006-03-15] = Announcements = --- Webstats for python.org --- Thomas Wouters set up webalizer on dinsdale.python.org and added webstats for all subsites of python.org: * http://www.python.org/webstats/ * http://beta.python.org/webstats/ * http://bugs.python.org/webstats/ * http://planet.python.org/webstats/ * http://docs.python.org/webstats/ * http://svn.python.org/webstats/ Check 'em out if you're interested! Contributing thread: - `Webstats for www.python.org et al. http://mail.python.org/pipermail/python-dev/2006-March/061930.html`__ [SJB] --- Python 2.5 release schedule --- The first releases scheduled for Python 2.5 are quickly approaching. Check `PEP 356`_ for details, but the first alpha is due on April 1st. .. _PEP 356: http://www.python.org/doc/peps/pep-0356/ Contributing thread: - `2.5 release schedule? http://mail.python.org/pipermail/python-dev/2006-March/062185.html`__ [SJB] --- Py3K branch --- Guido has begun work on Py3K, starting a new branch to rip out some stuff like string exceptions and classic classes. He's trying to get a feel for what Python 3.0 will look like, hopefully before his keynote in OSCON. Contributing thread: - `Py3k branch - please stay out :-) http://mail.python.org/pipermail/python-dev/2006-March/062396.html`__ [SJB] --- Deprecated modules going away in Python 2.5 --- A number of deprecated modules will be removed in Python 2.5, including: * reconvert.py * regex (regexmodule.c) * regex_syntax.py * regsub.py and a variety of things from lib-old. These modules have been deprecated for a while now, and will be pulled in the next Python release. Contributing thread: - `Deprecated modules going away in 2.5 http://mail.python.org/pipermail/python-dev/2006-March/062405.html`__ [SJB] = Summaries = --- Maintaining ctypes in SVN trunk --- Thomas Heller put ctypes into the Python SVN repository, and with the help of perky, Neal Norwitz and Thomas Wouters, updated it to take advantage of the new ssize_t feature. The official ctypes development will remain in its Sourceforge repository at least for a while since this makes it easy to test ctypes on the SF compile farm. Contributing threads: - `ctypes is in SVN now. http://mail.python.org/pipermail/python-dev/2006-March/062211.html`__ - `Developing/patching ctypes (was: Re: integrating ctypes into python) http://mail.python.org/pipermail/python-dev/2006-March/062243.html`__ - `Developing/patching ctypes http://mail.python.org/pipermail/python-dev/2006-March/062244.html`__ [SJB] - Windows buildbots - Josiah Carlson had been working on getting a buildbot slave running on a Windows box, but eventually gave up due to crashes caused by VS.NET. Tim Peters fought his way through the setup with a XP box, posting `his lessons`_ to the wiki, and Trent Mick managed to follow a similar route and setup a Win2K buildbot slave. Thanks to all who suffered through the config -- Windows buildbot coverage looks pretty good now! .. _his lessons: http://wiki.python.org/moin/BuildbotOnWindows Contributing threads: - `Another Windows buildbot slave http://mail.python.org/pipermail/python-dev/2006-March/062068.html`__ - `Still looking for volunteer to run Windows buildbot http://mail.python.org/pipermail/python-dev/2006-March/062267.html`__ [SJB] --- Python 3.0: itr.next() or next(itr) --- The end of last fortnight's defaultdict thread turned to discussing the fate of the iterator protocol's .next() method in Python 3.0. Greg Ewing argued that renaming .next() to .__next__() and introducing a builtin function next() would be more consistent with the other magic methods and also more future-proof, since the next() function could be modified if the protocol method needed to change. Raymond Hettinger was very strongly against this proposal, suggesting that trading a Python-level attribute lookup for a Python-level global lookup plus a C-level slot lookup was not a good tradeoff. The discussion then spread out to other protocol method/function pairs -- e.g. len() and __len__() -- and Oleg Broytmann suggested that they could all be replaced with methods, thus saving a lookup and clearing out the builtin namespace. Neil Schemenauer and Michael Chermside argued against such a change, saying that the double-underscore pattern allows new special methods to be introduced without worrying about breaking user code, and that using
python-dev Summary for 2006-02-01 through 2006-02-15
python-dev Summary for 2006-02-01 through 2006-02-15 .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-02-01_2006-02-15] = Announcements = - QOTF: Quotes of the Fortnight - We had a plethora (yes, I did just say plethora) of quotable quotes this fortnight. Martin v. Löwis on the `lambda keyword`_: I believe that usage of a keyword with the name of a Greek letter also contributes to people considering something broken. Raymond Hettinger on the `learnability of Python`_: A language suitable for beginners should be easy to learn, but it should not leave them permanently crippled... To misquote Einstein: The language should be as simple as possible, but no simpler. Robert Brewer on `Pythonic syntax`_: Community consensus on syntax is a pipe dream. .. _lambda keyword: http://mail.python.org/pipermail/python-dev/2006-February/060389.html .. _learnability of Python: http://mail.python.org/pipermail/python-dev/2006-February/060420.html .. _Pythonic syntax: http://mail.python.org/pipermail/python-dev/2006-February/060556.html [SJB] Release plan for 2.5 `PEP 356`_ lists the release plan for Python 2.5. Check it out for the latest feature updates and planned release dates. .. _PEP 356: http://www.python.org/dev/peps/pep-0356/ Contributing threads: - `release plan for 2.5 ? http://mail.python.org/pipermail/python-dev/2006-February/060493.html`__ - `2.5 release schedule http://mail.python.org/pipermail/python-dev/2006-February/060982.html`__ - `2.5 PEP http://mail.python.org/pipermail/python-dev/2006-February/060985.html`__ [SJB] lsprof available as cProfile Armin Rigo finished his integration of the lsprof profiler. It's now available as the cProfile module which exposes the same interface as profile. Contributing thread: - `cProfile module http://mail.python.org/pipermail/python-dev/2006-February/060479.html`__ [SJB] - ssize_t branch merged - Martin v. Löwis merged in the ssize_t branch (`PEP 353`_). All you folks on 64 bit machines should now be able to index sequences using your full address space. Enjoy! .. _PEP 353: http://www.python.org/dev/peps/pep-0353/ Contributing threads: - `ssize_t status (Was: release plan for 2.5 ?) http://mail.python.org/pipermail/python-dev/2006-February/060714.html`__ - `ssize_t branch (Was: release plan for 2.5 ?) http://mail.python.org/pipermail/python-dev/2006-February/060810.html`__ - `ssize_t branch merged http://mail.python.org/pipermail/python-dev/2006-February/061073.html`__ [SJB] = Summaries = -- Rumors of lambda's death have been greatly exaggerated -- Guido's finally given in -- the lambda expression will stay in Python 3.0. Of course, this didn't stave off another massively long thread discussing the issue, but Guido finally killed that by providing a pretty exhaustive list of why we should keep lambda as it is: * No purely `syntactic change to lambda`_ is clearly a net gain over the current syntax * It's perfectly fine that Python's lambda is different from Lisp's * Lambda current binding behavior is (correctly) exactly the same as a def statement * Allowing a block inside a lambda is never going to work because of the need to indent the block .. _syntactic change to lambda: http://wiki.python.org/moin/AlternateLambdaSyntax Contributing threads: - `any support for a methodcaller HOF? http://mail.python.org/pipermail/python-dev/2006-February/060341.html`__ - `Let's just *keep* lambda http://mail.python.org/pipermail/python-dev/2006-February/060415.html`__ - `Let's send lambda to the shearing shed (Re: Let's just *keep* lambda) http://mail.python.org/pipermail/python-dev/2006-February/060583.html`__ [SJB] -- The bytes type -- Guido asked for an update to `PEP 332`_, which proposed a ``bytes`` type. This spawned a massive discussion about what the bytes type should look like and how it should interact with strings, especially in Python 3.0 when all strings would be unicode. Pretty much everyone agreed that bytes objects should be mutable sequences of ints in the range(0, 256). Guido and others were also generally against a b'...' literal for bytes, as that would confusingly suggest that bytes objects were text-like, which they wouldn't be. There was a fair bit of haggling over the signature of the bytes constructor, but it seemed towards the end of the discussion that people were coming to an agreement on ``bytes(initializer [,encoding])``, where ``initializer`` could be a sequence of ints or a str or unicode instance, and where ``encoding`` would be
python-dev Summary for 2006-02-16 through 2006-02-28
python-dev Summary for 2006-02-16 through 2006-02-28 .. contents:: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2006-02-16_2006-02-28] = Announcements = --- Python release schedule --- The Python 2.5 release schedule is `PEP 356`_. The first releases are planned for the end of March/beginning of April. Check the PEP for the full plan of features. .. _PEP 356: http://www.python.org/dev/peps/pep-0356/ Contributing threads: - `2.5 PEP http://mail.python.org/pipermail/python-dev/2006-February/061110.html`__ - `2.5 release schedule http://mail.python.org/pipermail/python-dev/2006-February/061249.html`__ - `2.4.3 for end of March? http://mail.python.org/pipermail/python-dev/2006-February/061901.html`__ [SJB] - Buildbot improvements - Thanks to Benji York and Walter Dörwald, the `buildbot results page`_ now has a new CSS stylesheet that should make it a little easier to read. (And thanks to Josiah Carlson, we should now have a Windows buildbot slave.) .. _buildbot results page: http://www.python.org/dev/buildbot/ Contributing threads: - `buildbot is all green http://mail.python.org/pipermail/python-dev/2006-February/061399.html`__ - `buildbot vs. Windows http://mail.python.org/pipermail/python-dev/2006-February/061554.html`__ [SJB] --- Deprecation of multifile module --- The multifile module, which has been supplanted by the email module since Python 2.2, is finally being deprecated. Though the module will not be removed in Python 2.5, its documentation now clearly indicates the deprecation. Contributing thread: - `Deprecate \`\`multifile\`\`? http://mail.python.org/pipermail/python-dev/2006-February/061211.html`__ [SJB] -- Win64 AMD64 binaries available -- Martin v. Löwis has made `AMD64 binaries`_ available for the current trunk's Python. If you're using an AMD64 machine (a.k.a. EM64T or x64), give 'em a whirl and see how they work. .. _amd64 binaries: http://www.dcl.hpi.uni-potsdam.de/home/loewis/ Contributing thread: - `Win64 AMD64 (aka x64) binaries available64 http://mail.python.org/pipermail/python-dev/2006-February/061533.html`__ [SJB] --- Javascript to adopt Python iterators and generators --- On a slightly off-topic note, Brendan Eich has blogged_ that the next version of Javascript will borrow iterators, generators and list comprehensions from Python. Nice to see that the Python plague is even spreading to other programming languages now. ;) .. _blogged: http://weblogs.mozillazine.org/roadmap/archives/2006/02/ Contributing thread: - `javascript quot;standing on Python's shouldersquot; as it moves forward. http://mail.python.org/pipermail/python-dev/2006-February/061472.html`__ [SJB] = Summaries = --- A dict with a default value --- Guido suggested a defaultdict type which would act like a dict, but produce a default value when __getitem__ was called and no key existed. The intent was to simplify code examples like:: # a dict of lists for x in y: d.setdefault(key, []).append(value) # a dict of counts for x in y: d[key] = d.get(key, 0) + 1 where the user clearly wants to associate a single default with the dict, but has no simple way to spell this. People quickly agreed that the default should be specified as a function so that using ``list`` as a default could create a dict of lists, and using ``int`` as a default could create a dict of counts. Then the real thread began. Guido proposed adding an ``on_missing`` method to the dict API, which would be called whenever ``__getitem__`` found that the requested key was not present in the dict. The ``on_missing`` method would look for a ``default_factory`` attribute, and try to call it if it was set, or raise a KeyError if it was not. This would allow e.g. ``dd.default_factory = list`` to make a dict object produce empty lists as default values, and ``del dd.default_factory`` to revert the dict object to the standard behavior. However, a number of opponents worried that confusion would arise when basic dict promises (like that ``x in d`` implies that ``x in d.keys()`` and ``d[x]`` doesn't raise a KeyError) could be conditionally overridden by the existence of a ``default_factory`` attribute. Others worried about complicating the dict API with yet another method, especially one that was never meant to be called directly (only overridden in subclasses). Eventually, Guido was convinced that instead of modifying the builtin dict type, a new collections.defaultdict should be introduced. Guido then defended keeping
Re: Non-web-based templating system
Actually, that looks even better that EmPy for what I need. I will try out these suggestions and then see what seems best. Thanks very much. -- http://mail.python.org/mailman/listinfo/python-list
Re: Non-web-based templating system
[EMAIL PROTECTED] wrote: Actually, that looks even better that EmPy for what I need. :-( -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM erikmaxfrancis All bad poetry springs from genuine feeling. -- Oscar Wilde -- http://mail.python.org/mailman/listinfo/python-list
Re: Using a browser as a GUI: which Python package
Problem solved using CherryPy. See http://aroberge.blogspot.com/2006/04/cherrypy-is-great.html for the details. -- http://mail.python.org/mailman/listinfo/python-list
Re: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism)
John Bokma wrote: Tagore Smith [EMAIL PROTECTED] wrote: Try sending mail to abuse at (any of my) desmesne(s). You won't get a response- in fact, no-one will read your mail. Then you come close to being RFC ignorant IMO. Couldn't be bothered to check it out. I don't care much about the RFC. I'd like to actually handle abusive users. But people report abuse for all kinds of strange reasons. It seems that believing in Darwinism is a form of abuse... go figure. That's actually my point. You are helping to ensure that abuse is tolerated. We stopped reading the abuse account for a reason. I'm not sure that Xah's post was offtopic, and I am not sure how to determine that objectively. An excessive crosspost is hardly ever on topic. Now you are just being dishonest. I am sure that it was excessively crossposted. I also know that Xah was posting to Usenet a long time before you, Could be, oldest post I could find of myself: http://groups.google.com/group/comp.sys.acorn/msg/c1a1f50a7fc6f3a4? dmode=source But is this a pissing contest? No- if it were you would no longer have internet access. -- http://mail.python.org/mailman/listinfo/python-list
Re: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism)
Tagore Smith [EMAIL PROTECTED] wrote: John Bokma wrote: [ .. ] An excessive crosspost is hardly ever on topic. Now you are just being dishonest. In what way? No- if it were you would no longer have internet access. Try me. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html -- http://mail.python.org/mailman/listinfo/python-list
Re: MinGW and Python
Martin v. Löwis wrote: How would you build for MSVCRT.DLL using MSVC 7 or 8? You don't have the header files for that library... You should be able to use the header files that come with these compilers. Things like sizes, field offsets, or member function names don't change between versions of the runtime. See the MSDN library page you refered to earlier: http://msdn2.microsoft.com/en-us/library/abx4dbyh(VS.80).aspx ... and you don't have the import library. I already mentioned where you can get it. Ross Ridge -- http://mail.python.org/mailman/listinfo/python-list
Re:
Tagore Smith schreef: [addressing John Bokma] your objection seems to be less about the crossposting, and more about the content. Why do you think that? -- Affijn, Ruud Gewoon is een tijger. -- http://mail.python.org/mailman/listinfo/python-list
Re: python-dev Summary for 2006-02-16 through 2006-02-28
Steven Bethard ha scritto: python-dev Summary for 2006-02-16 through 2006-02-28 .. contents:: [...] Translating the Python documentation Facundo Batista had proposed translating the Library Reference and asked about how to get notifications when the documentation was updated (so that the translations could also be updated). Georg Brandl suggested a post-commit hook in SVN, though this would only give notifications at the module level. Fredrik Lundh suggested something based on his `more dynamic library reference platform`_ so that the notifications could indicate particular methods and functions instead. As the new maintainer of python.it (where an huge amount of documentation has been already translated), I have written some scripts/modules to help to keep this translation updated. The scripts are in http://svn.python.it/admin/trunk/scripts/ with some examples in http://svn.python.it/admin/branches/updates/examples/ The process is simple. First with the mark script one can split a new document in N subparts (using visual marks), for helping translators to focus on small parts. see: http://svn.python.it/admin/branches/updates/examples/libdecimal.tex The main issue is updating the documentation to a new version. The update-version script will merge changes from old and new versions of the original documentation to the translated one. see: http://svn.python.it/admin/branches/updates/examples/emailmessage.tex I hope this scripts can be useful, I'm thinking of releasing then as a separate package. Regards Manlio Perillo -- http://mail.python.org/mailman/listinfo/python-list
Re: not quite 1252
Martin v. Löwis wrote: Well, if the document is UTF-8, you should decode it as UTF-8, of course. Thanks. This and: http://en.wikipedia.org/wiki/UTF-8 solved my problem with understanding the encoding. Anton proof that I understand it now (please anyone, prove me wrong if you can): from zipfile import ZipFile, ZIP_DEFLATED def by80(seq): it = iter(seq) while it: yield ''.join(it.next() for i in range(80)) def utfCheck(infn): zin = ZipFile(infn, 'r', ZIP_DEFLATED) data = zin.read('content.xml').decode('utf-8') for line in by80(data): print line.encode('1252') def test(): infn = xxx.sxw utfCheck(infn) if __name__=='__main__': test() -- http://mail.python.org/mailman/listinfo/python-list
PyQt 4.0beta1 Released
Riverbank Computing is pleased to announce the release of PyQt v4.0beta1 available from http://www.riverbankcomputing.co.uk/pyqt/. PyQt is a comprehensive set of Qt bindings for the Python programming language and supports the same platforms as Qt (Windows, Linux and MacOS/X). Like Qt, PyQt is available under the GPL and a commercial license. PyQt v4 supports Qt v4 (http://www.trolltech.com/products/qt/index.html). PyQt v3 is still available to support earlier versions of Qt. PyQt v4 is implemented as a set of 8 extension modules containing approximately 400 classes and 6,000 functions and methods. QtCore The non-GUI infrastructure including event loops, threads, i8n, Unicode, signals and slots, user and application settings. QtGui A rich collection of GUI widgets. QtNetwork A set of classes to support TCP and UDP socket programming and higher level protocols (eg. HTTP). QtOpenGL A set of classes that allows PyOpenGL to render onto Qt widgets. QtSql A set of classes that implement SQL data models and interfaces to industry standard databases. Includes an implementation of SQLite. QtSvg A set of classes to render SVG files onto Qt widgets. QtXML A set of classes that implement DOM and SAX parsers. QtAssistant A set of classes that enables the Qt Assistant online help browser to be integrated with an application. A Windows installer is provided for the GPL version of PyQt to be used with the GPL version of Qt v4 (http://www.trolltech.com/download/qt/windows.html). It enabes a complete PyQt environment to be installed on Windows without the need for a C++ compiler. PyQt includes the pyuic utility which generates Python code to implement user interfaces created with Qt Designer in the same way that the uic utility generates C++ code. It is also able to load Designer XML files dynamically. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Leo 4.4 rc1 released
Alle 22:58, venerdì 28 aprile 2006, Edward K. Ream ha scritto: Many new commands, including Small question. Has it way of using macro or programmable input? I mean this because for linux there arent many text editors with macro (recording/playing back) nor any with script commands. Thank you. If Leo lack of this, would be appreciated to give some idea to get involved on making it running python code. F -- http://mail.python.org/mailman/listinfo/python-list
Python member of function
Hi, I was wondering if anyone knew of a built in Python function that will check if an item is a member of a list, i.e., if item i is a member of list l. I read of a function in but I can't seem to get that to work and finding pages for python in does not reveal very many relevant sources. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python member of function
[EMAIL PROTECTED] wrote: I was wondering if anyone knew of a built in Python function that will check if an item is a member of a list, i.e., if item i is a member of list l. I read of a function in but I can't seem to get that to work and finding pages for python in does not reveal very many relevant sources. Yes, `in` is the relevant operator. It's quite simple to use: a = [1, 4, 9, 16, 25] 2 in a False 4 in a True If you're having problems using it in some circumstance, you'll have to be specific. -- Erik Max Francis [EMAIL PROTECTED] http://www.alcyone.com/max/ San Jose, CA, USA 37 20 N 121 53 W AIM erikmaxfrancis No man quite believes in any other man. -- H.L. Mencken -- http://mail.python.org/mailman/listinfo/python-list
Re: Python member of function
[EMAIL PROTECTED]: I was wondering if anyone knew of a built in Python function that will check if an item is a member of a list, i.e., if item i is a member of list l. 1 in [1,3,4] True 2 in [1,3,4] False -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
Re: Python member of function
Thanks, I was using in incorrectly. Thanks a lot! -- http://mail.python.org/mailman/listinfo/python-list
midi input
hiya, can you tell me of a python module available for linux which allows me to access midi i/o data. ie i want to get hold of raw midi input coming in from an external controller. ive managed to get the controller configured under alsa-midi. if possible could you also give me some example code on how to do this. thanks in advance will -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Leo 4.4 rc1 released
Fulvio wrote: I mean this because for linux there arent many text editors with macro (recording/playing back) nor any with script commands. umm. what about the big ones: emacs vim ? they both have extensive support for macros and scripting, and can both be scripted in Python. and if you're running linux, they're not very far away... /F -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt 4.0beta1 Released
Phil Thompson wrote: Riverbank Computing is pleased to announce the release of PyQt v4.0beta1 available from http://www.riverbankcomputing.co.uk/pyqt/. PyQt is a comprehensive set of Qt bindings for the Python programming language and supports the same platforms as Qt (Windows, Linux and MacOS/X). Like Qt, PyQt is available under the GPL and a commercial license. PyQt v4 supports Qt v4 (http://www.trolltech.com/products/qt/index.html). PyQt v3 is still available to support earlier versions of Qt. Phil, great news! However I have one question: my qt4 is built with QT_NO_ACCESSIBILITY and when I try to build pyqt I got errors no such method QWidget.setAccessibleName What should I do? Rebuild qt4 without QT_NO_ACCESSIBILITY #define? My qt is 4.1.2 skink -- http://mail.python.org/mailman/listinfo/python-list
[ANN] ConfigObj 4.3.1 validate 0.2.2
`ConfigObj 4.3.1 http://www.voidspace.org.uk/python/configobj.html`_ and `validate 0.2.2 http://www.voidspace.org.uk/python/validate.html`_ are now available. These are both minor bugfix/feature enhancement releases. What is New in ConfigObj ? Changes since **ConfigObj** 4.3.0 : * Added ``validate.py`` back into ``configobj.zip``. (Thanks to Stewart Midwinter) * Updated to `validate.py`_ 0.2.2. * Preserve tuples when calling the ``dict`` method. (Thanks to Gustavo Niemeyer.) * Changed ``__repr__`` to return a string that contains ``ConfigObj({ ... })``. * Change so that an options dictionary isn't modified by passing it to ConfigObj. (Thanks to Artarious.) * Added ability to handle negative integers in ``unrepr``. (Thanks to Kevin Dangoor.) What is New in validate ? Changes since **validate** 0.2.1 : * Addressed bug where a string would pass the ``is_list`` test. (Thanks to Konrad Wojas.) What is ConfigObj ? **ConfigObj** is a simple but powerful config file reader and writer: an *ini file round tripper*. Its main feature is that it is very easy to use, with a straightforward programmer's interface and a simple syntax for config files. It has lots of other features though : * Nested sections (subsections), to any level * List values * Multiple line values * String interpolation (substitution) * Integrated with a powerful validation system - including automatic type checking/conversion - repeated sections - and allowing default values * All comments in the file are preserved * The order of keys/sections is preserved * No external dependencies * Full Unicode support * A powerful ``unrepr`` mode for storing basic datatypes What is validate ? `validate.py http://www.voidspace.org.uk/python/validate.html`_ is a module for validating values against a specification. It can be used with **ConfigObj**, or as a standalone module. It is extensible, and as well as doing type conversion from strings, you can easily implement your own functions for transforming values in any way you please. -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt 4.0beta1 Released
On Saturday 29 April 2006 1:27 pm, Skink wrote: Phil Thompson wrote: Riverbank Computing is pleased to announce the release of PyQt v4.0beta1 available from http://www.riverbankcomputing.co.uk/pyqt/. PyQt is a comprehensive set of Qt bindings for the Python programming language and supports the same platforms as Qt (Windows, Linux and MacOS/X). Like Qt, PyQt is available under the GPL and a commercial license. PyQt v4 supports Qt v4 (http://www.trolltech.com/products/qt/index.html). PyQt v3 is still available to support earlier versions of Qt. Phil, great news! However I have one question: my qt4 is built with QT_NO_ACCESSIBILITY and when I try to build pyqt I got errors no such method QWidget.setAccessibleName What should I do? Rebuild qt4 without QT_NO_ACCESSIBILITY #define? My qt is 4.1.2 Yes - the current code assumes a fully configured Qt. Phil -- http://mail.python.org/mailman/listinfo/python-list
Re: Recommendations for a PostgreSQL db adapter, please?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Keen Anthony wrote: Hello, I am currently using psycopg 2 as my db adapter for a mod_python PostgreSQL web app. It's works fine, and I haven't any complaints. I would appreciate some input on what other pythonistas like in an adapter. There were several different options available to me, but there was no particular informed reason for me to choose psycopg. Am I missing anything? Considering pyPgSQL, psycopg1, PyGreSQL and psycopg2 - psycopg2 is a good choice. There's also interesting development happening here: http://python.projects.postgresql.org/ - but it seems to be in the midst of development. - -- Gerhard -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFEU17XdIO4ozGCH14RAsQyAKCS5opydZzciB8bCDbKqDWTLWeRHgCgmLpQ e40YgQmGCJfApvBNSVYX5kk= =L1El -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: Re:
Bill Atkins [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] John Bokma [EMAIL PROTECTED] writes: Isn't it crazy that one person is allowed to create such a huge mess everytime he posts? Isn't it crazy that one person willfully creates such a mess every time Xah posts? Shush! Don't waste your time with the Bokma. He wants everyone to follow the posting rules that annoy Bokma the least, but he never follows them himself. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to determine sequence ordering?
Steven Bethard wrote: nikie wrote: Steven Bethard wrote: John Salerno wrote: If I want to make a list of four items, e.g. L = ['C', 'A', 'D', 'B'], and then figure out if a certain element precedes another element, what would be the best way to do that? Looking at the built-in list functions, I thought I could do something like: if L.index('A') L.index('D'): # do some stuff This is probably a pretty reasonable approach as long as you're not too worried about efficiency. It scans the list twice though, so if you start doing this with really big lists, it might be better to do something like: On average, it'll only have go through half the list twice, as it can break as soon as it finds the item it searches for. Don't think you can get any more efficient than that. Sure you can: a_index = None d_index = None for i, item in enumerate(L): if item == 'A': a_index = i elif item == 'D': d_index = i if a_index is not None and d_index is not None: break if a_index d_index: # do some stuff That goes through exactly the minimum number of elements. But it's probably slower than two .index() calls since .index() is coded in C. But timeit and see if you're interested. On my PC, calling index twice is 5 times faster. But let's just pretend for a moment Python code was compiled and optimized as well as C code. Then, this function would still not be faster than calling index twice. You seem to be under the impression that looping through a list takes a lot of time and comparing items takes none. The reverse is the case: Looping through a list means the processor has to do something like increment an index once for every item in the list (for optimized C code! Looping through a generator like the one returned by enumerate in interpreted code is a lot more complex). Comparing two items on the other hand involves (as lists aren't statically typed) looking up a cmp-method dynamically, calling it dynamically, and, of course, a string comparison, which again involves two pointer lookups for every character that has to be compared. So, if you want to know how fast your function will be, you'll have to count the number of comparisons. (Of course, we're ignoring the fact that smaller functions tend to run quicker due to cache-, branch-prediction and optimization-effects) If you call your function with the list ['C', 'A', 'D', 'B'], it will compare the first item 'C' to 'A' and 'D', than the second, 'A' to 'A' and the third 'D' to 'A' and 'D', so it'll have to do 5 comparisons, correct? If you call index to find the first occurence of the item 'A' in the same list, it will have to do 2 comparisons (it can break as soon as it finds the iten), and 3 comparisons are needed for finding the item 'D', so it'll do 5 comparisons, too. Plus, you have a small overhead for comparing a_index and d_index to none (which is faster than a sting-comparison, but still takes time, probably more time than incrementing an index for looping through a list). Things get even worse if 'A' and 'D' aren't neighbors in the list, because than all the items bewteen 'A' and 'D' will have to be compared to 'A' and 'D' in the version above, but only to 'D' if you call index twice. So, the function above isn't only less readable, it's also slower on the average case. You might however be able to tweak the performance of the index-version a little bit if you call it only on small chunks of the array at a time, using the index()-versions that take a start- and stop index, so the whole list only has to be moved from the memory to the cache once. But I'm not sure the performance is memory-bound at all (always hard to tell in an interpreted language). L = ['C', 'A', 'D', 'B'] positions = dict((item, i) for i, item in enumerate(L)) positions {'A': 1, 'C': 0, 'B': 3, 'D': 2} positions['A'] positions['D'] True Isn't this bound to be less efficient? I mean, inserting the items into a dict is probably O(n log n) No, it's O(N). Dicts are just hash tables. Insertion is O(1). So N insertions is O(N). I've measured that with the timeit module. The time it takes to build a dict with N entries doesn't seem to be proportional to N, (t-c)/n keeps increasing. Try this: import timeit, math def time(N): return timeit.Timer(dict([('%%010i'%%i,i) for i in range(%i)]) % N).timeit(number=5) c = time(1000)*2-time(2000) for i in range(1000,100,1000): t = time(i) print %5i - %f (t/n = %f) % (i,t, (t-c)/i*1000) This route is also dramatically more efficient if you need to make M comparisons between items instead of just 1 comparison. In that case, using the dict is O(N + M) instead of the O(N * M) of the .index() route. Assuming (as I have said already) that you build the dict once, but call index again and again for every comparison, which is of course comparing
Need help removing list elements.
This is python 2.4.3 on WinXP under PythonWin. I have a config file with many blank lines and many other lines that I don't need. read the file in, splitlines to make a list, then run a loop that looks like this: config_file = open(lines.txt, rb) returned_lines = config_file.read().splitlines() i = len(returned_lines) for i in range(i): if returned_lines[i].find(Value) == -1: if returned_lines[i].find(Name) == -1: print read in this useless line ... print returned_lines[i] print Removing line ... returned_lines[i] = This blanks out all the lines I don't want. I did originally try 'del returned_lines[i]' but I got list index out of range, so I made a loop to delete the empty elements. for i in range(i): if returned_lines[i] == : del returned_lines[i] But this gives me IndexError: list out of range After much experimentation and dumping of the list, I have figured out that it doesn't like removing multiple empty elements in a row. In other words, if there are 4 empty lines, it will remove one of them, and seems to behave as though that was one element instead of 3. if I make i = i - *number of groups of empty elements* it works without an error, but leaves many empty elements behind. Obviously I can iterate over it time and again, but that isn't how the world should work. Is this something obvious that I am doing wrong, or something more complicated? Any help will be gratefully appreciated! -- http://mail.python.org/mailman/listinfo/python-list
Re: Recommendations for a PostgreSQL db adapter, please?
Gerhard Häring wrote: Keen Anthony wrote: Hello, I am currently using psycopg 2 as my db adapter for a mod_python PostgreSQL web app. It's works fine, and I haven't any complaints. I would appreciate some input on what other pythonistas like in an adapter. There were several different options available to me, but there was no particular informed reason for me to choose psycopg. Am I missing anything? Considering pyPgSQL, psycopg1, PyGreSQL and psycopg2 - psycopg2 is a good choice. Hmmm, Gerhard, you are listed as one of two developers for pyPgSQL on SourceForge ( http://sourceforge.net/projects/pypgsql/ ). The fact that you are recommending a different DB adaptor project suggests a degree of disengagement with pyPgSQL. Is Billy G. Allie still interested in pyPgSQL, or is it now completely unloved? If so, then perhaps some new maintainers can be found for it - several projects rely on pyPgSQL, including ours ( http://sourceforge.net/projects/netepi/ ) - for which we currently need to provide our own pyPgSQL tarball rolled from CVS plus some of our own minor but important patches - which were submitted for consideration but have not (AFAIK) been checked into the pyPgSQL CVS. The latest tarball for pyPgSQl available from the pyPgSQL SourceForge pages is dated 2003. No criticism is intended in any of the foregoing observations - it is inevitable that people move on to new projects (such as pySQLite), but it would be a shame if pyPgSQL just rotted, because it has several things in its favour, such as some unit tests (which were conspicuously absent from any of the alternatives when we evaluated them in 2003 - perhaps they have been added by now). Overall we have found pyPgSQL to be very reliable. Tim C -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help removing list elements.
This looks like a job for list comprehensions: returned_lines= ['Name: John, Value: 12','We don't want this one.','Name: Eric, Value: 24'] [x for x in returned_lines if ('Name' in x and 'Value' in x)] ['Name: John, Value: 12', 'Name: Eric, Value: 24'] List comprehensions are great. If you are not familiar with them, check out the Python documentation. Once you get started with them, you won't look back. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help removing list elements.
Ooops! Looking at your example a bit closer, change the 'and' in the list comprehension I posted to 'or', and it should do what you want. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help removing list elements.
[EMAIL PROTECTED] wrote in news:[EMAIL PROTECTED]: But this gives me IndexError: list out of range You are making the list shorter as you are iterating. By the time your index is at the end of the original list, it isn't that long any more. Creating a new list and appending the elements you want to keep avoids the problem. Or you can just use a list comprehension(untested): returned_lines=[line for line in open(lines.txt, 'rb') if line != ] or just returned_lines=[line for line in open(lines.txt) if line] max -- http://mail.python.org/mailman/listinfo/python-list
Re: Recommendations for a PostgreSQL db adapter, please?
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Tim Churches wrote: Gerhard Häring wrote: [...] Considering pyPgSQL, psycopg1, PyGreSQL and psycopg2 - psycopg2 is a good choice. Hmmm, Gerhard, you are listed as one of two developers for pyPgSQL on SourceForge ( http://sourceforge.net/projects/pypgsql/ ). The fact that you are recommending a different DB adaptor project suggests a degree of disengagement with pyPgSQL. It's not that I'd now say that pyPgSQL is bad software, but as you say it didn't see a lot of maintenance the last two years, and AFAIK this won't change anytime soon. With the last release, it was pretty much feature complete, and Billy G. Allie and me were talking about a rewrite of many parts in C for increased performance, and for taking advantage of the new PostgreSQL API. I told him that I was unfortunately too busy with other things to contribute significantly to pyPgSQL. I see myself more as a helper for pyPgSQL nowadays. Is Billy G. Allie still interested in pyPgSQL, or is it now completely unloved? AFAIK he is still interested and committing fixes to the current codebase now and then and working on the rewrite. I don't know, however, if there's a plan for the long overdue maintenance release to the last release from 2003. If so, then perhaps some new maintainers can be found for it [...] I'll just cc Billy so he can comment :-) - several projects rely on pyPgSQL, including ours ( http://sourceforge.net/projects/netepi/ ) - for which we currently need to provide our own pyPgSQL tarball rolled from CVS plus some of our own minor but important patches - which were submitted for consideration but have not (AFAIK) been checked into the pyPgSQL CVS. The latest tarball for pyPgSQl available from the pyPgSQL SourceForge pages is dated 2003. No criticism is intended in any of the foregoing observations - it is inevitable that people move on to new projects (such as pySQLite), but it would be a shame if pyPgSQL just rotted, because it has several things in its favour, such as some unit tests (which were conspicuously absent from any of the alternatives when we evaluated them in 2003 - perhaps they have been added by now). Overall we have found pyPgSQL to be very reliable. - -- Gerhard -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFEU3l/dIO4ozGCH14RAm7uAJ9AE5TnPvDL6Ic0z6Cf+QSSlkWnRwCgirdy TQnyqOyWMGX2KbGE+gFKIZU= =cTbz -END PGP SIGNATURE- -- http://mail.python.org/mailman/listinfo/python-list
Re: can i set up a mysql db connection as a class ?
On Apr 27, 2006, at 8:15 PM, [EMAIL PROTECTED] wrote: my question is, is there a way i can set up a global connection so that when the program loads, it connects once, then stays connected ? maybe i could assign instances of the cursor ? We do something like this in Dabo. We define connections, giving each an identifying name, and the application object loads the definitions at startup (without actually connecting). When a business object needs a connection, they call self.Application.getConnectionByName(connName). If that connection hasn't been made, the app connects and returns a reference to the connection. It also stores the reference, so that the next time a business object requests that connection, it simply returns the existing reference. shameless plug If you're developing database applications, especially if they involve a GUI, you really should take a look at Dabo. It's an app framework written by database developers for database developers. /shameless plug -- Ed Leafe -- http://leafe.com -- http://dabodev.com -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython, wxcombobox opening
Hi, I do not have the answer but am very interested in the issue. I tried this: l_ev = wx.MouseEvent(wx.wxEVT_LEFT_DOWN) l_ev.SetEventObject(self.GetCombo()) self.GetEventHandler().ProcessEvent(l_ev) Which did send the event to the combo (which is in a pannel in my case) .. but that is apparently not the event that triggers the dropping of the list. I posed elsewhere and will forward here any hint. Philippe Rony Steelandt wrote: Hi, Does somebody knows a way to automaticely open the list part of a wxCombobox when it gets the focus ? tia, Rony -- http://mail.python.org/mailman/listinfo/python-list
RE: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism)
but you know... one could simply hit the delete/skip button when you see a msg you don't like!!! or email/spam filters... or you can spend more time complaining.. in life, you gotta' learn to pick your battles... peace.. -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Tagore Smith Sent: Friday, April 28, 2006 9:43 PM To: python-list@python.org Subject: Re: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism) John Bokma wrote: Tagore Smith [EMAIL PROTECTED] wrote: Your emails to his ISP are far more wasteful- you are using up very scarce resources dedicated to dealing with real abuse. According to his hosting provider dreamhost: quote I have warned this user that excessive offtopic cross-posting is not allowed, and explained that if he doesn't quit he risks losing his account. If you (or anyone else) notice this in the future, please do not hesitate to submit another report. /quote Precisely: you have wasted the time of someone who might otherwise have spent that time dealing with real abuse. You got the standard email sent out to placate people like you. That was my point. Try sending mail to abuse at (any of my) desmesne(s). You won't get a response- in fact, no-one will read your mail. We just don't have the resources to deal with the easily offended. Too bad- we wouldn't mind handling real abuse, though it is unlikely given our selective set of users. I'm not sure that Xah's post was offtopic, and I am not sure how to determine that objectively. I am sure that it was excessively crossposted. I also know that Xah was posting to Usenet a long time before you, and that he will still be posting to Usenet long after you have given up in disgust, no matter who you complain to. Reread it a few times, it might educate you (note the *cross-posting* and the *submit another report*) I think I've mentioned the crossposting in every message I have posted on this thread, and that I don't approve of crossposting. I'm not sure that you are in a position to educate me, and that you suggest that you are is, frankly, obnoxious. I've been civil so far. (Rest of your misinterpretation snipped). You can snip the important part, but that won't make the point go away. I happen to have been working in this industry for a long time. I have a lot of friends working at, and running, various enterprises. Some of those enterprises handle a lot of the internet's traffic, measured by packets at least. If I were really ethically impaired I could easily mess up internet access for a list of people I don't like. A call from a backbone provider is not as ignorable as a random email to [EMAIL PROTECTED] But I am not ethically impaired (or at least not ethically impaired in that way). Every young sysadmin learns a simple thing: you have disproportionate power, don't abuse it. Sometimes you have to read people's mail, to diagnose a problem. If they are into weird bondage stuff you avert your eyes, and you _never_ tell anyone (though I think you are allowed to look at them funny at the company picnic). If they are into child porn you call the cops, I think (the ethics are fuzzy here, but this is my conclusion). Crossposting is bad, unless it serves a specific purpose- Xah's post obviously doesn't. I dont like people reporting on Usenet posters to their ISPs, but... I can't really complain about that. Crossposting is not good, without a really good justification. But you are complaining about the content of his posts, and harassing his ISP based on that. That's not just bad, it is wicked. You can quote whatever you want from their emails, but I won't change my mind on this subject- Xah shouldn't crosspost, but otherwise he should be allowed to post. Would you like a Usenet campaign started to disrupt your internet access? You would be angry if that were done, and justifiably. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Databases in Python
Dennis Lee Bieber wrote: On Fri, 28 Apr 2006 21:29:32 +0100, Steve Holden [EMAIL PROTECTED] declaimed the following in comp.lang.python: Dennis Lee Bieber wrote: Given that his web-site implies that he does these for a living, it may not be a publicly available item. Nah, he's a bozo and his web site is completely wrong (as usual :-). I didn't mean to imply everything is done commercially, only that what I saw seemed to lean that way (I also clicked on one of the books that showed up and got something about unavailable from Amazon G) Hmm, time to crawl the site, methinks. Thank you! regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Can you create an instance of a subclass with an existing instance of the base class?
Lawrence D'Oliveiro wrote: In article [EMAIL PROTECTED], bruno at modulix [EMAIL PROTECTED] wrote: Lawrence D'Oliveiro wrote: In article [EMAIL PROTECTED], bruno at modulix [EMAIL PROTECTED] wrote: Lawrence D'Oliveiro wrote: (snip) I think you're taking Python's OO-ness too seriously. One of the strengths of Python is that it can _look_ like an OO language without actually being OO. According to which definition of OO ? Isn't there one? Your claim that Python _look_ like an OO language without actually being OO implicitely relies on a definition of OO - or is just meaningless. Which nicely evades answering the question. Well I have to say you are also nicely evading answering the question, which is enough to make me suspect your are trolling (deliberately asking contentious questions for the purposes of creating futile argument and discussion). If you *aren't* trolling then what's your objection to saying what led you to make the assertion that Python could look like an OO language without being one? But sine you say later that Python objects are basically dictionaries it's clear your understanding of Python isn't terribly complete, which might cast doubt on your understanding of object orientation. For the record, Python *is* an object-oriented language, but it happens to offer convenient features for procedural programming as well. Since these features are orthogonal to its OO features, the fact that they exist doesn't stop Python from being an OO language. So why do you assert that it merely looks like one? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
http://blog.wokkow.com/user1/xinyegong/index.shtml
http://blog.wokkow.com/user1/xinyegong/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
http://blog.wokkow.com/user1/xinyegong/index.shtml
http://blog.wokkow.com/user1/xinyegong/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
http://blog.wokkow.com/user1/xinyegong/index.shtml
http://blog.wokkow.com/user1/xinyegong/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
How to get computer name
How do I get the computer name in python? I've been looking over the internet, and couldn't find anything. Thanks! Bud -- http://mail.python.org/mailman/listinfo/python-list
self modifying code
When young I was warned repeatedly by more knowledgeable folk that self modifying code was dangerous. Is the following idiom dangerous or unpythonic? def func(a): global func, data data = somethingcomplexandcostly() def func(a): return simple(data,a) return func(a) It could be replaced by data = somethingcomplexandcostly() def func(a): return simple(data,a) but this always calculates data. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get computer name
pitarda [EMAIL PROTECTED] writes: How do I get the computer name in python? You can use the os module to get it from your environment. import os os.getenv('HOSTNAME') 'calvin.watterson' Depending on your operating system, the environment variable you need might have a different name. For example, I think in Windows you might try os.getenv('COMPUTERNAME') You can see all of the environment variables currently available with os.environ I hope this helps, Tim -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get computer name
Thanks! :) Though,... I think once I saw something like: getComputerByName but can't find it anymore,... :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Re:
Matt Garrish [EMAIL PROTECTED] wrote: Don't waste your time with the Bokma. He wants everyone to follow the posting rules that annoy Bokma the least, but he never follows them himself. Wow Matt, did it hurt that bad boy? Grow up, you're smart enough to see what Xah is doing. If not, ask someone with more brains to control you better. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Hooking things up in GUI application
Ryan Ginstrom [EMAIL PROTECTED] wrote: Behalf Of sturlamolden If you use PyGTK (it also runs on Windows), you can design the GUI with GLADE and then use libglade to import the gui as an xml-resource. Yes, I've tried something similar with wxGlade. Nice, but it doesn't seem to remove the most tedious work -- hooking up handlers (although it does help here, at the cost of some behind-the-scenes magic), and getting data into and out of GUI widgets. Kiwi http://www.async.com.br/projects/kiwi/ looks promising, but it is under heavy development and you have to learn it by examples. Florian -- Emacs hat den weiten Weg von krank, nur krank bis komisch hinter sich. [David Kastrup in [EMAIL PROTECTED]] -- http://mail.python.org/mailman/listinfo/python-list
Re: self modifying code
Robin Becker schrieb: When young I was warned repeatedly by more knowledgeable folk that self modifying code was dangerous. Is the following idiom dangerous or unpythonic? def func(a): global func, data data = somethingcomplexandcostly() def func(a): return simple(data,a) return func(a) It took me quite a while to figure out how it works, so, yes, I'd say it's unpythonic ;-). It's not really dangerous, but it can get nasty if someone tries to rename the function, or put it into a class. But that's probably not the kind of self-modifying code you've been warned against anyway: I've only ever seen self-modifying code in assembly language or in lisp, the idea is that you really change the code (i.e. single opcodes in the function that's currently running), so you can e.g. make an infinite loop, and eventually overwrite the loop statement to do something else so the loop ends. I'm not sure if you can do the same thing in Python, maybe by changing the bytecode of a running function. It could be replaced by data = somethingcomplexandcostly() def func(a): return simple(data,a) but this always calculates data. You could of course initialize data with None and calculate it only on demand. Or you could use: http://www.phyast.pitt.edu/~micheles/python/documentation.html#memoize This has the advantage of encapsulating the memoization logic so it can be tested (and understood) separately from your code. -- http://mail.python.org/mailman/listinfo/python-list
Re: self modifying code
Robin Becker wrote: When young I was warned repeatedly by more knowledgeable folk that self modifying code was dangerous. Is the following idiom dangerous or unpythonic? def func(a): global func, data data = somethingcomplexandcostly() def func(a): return simple(data,a) return func(a) It could be replaced by data = somethingcomplexandcostly() def func(a): return simple(data,a) but this always calculates data. Consider data = None def func(a): global data if data is None: data = costly() return simple(data, a) if you want lazy evaluation. Not only is it easier to understand, it also works with from lazymodule import func at the cost of just one object identity test whereas your func() implementation will do the heavy-lifting every time func() is called in the client (unless func() has by chance been invoked as lazymodule.func() before the import). Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Re:
John Bokma [EMAIL PROTECTED] wrote: Matt Garrish [EMAIL PROTECTED] wrote: Don't waste your time with the Bokma. He wants everyone to follow the posting rules that annoy Bokma the least, but he never follows them himself. Wow Matt, did it hurt that bad boy? Grow up, you're smart enough to see what Xah is doing. If not, ask someone with more brains to control you better. Also, if you need a post in a Xah Lee thread to make you look right, and me look bad... that's quite a message in itself Garrish :-D. -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get computer name
On 29 Apr 2006 10:04:39 -0700, pitarda wrote: Thanks! :) Though,... I think once I saw something like: getComputerByName but can't find it anymore,... :) import socket print socket.gethostname() blade print socket.gethostbyname('blade') # will print IP address -- Richard -- http://mail.python.org/mailman/listinfo/python-list
Re: self modifying code
Peter Otten wrote: def func(a): global func, data data = somethingcomplexandcostly() def func(a): return simple(data,a) return func(a) at the cost of just one object identity test whereas your func() implementation will do the heavy-lifting every time func() is called in the client (unless func() has by chance been invoked as lazymodule.func() before the import). in the example code the heavy lifting, costly(), is done only once as the function that does it is overwritten. As pointed out it won't work as simply in a class. Memoisation could improve the performance of the normal case form of the function ie def func(a): return simple(data,a) but I guess that would depend on whether simple(data,a) is relatively expensive compared to the costs the memo lookup. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
opposite function to split?
hello everyone! I can't seem to find a function that combines a list of items into a string with a seperator between the individual elements.. Is there such a method that does the opposite of sting.split? thanks alot! -- http://mail.python.org/mailman/listinfo/python-list
Re: opposite function to split?
[EMAIL PROTECTED] wrote: hello everyone! I can't seem to find a function that combines a list of items into a string with a seperator between the individual elements.. Is there such a method that does the opposite of sting.split? thanks alot! join is your answer ','.join(['a','b','c']) == 'a,b,c' -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: self modifying code
Robin Becker [EMAIL PROTECTED] writes: When young I was warned repeatedly by more knowledgeable folk that self modifying code was dangerous. Is the following idiom dangerous or unpythonic? def func(a): global func, data data = somethingcomplexandcostly() def func(a): return simple(data,a) return func(a) 1. I don't think most people would call that self-modifying code. I won't try defining that term precisely because I know you'll just pick holes in my definition ;-) 2. The use of global func is just plain weird :-) 3. Peter Otten's version is OK, but how about this, using a closure instead of globals (UNTESTED) def make_func(): namespace = object() namespace.data = None def func(a): if namespace.data is None: namespace.data = somethingcomplexandcostly() return simple(namespace.data, a) return func func = make_func() John -- http://mail.python.org/mailman/listinfo/python-list
Re: Using a browser as a GUI: which Python package
André [EMAIL PROTECTED] writes: [...] I would like to use a browser (e.g. Firefox) as a simple GUI framework. Note that this is to be done on a single user machine, so the question of sandboxing is not really relevant here. [...] My ultimate goal would be to port the main features of two wxPython-based apps I wrote (rur-ple and Lightning Compiler, both found at https://sourceforge.net/project/showfiles.php?group_id=125834) within a standard browser. If you can stick to Firefox, you might find XUL useful. There are various different styles of development that use XUL and Python -- a bit of Googling and reading should find them. John -- http://mail.python.org/mailman/listinfo/python-list
Re: Urllib2 / add_password method
mrstephengross [EMAIL PROTECTED] writes: I'm working on learning how to use urllib2 to use a proxy server. I've looked through the postings on this group, and it's been helpful. I have not, however, found complete documentation on the add_password() functions. Here's what I've got so far: Don't use a password manager with proxy auth in 2.4, it doesn't work: http://python.org/sf/1470846 [...] It works, but I don't really know what I'm doing with the proxy_auth_handler part. Specifying username and password make sense, but I haven't found documentation on what 'realm' and 'host' are for. Shouldn't username password be sufficient? Both proxy and auth handling in urllib2 are buggy in 2.4, but passing the username and password in the userinfo component of the URL works (didn't read your code, hope nothing important in there): import urllib2 proxy_handler = urllib2.ProxyHandler({ http: http://john:[EMAIL PROTECTED]:3128}) opener = urllib2.build_opener(proxy_handler) response = opener.open(url) However, ISTR specifying a port number as I do above (the :3128 bit) is not supported in 2.4 (it does in current SVN, so will in 2.5). Hmm, I notice just now that urllib2's digest auth support breaks urllib2's handler scheme. Must file another bug... John -- http://mail.python.org/mailman/listinfo/python-list
Re: self modifying code
John J. Lee wrote: 1. I don't think most people would call that self-modifying code. I won't try defining that term precisely because I know you'll just pick holes in my definition ;-) Don't really disagree about the rewriting code, but the function does re-define itself. 2. The use of global func is just plain weird :-) 3. Peter Otten's version is OK, but how about this, using a closure instead of globals (UNTESTED) def make_func(): namespace = object() namespace.data = None def func(a): if namespace.data is None: namespace.data = somethingcomplexandcostly() return simple(namespace.data, a) return func func = make_func() ... the inner function is almost precisely what I started with, except I used the global namespace. However, it keeps the test in side the function which costs about 1%. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: A QFB agent: how to catch C-level crashes and last Python stack ?
Thomas Heller wrote: robert wrote: When employing complex UI libs (wx, win32ui, ..) and other extension libs, nice only Python stack traces remain a myth. Currently I'm hunting again a rare C-level crash bug of a Python based Windows app with rare user reports - and still in the dark (I get snippets of machine stack traces / screenshots with random mem. access error / python caused the runtime to terminate in an unusual way / ..) I'd like to hook a kind of quality feedback agent a C-level to enable the user transfer a report (similar to what Mozilla/Netscape has), e.g. in a changed python.exe stub. Next to the machine stack/regs it should grab the relevant last Python thread stack(s), if any, and maybe other useful status and python global vars. (There are also Python threads going on. ) Is that possible? -robert It looks like this may be what you want. Quoting from http://www.usenix.org/events/usenix01/full_papers/beazley/beazley.pdf In recent years, scripting languages such as Perl, Python, and Tcl have become popular development tools for the creation of sophisticated application software. One of the most useful features of these languages is their ability to easily interact with compiled languages such as C and C++. Although this mixed language approach has many benefits, one of the greatest drawbacks is the complexity of debugging that results from using interpreted and compiled code in the same application. In part, this is due to the fact that scripting language interpreters are unable to recover from catastrophic errors in compiled extension code. Moreover, traditional C/C++ debuggers do not provide a satisfactory degree of integration with interpreted languages. This paper describes an experimental system in which fatal extension errors such as segmentation faults, bus errors, and failed assertions are handled as scripting language exceptions. This system, which has been implemented as a general purpose shared library, requires no modifications to the target scripting language, introduces no performance penalty, and simplifies the debugging of mixed interpreted-compiled application software. It may be an interesting project to port this to Windows. Hope that helps, Thanks, exactly. That would be quite luxurious as WAD manages to even continue normal Python execution on the current stack (only in a UNIX main thread?) with a regular Python exception. That would make pets out of all bugs - preventing users from facing nameless app freezes, but make the help bug elimination for distributed programs by detailed reports. simply catching signal.SIGSEGV with Python's signal module causes just looping at 100% CPU load (The GIL is not forced ?) WAD obviously has not anymore evolved since the beginning. The Author says, that a Windows port would be quite complex - because advanced execution context manipulation is obviously not possible with signals on Windows. Yet he mentions the Windows C++ structured exception handling, which may enable that. I know that the fast Object Store OO-Database uses exactly that method to catch and recover execution from seg faults, while updating a kind of memory mapped database into the system. I integrated that OO-DBMS exception handler once with Python some years back by making a C++ file out of python.c as shown below or even by using that PSECall alone, which is needed anyway for wrapping any other Python threads (start functions) with the seg fault handler. Probably there is even better thread control possible than on Linux. Yet I don't know so far if its possible to find the valid Python exit functions on the stack (for returning from exceptions) the same style as in Unix ELF binaries ... -- #define OS_PSE_ESTABLISH_FAULT_HANDLER \ { try { _PSE_NS_ _ODI_fault_handler _ODI_handler; try { .. #define OS_PSE_END_FAULT_HANDLER \ } catch (_PSE_NS_ os_err e) { e.print(); } \ } catch (_PSE_NS_ _ODI_fault_handler) {} } .. #include os_pse/ostore.hh #include Python.h extern C { DL_EXPORT(int) Py_Main(int, char**);} int main(int argc, char **argv) { int result=0; // The top of the stack of every thread of every program // must be wrapped in a fault handler // This macro begins the handler's scope OS_PSE_ESTABLISH_FAULT_HANDLER result = Py_Main(argc, argv); // This macro ends the fault handler's scope OS_PSE_END_FAULT_HANDLER return result; } --- #ifdef SWIG //# for wrapping python threads with the PSE fault handler %native(PSECall) _wrap_PSECall; %{ //#include os_pse/ostore.hh //#include Python.h static PyObject *_wrap_PSECall(PyObject *self, PyObject *args) { PyObject * func =0 ; PyObject * funcargs =0 ; PyObject* result; if(!PyArg_ParseTuple(args,OO:PSECall,func, funcargs)) return NULL; // The top of the stack of every thread of every program // must be wrapped in
Re: [wwwsearch-general] Re: Urllib2 / add_password method
On Sat, 29 Apr 2006, John J. Lee wrote: mrstephengross [EMAIL PROTECTED] writes: I'm working on learning how to use urllib2 to use a proxy server. I've looked through the postings on this group, and it's been helpful. I have not, however, found complete documentation on the add_password() functions. Here's what I've got so far: Don't use a password manager with proxy auth in 2.4, it doesn't work: http://python.org/sf/1470846 [...] It works, but I don't really know what I'm doing with the proxy_auth_handler part. Specifying username and password make sense, but I haven't found documentation on what 'realm' and 'host' are for. Shouldn't username password be sufficient? Oops, didn't read your question. I'm surprised if it worked at all given that bug (maybe you're using an older Python, and I forget all the details of the bug). Anyway, to answer your question: yes, username password *should* be sufficient, but the password manager classes in urllib2 at present aren't very friendly like that. You can use HTTPPasswordMgrWithDefaultRealm so that at least you can forget about the realm part. (The realm is what you see in the title bar of the pop-up that web browsers display. See RFC 2617 for more details.) I'm adding friendlier proxy/auth support to package mechanize ATM (and finding/fixing bugs as I go), so maybe some of that will find its way into Python 2.6. John -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple DAV server?
Ivan Voras wrote: Kyler Laird wrote: Ivan's been working on a problem I've been experiencing with Windows XP (failure to launch). He sent a new version my way today. I'm going to test it tomorrow when I've got some XP users available. If it works I'm going to work on putting my changes into a subclass. I don't see this being a full-featured fully-compliant DAV server immediately but I'm betting that it will provide adequate service for my users soon. Most of the problems are probably because I didn't mean it to be a fully-compliant WebDAV server, but to serve my need at the time :) I'm still waiting for SourceForge to approve the project so there's a proper place to integrate all the patches. One thing I insist on is the separation of davserver and fsdav (e.g. no contamination of knowledge between the two). I tried a little with that last package from KL (MOVE). Added the missing urllib.unquote's and sorted few other problems. ok. I now also need PROPPATCH / arbitrary properties. Windows for example stores (original) file time stamps in such properties. Started writing on that, yet not complete - little complex. Properties to go to a .##dav folder (copied and moved together with the objects with COPY/MOVE). -robert -- http://mail.python.org/mailman/listinfo/python-list
Re: urllib.urlopen() with pages that requires cookies.
mwt [EMAIL PROTECTED] writes: Fredrik Lundh wrote: [...] use urllib2 and cookielib. here's an outline: import urllib2, cookielib # set things up jar = cookielib.CookieJar() handler = urllib2.HTTPCookieProcessor(jar) opener = urllib2.build_opener(handler) urllib2.install_opener(opener) data = urllib2.urlopen(someurl).read() # ... data = urllib2.urlopen(someotherurl).read() # ... # dump cookie jar contents (for debugging) for cookie in jar: print cookie /F How would this outline be changed/expanded if it also needed to handle basic authentication? ... handler = urllib2.HTTPCookieProcessor(jar) pm = urllib2.HTTPPasswordMgrWithDefaultRealm() # use None for realm: send username and password for all realms pm.add_password(None, http://example.com/;, joe, password) auth_handler = HTTPBasicAuthHandler(pm) opener = urllib2.build_opener(handler, auth_handler) ... Note that (I just noticed that) using both basic auth and digest auth handlers at the same time is broken, at least in SVN :-(( John -- http://mail.python.org/mailman/listinfo/python-list
Re: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism)
Tagore Smith [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] The only thing really wrong with Xah's post is that it was crossposted to several groups. I think the content of repeatedly slandering people as criminals, because of technical disagreements, is even more abusive. tjr -- http://mail.python.org/mailman/listinfo/python-list
Can we create an_object = object() and add attribute like for a class?
Hi all, Is there any reason that under Python you cannot instantiate the object class and create any attributes like you would be able for a normal class? Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. a = object() a.data = 1 Traceback (most recent call last): File stdin, line 1, in ? AttributeError: 'object' object has no attribute 'data' class Object: ... pass ... a = Object() a.data = 1 print a.data = , a.data a.data = 1 class Object2(object): ... pass ... b = Object2() b.data = 2 b.data 2 I also tried with Python 2.4.3 with the same results. Being able to do it would seem a natural way of declaring namespaces. -- Pierre Rouleau -- http://mail.python.org/mailman/listinfo/python-list
Re: (was Re: Xah's Edu Corner: Criticism vs Constructive Criticism)
bruce wrote: but you know... one could simply hit the delete/skip button when you see a msg you don't like!!! or email/spam filters... or you can spend more time complaining.. in life, you gotta' learn to pick your battles... peace.. Bruce: You may want to check your mail reader to make sure it responds to the thread. That would help people to skip messages. The thread in question got out of hand a long time ago (even before I jumped in ;), so it would help if related posts replied to the thread--at least thunderbird does not group your post with the thread. I'm guessing other news readers won't either. Also, there is no doubt that you will soon be chastised for top posting: http://en.wikipedia.org/wiki/Top-posting James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah's Edu Corner: What Languages to Hate
John Bokma schrieb: quote I have warned this user that excessive offtopic cross-posting is not allowed,[...] /quote I just wrote to the abuse department at dreamhost, telling them that your accusations are highly exaggerated. Timo -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah's Edu Corner: What Languages to Hate
Timo Stamm [EMAIL PROTECTED] wrote: I just wrote to the abuse department at dreamhost, telling them that your accusations are highly exaggerated. I included Xah's post, on which they based their reply. Maybe use your weekend to do some research? -- John MexIT: http://johnbokma.com/mexit/ personal page: http://johnbokma.com/ Experienced programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Databases in Python
Thank you very much, Steve. Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah's Edu Corner: Criticism vs Constructive Criticism
Good thing there's absolutely nothing happening in the world of functional programming... -- http://mail.python.org/mailman/listinfo/python-list
Why does bufsize=1 not work in subprocess.Popen ?
I read in the docs that bufsize=1 causes line buffering. (for subprocess.Popen) The following tiny program launches an executable file and then receives its output. That works, but I want to receive each line as it is ouput, not all of the lines at termination, which is what is happening. --- from subprocess import Popen, PIPE from os import remove, sep p = Popen(. + sep + myprogram, stdout=PIPE, bufsize=1) while(1): line = p.stdout.readline() # get next line print line, if line.count(terminator): break -- How can I get line buffering? Mitchell Timin -- I'm proud of http://ANNEvolve.sourceforge.net. If you want to write software, or articles, or do testing or research for ANNEvolve, let me know. Humans may know that my email address is: (but remove the 3 digit number) zenguy at shaw666 dot ca -- http://mail.python.org/mailman/listinfo/python-list
Re: Need help removing list elements.
On 30/04/2006 12:22 AM, Max Erickson wrote: [EMAIL PROTECTED] wrote in news:[EMAIL PROTECTED]: But this gives me IndexError: list out of range You are making the list shorter as you are iterating. By the time your index is at the end of the original list, it isn't that long any more. If you are hell-bent on conditionally deleting items from a list in situ, you need to do it backwards: for i in xrange(len(alist)-1, -1, -1): if not_interested(alist[i]): del alist[i] Creating a new list and appending the elements you want to keep avoids the problem. Or you can just use a list comprehension(untested): returned_lines=[line for line in open(lines.txt, 'rb') Call me crazy, but I wouldn't open the file in BINARY mode :-) if line != ] or just returned_lines=[line for line in open(lines.txt) if line] For a modicum of extra effort, the condition if line.strip() throws away lines containing only whitespace. However I don't see the point of creating a list of lines, then throwing out only *some* of the uninteresting ones. IMHO the OP might be better advised to read the file one line at a time, ignoring blank/empty/comment lines, then *validate* the remainder. Hint: with the semi-squished-list approach, you can't report the original line number of any erroneous line without extra effort. The OP might be even better advised to (read the source of, use) an existing config file parser module. Hope some of this helps, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Databases in Python
Petr Jakes wrote: Thank you very much, Steve. Happy to oblige. You did me a favor, as I had promised the students I would put the notes up on the net. Must remember to include them in the permanent site build process now :-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does bufsize=1 not work in subprocess.Popen ?
In [EMAIL PROTECTED], I. Myself wrote: I read in the docs that bufsize=1 causes line buffering. (for subprocess.Popen) The following tiny program launches an executable file and then receives its output. That works, but I want to receive each line as it is ouput, not all of the lines at termination, which is what is happening. From the Python side you can only control Python's input buffer but not the output buffer of the external program you are starting. I guess that programs buffers its output. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Can we create an_object = object() and add attribute like for a class?
Pierre Rouleau [EMAIL PROTECTED] wrote: Hi all, Is there any reason that under Python you cannot instantiate the object class and create any attributes like you would be able for a normal class? Yep: instances of type object do not have a __dict__ and therefore there is no place to put any attributes. This is necessary to allow ANY subclass of object, and thus any type whatsoever, to lack a per-instance __dict__ (and thus to save its per-instance memory costs), since by the principle of inheritance (known as Liskov substutition, or also as the IS-A rule) a subclass cannot _remove_ superclass attributes, so if the universal superclass had a __dict__ so would every type in Python. Being able to do it would seem a natural way of declaring namespaces. I find that ns = type('somename', (), dict(anattribute=23)) isn't too bad to make a namespace ns, though it has some undesirable issues (e.g., ns is implicitly callable, which may make little sense for a namespace). At any rate, any natural way of declaring a namespace SHOULD allow arbitrary named arguments in the instantiation call -- bending principles to give each instance of object a __dict__ would still not fix that, so that wouldn't do much. I think it's worth the minor bother to write out something like class Namespace(object): def __init__(self, **kwds): self.__dict__ = kwds and I generally go further anyway, by defining at least a repr that shows the attributes' names and values (very useful for debugging...). Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: self modifying code
On 2006-04-29, Robin Becker [EMAIL PROTECTED] wrote: When young I was warned repeatedly by more knowledgeable folk that self modifying code was dangerous. Is the following idiom dangerous or unpythonic? def func(a): global func, data data = somethingcomplexandcostly() def func(a): return simple(data,a) return func(a) It looks quite clever (a bit too clever ... :) It could be replaced by data = somethingcomplexandcostly() def func(a): return simple(data,a) but this always calculates data. Why not just: data = None def func(a): global data if not data: data = somethingcomplexandcostly() return simple(data, a) Or nicer to use a singleton perhaps than a global, perhaps something like this: class Func(object): exists = False def __init__(self): assert not Func.exists Func.exists = True self.data = None def simple(self, a): assert self.data is not None # ... do something with self.data presumably return something def __call__(self, a): if self.data is None: self.data = somethingcomplexandcostly() return self.simple(a) func = Func() func(a) -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to determine sequence ordering?
nikie wrote: Steven Bethard wrote: nikie wrote: Steven Bethard wrote: John Salerno wrote: If I want to make a list of four items, e.g. L = ['C', 'A', 'D', 'B'], and then figure out if a certain element precedes another element, what would be the best way to do that? Looking at the built-in list functions, I thought I could do something like: if L.index('A') L.index('D'): # do some stuff This is probably a pretty reasonable approach as long as you're not too worried about efficiency. It scans the list twice though, so if you start doing this with really big lists, it might be better to do something like: On average, it'll only have go through half the list twice, as it can break as soon as it finds the item it searches for. Don't think you can get any more efficient than that. Sure you can: a_index = None d_index = None for i, item in enumerate(L): if item == 'A': a_index = i elif item == 'D': d_index = i if a_index is not None and d_index is not None: break if a_index d_index: # do some stuff That goes through exactly the minimum number of elements. But it's probably slower than two .index() calls since .index() is coded in C. But timeit and see if you're interested. On my PC, calling index twice is 5 times faster. But let's just pretend for a moment Python code was compiled and optimized as well as C code. Ok, lets get comparable functions by writing them both in Python: - temp.py - def index(L, item): for i, x in enumerate(L): if x == item: return i return -1 def a_d_index(L): a_index = None d_index = None for i, item in enumerate(L): if item == 'A': a_index = i elif item == 'D': d_index = i if a_index is not None and d_index is not None: break return a_index, d_index --- $ python -m timeit -s import temp; L = ['C', 'A', 'D', 'B'] a = temp.index(L, 'A'); d = temp.index(L, 'D'); a d 10 loops, best of 3: 5.73 usec per loop $ python -m timeit -s import temp; L = ['C', 'A', 'D', 'B'] a, d = temp.a_d_index(L); a d 10 loops, best of 3: 3.75 usec per loop The a_d_index() function is definitely faster. I understand your point about comparison time, but in this case we're just comparing one element strings, so it's not so horrible. Sure, if you used strings that are more complicated to compare (or worse yet, you used your own custom objects with __cmp__ methods) you could provoke the kind of behavior you're looking for. But in this particular case, there really is some substantial overhead to Python's iterator protocol, and you can't just ignore that. Of course the moral of the story (as is the moral of all such threads) is that if you're really interested in speeding things up you need to start timing things. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Why does bufsize=1 not work in subprocess.Popen ?
Marc 'BlackJack' Rintsch wrote: In [EMAIL PROTECTED], I. Myself wrote: I read in the docs that bufsize=1 causes line buffering. (for subprocess.Popen) The following tiny program launches an executable file and then receives its output. That works, but I want to receive each line as it is ouput, not all of the lines at termination, which is what is happening. From the Python side you can only control Python's input buffer but not the output buffer of the external program you are starting. I guess that programs buffers its output. Ciao, Marc 'BlackJack' Rintsch That makes sense. I remember now that someone told me that Windows sends line-by-line only to the screen. To a pipe it sends buffers full. Thanks, Mitchell Timin -- I'm proud of http://ANNEvolve.sourceforge.net. If you want to write software, or articles, or do testing or research for ANNEvolve, let me know. Humans may know that my email address is: (but remove the 3 digit number) zenguy at shaw666 dot ca -- http://mail.python.org/mailman/listinfo/python-list
resume picking items from a previous list
I have a several list of songs that i pick from, lets, say that there are 10 songs in each list and there are 2 lists. For a time i pick from my songs, but i only play a few of the songs in that list... now my wife, Jessica Alba, comes home, and i start playing from Jessica's list of songs. After playing a few songs, Jessica, who needs her beauty sleep, goes to bed, and i start my play loop which starts picking from my songs again... The wrinkle: only now i want it to pick first from among the 6 songs yet not played from the first time around, and *then* when the list is exhausted, shuffle the whole original list of songs and start again. Here is some working but hilariously bad code that does most of this funny biz... I've gotten this far, but can't figure out how to get the loops to keep track of what was played and what wasn't and how to pick-up the list where it left off. I know this is a dumb thing to want to do, but you know, being married to bona-fide star is not easy. # --- #!/usr/bin/env python import random import os def shuffleloop(iterable): An iterator like itertools cycle, which returns elements from the iterable and saves a copy of each. When the iterable is exhausted, it return elements from the saved copy. The added wrinkle here is that the saved copy is randomly shuffled. Repeats indefinitely. saved = [] for element in iterable: yield element saved.append(element) while saved: random.shuffle(saved) for element in saved: yield element def playall_reload(startime, playdur, smpl_lst): '''a loop that shuffles and plays all sounds in a list. If the sequence is exhausted the list is reloaded, re-shuffled, and plyed through again. It does this as many times as needed to fill the time specified. Also returns the end of the last duration so that the begining of the next section can be fed to the next function or loop. ''' event = 0; incr = 0; lst_len = len(smpl_lst) random.shuffle(smpl_lst) smpl_loop = shuffleloop(smpl_lst) endpoint = startime + playdur while startime endpoint: sample = smpl_loop.next() splt = os.path.split(sample) # get the duration of the current soundfile # (hard wire it for now) #incr = DUR() dur = 10 #load the sample play it # # input(sample) # PLAY(startime, dur) # print event %d @ %.4f -- [%s] dur: %.4f % (event+1, startime, splt[1], dur) incr = dur startime = startime + incr event = event + 1 if (event lst_len): print \n\n*** Heads-up yo: the input sequence was not exhausted ***\n\n return startime def test(): kevins = ['/Users/kevin/snd/songs/loveisintheair.aif', '/Users/kevin/snd/songs/boymeetsgirl.aif', '/Users/kevin/snd/songs/yourcheatingheart.aif', '/Users/kevin/snd/songs/kindletheflame.aif', '/Users/kevin/snd/songs/mywifeissohot.aif', '/Users/kevin/snd/songs/haha.aif', '/Users/kevin/snd/songs/blueberryorstrawberry.aif', '/Users/kevin/snd/songs/didyoupaytheelectricbill.aif', '/Users/kevin/snd/songs/whereistheremote.aif', '/Users/kevin/snd/songs/youspenthowmuchforthoseshoes.aif'] jessicas = ['/Users/kevin/snd/quiet_songs/iloveu.aif', '/Users/kevin/snd/quiet_songs/uloveme.aif', '/Users/kevin/snd/quiet_songs/wearehappy.aif', '/Users/kevin/snd/quiet_songs/wearesad.aif', '/Users/kevin/snd/quiet_songs/letsbreakup.aif', '/Users/kevin/snd/quiet_songs/letsgetbacktogether.aif', '/Users/kevin/snd/quiet_songs/walkinthesunshine.aif', '/Users/kevin/snd/quiet_songs/iloveutruly.aif', '/Users/kevin/snd/quiet_songs/whosefootisthat.aif', '/Users/kevin/snd/quiet_songs/ohbaby.aif'] print one = playall_reload(1.00, 20.00, kevins) print two = playall_reload(one, 180, jessicas) print three = playall_reload(two, 40.00, kevins) if __name__ == '__main__': test() -- http://mail.python.org/mailman/listinfo/python-list
Re: self modifying code
John J. Lee wrote: Robin Becker [EMAIL PROTECTED] writes: When young I was warned repeatedly by more knowledgeable folk that self modifying code was dangerous. Is the following idiom dangerous or unpythonic? def func(a): global func, data data = somethingcomplexandcostly() def func(a): return simple(data,a) return func(a) 1. I don't think most people would call that self-modifying code. I won't try defining that term precisely because I know you'll just pick holes in my definition ;-) 2. The use of global func is just plain weird :-) 3. Peter Otten's version is OK, but how about this, using a closure instead of globals (UNTESTED) def make_func(): namespace = object() namespace.data = None def func(a): if namespace.data is None: namespace.data = somethingcomplexandcostly() return simple(namespace.data, a) return func func = make_func() Unfortunately, this doesn't work because you can add attributes to plain object instances: namespace = object() namespace.data = None Traceback (most recent call last): File interactive input, line 1, in ? AttributeError: 'object' object has no attribute 'data' Maybe you want something like: def make_func(): ... def func(a): ... if func.data is None: ... func.data = somethingcomplexandcostly() ... return simple(func.data, a) ... func.data = None ... return func ... func = make_func() def somethingcomplexandcostly(): ... print 'executing somethingcomplexandcostly' ... return 42 ... def simple(data, a): ... return data, a ... func(1) executing somethingcomplexandcostly (42, 1) func(2) (42, 2) STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Can we create an_object = object() and add attribute like for a class?
Alex Martelli wrote: Pierre Rouleau [EMAIL PROTECTED] wrote: Hi all, Is there any reason that under Python you cannot instantiate the object class and create any attributes like you would be able for a normal class? Yep: instances of type object do not have a __dict__ and therefore there is no place to put any attributes. This is necessary to allow ANY subclass of object, and thus any type whatsoever, to lack a per-instance __dict__ (and thus to save its per-instance memory costs), Makes sense. I was under the impresssion that instances of type object did have a __dict__ but was hidden for some reason. I should have known ... explicit is better than implicit... Being able to do it would seem a natural way of declaring namespaces. I find that ns = type('somename', (), dict(anattribute=23)) isn't too bad to make a namespace ns, though it has some undesirable issues (e.g., ns is implicitly callable, which may make little sense for a namespace). At any rate, any natural way of declaring a namespace SHOULD allow arbitrary named arguments in the instantiation call -- bending principles to give each instance of object a __dict__ would still not fix that, so that wouldn't do much. I think it's worth the minor bother to write out something like class Namespace(object): def __init__(self, **kwds): self.__dict__ = kwds and I generally go further anyway, by defining at least a repr that shows the attributes' names and values (very useful for debugging...). That's what I do too, but sometimes i just want to have a quick holder attribute in a class and am lazy to do it. I could declare one such class inside a module and import it but again, that means importing, name space of the module, etc... I can understand the design decision not to give object a __dict__, but I wonder if i'd be a good idea to have a class that derives from object and has a __dict__ to be in the standard library. I posted the original question because I run into this quite often and I just saw a post a little before mine (self modifying code) where the idiom was used. -- Pierre Rouleau -- http://mail.python.org/mailman/listinfo/python-list
Re: time conversions [hh:mm:ss.ms - sec(.ms)
timedelta looks to be just the ticket! bravo, thank you... i guess this must be pretty new to Python. Nice... more batteries included stuff... cheers, -kevin-- -- http://mail.python.org/mailman/listinfo/python-list
Re: Can we create an_object = object() and add attribute like for a class?
Pierre Rouleau [EMAIL PROTECTED] wrote: ... I can understand the design decision not to give object a __dict__, but I wonder if i'd be a good idea to have a class that derives from object and has a __dict__ to be in the standard library. I posted the original question because I run into this quite often and I just saw a post a little before mine (self modifying code) where the idiom was used. Yes, I do agree it would be a good idea. It's probably too late to add features to Python 2.5, but I think you should propose a PEP for 2.6. Standard library module containers seems to be a good place for the proposed namespace-type, but some discussion might help get some idea of a consensus about the type's name (is 'namespace' good enough? Is an __init__ taking arbitrary named arguments, and a __repr__ emitting them, all the functionality we need -- or should perhaps the type also expose some other methods delegating to the underlying __dict__, such as __len__ [[number of attributes]], update, __contains__, __iter__...?). Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate a sequence of random numbers that sum up to 1?
Anthony Liu [EMAIL PROTECTED] writes: OK, I actually just want to manually create Hidden Markov Models by randomly generating the initial state probabilities PI, OK, this sounds like you actually want to divide the unit interval up into pieces of varying sizes. Example (untested): n = 10 # number of pieces desired # Take the unit interval [0,1] and sprinkle in n-1 random points s = sorted([0,1] + [random() for i in xrange(n-1)]) # now find the size of each sub-interval and make a list r = [(s[i+1] - s[i]) for i in xrange(n)] print sum(r) # should be 1.0 within rounding error -- http://mail.python.org/mailman/listinfo/python-list
Re: midi input
http://www.mxm.dk/products/public/pythonmidi mxm rocks! i used to use it this to create midi files so i know it works... but now it has grown to big for my small brain, have no clue how to actually use it... i keep hoping for a small tutorial and some more docs, this partially due to the bizarre mysteries and dark science of the midi file format and how it actually works with time. I would love to be able to use this again... I just need to figure out how to change real human time into something that midi can use. If i could specify a tempo base (tempo of say 60) and have it go up a scale in quarter notes or something.. i could maybe figure it out from there. I just want to be able to specify notes like csound or something does: start_time, duration, freq etc but i think that this also will do realtime stuff and you can monitor/filter/pipe incoming midi data as well. I just don't know how to do that either another possibility is to look at csound or cmix or pd or supercollider all of which are free, mostly open source, and available on linux good luck on your quest! -- http://mail.python.org/mailman/listinfo/python-list
Re: String Exceptions (PEP 352)
bruno at modulix [EMAIL PROTECTED] writes: What's wrong with: assert foo and bar and i 10, \ if foo and bar i must not be greater than 10 It doesn't necessarily do anything. With optimization enable, assert is a no-op. -- http://mail.python.org/mailman/listinfo/python-list
Re: Can we create an_object = object() and add attribute like fora class?
Pierre Rouleau wrote: I can understand the design decision not to give object a __dict__, but I wonder if i'd be a good idea to have a class that derives from object and has a __dict__ to be in the standard library. so you can replace one line of code in some of your programs with an import statement ? cute. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to determine sequence ordering?
John Salerno wrote: If I want to make a list of four items, e.g. L = ['C', 'A', 'D', 'B'], and then figure out if a certain element precedes another element, what would be the best way to do that? Looking at the built-in list functions, I thought I could do something like: if L.index('A') L.index('D'): # do some stuff This actually performs pretty well since list.index is implemented in C. The obvious (to me) implementation of: def before(lst, a, b): for x in lst: if x == a: return True if x == b: return False runs about 10-50 times faster than the double index method if I use psyco. Without psyco, it ends up being faster for the cases where a or b appears early on in the list, and the other appears towards the end. -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to determine sequence ordering?
Steven Bethard wrote: nikie wrote: Steven Bethard wrote: nikie wrote: Steven Bethard wrote: John Salerno wrote: If I want to make a list of four items, e.g. L = ['C', 'A', 'D', 'B'], and then figure out if a certain element precedes another element, what would be the best way to do that? Looking at the built-in list functions, I thought I could do something like: if L.index('A') L.index('D'): # do some stuff This is probably a pretty reasonable approach as long as you're not too worried about efficiency. It scans the list twice though, so if you start doing this with really big lists, it might be better to do something like: On average, it'll only have go through half the list twice, as it can break as soon as it finds the item it searches for. Don't think you can get any more efficient than that. Sure you can: a_index = None d_index = None for i, item in enumerate(L): if item == 'A': a_index = i elif item == 'D': d_index = i if a_index is not None and d_index is not None: break if a_index d_index: # do some stuff That goes through exactly the minimum number of elements. But it's probably slower than two .index() calls since .index() is coded in C. But timeit and see if you're interested. On my PC, calling index twice is 5 times faster. But let's just pretend for a moment Python code was compiled and optimized as well as C code. Ok, lets get comparable functions by writing them both in Python: That's changing the subject, and you know that. The OP asked whether using L.index('A') L.index('D') was a good (pythonic, efficient) idea. It is. Maybe it wouldn't be efficient if List.index was implemented in python (because, as I have already said in my previous post, looping through an enumerate-object in python is more complex than a simple C-loop), but it is actually implemented in C. Even if you wrote a C function that tried to do all the comparisons in one sweep through the list, I'm willing to bet it won't be faster than the OP's suggestion on the average (at least for moderate-sized lists, otherwise, processing the list in blocks, using the cache more efficiently might be a good idea). That's what this thread was all about. Now, I don't really see what you are trying to say: Are you still trying to convince the OP that he should write a Python function like one of those you suggested, for performance reasons? If not, I must have misunderstood your last posts, and apologize for repeating the obvious ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to determine sequence ordering?
nikie wrote: That's what this thread was all about. Now, I don't really see what you are trying to say: Are you still trying to convince the OP that he should write a Python function like one of those you suggested, for performance reasons? Sure, if it really matters. Code it in C, and you can do better than .index(). But I don't think it really matters. ;-) STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to determine sequence ordering?
Steven Bethard wrote: John Salerno wrote: If I want to make a list of four items, e.g. L = ['C', 'A', 'D', 'B'], and then figure out if a certain element precedes another element, what would be the best way to do that? Looking at the built-in list functions, I thought I could do something like: if L.index('A') L.index('D'): # do some stuff This is probably a pretty reasonable approach Just to clarify, because there seems to be some confusion. I would absolutely go with this approach unless you have profiled and found it to be a bottleneck. It's clear, concise, and quite fast. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to determine sequence ordering?
Steven Bethard wrote: Ok, lets get comparable functions by writing them both in Python: First of all, your functions aren't quite comparable. The first index takes the value to locate as a variable, while the second has both values hard-coded as literals. Changing the second one to index2(L, a, b) makes a slight but not significant difference in the timings. Secondly, the lists you tested with are artificially short. As you increase the size of the list, the difference lessens to unimportance: $ python -m timeit -s import temp; L = ['x'] * 500 + ['C', 'A', 'D', 'B'] a, d = temp.index2(L,'A','D'); a d 1000 loops, best of 3: 227 usec per loop $ python -m timeit -s import temp; L = ['x'] * 500 + ['C', 'A', 'D', 'B'] a = temp.index1(L, 'A'); d = temp.index1(L, 'D'); a d 1000 loops, best of 3: 236 usec per loop Third, the target values are very close together in those lists. If there's a large difference in their positions, then the two-in-one-pass algorithm becomes much slower: $ python -m timeit -s import temp; L = ['C','A'] + ['x'] * 500 + ['D', 'B'] a = temp.index1(L, 'A'); d = temp.index1(L, 'D'); a d 1 loops, best of 3: 120 usec per loop $ python -m timeit -s import temp; L = ['C','A'] + ['x'] * 500 + ['D', 'B'] a, d = temp.index2(L,'A','D'); a d 1000 loops, best of 3: 267 usec per loop Remember kids: 1. Numbers can show anything 2. Know your data set 3. Premature optimizations are evil -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to determine sequence ordering?
Edward Elliott wrote: Remember kids: 1. Numbers can show anything 2. Know your data set 3. Premature optimizations are evil Amen. =) STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Can we create an_object = object() and add attribute like fora class?
Fredrik Lundh wrote: Pierre Rouleau wrote: I can understand the design decision not to give object a __dict__, but I wonder if i'd be a good idea to have a class that derives from object and has a __dict__ to be in the standard library. so you can replace one line of code in some of your programs with an import statement ? ok... I should have said something like the built-in object type instead of standard library... -- Pierre Rouleau -- http://mail.python.org/mailman/listinfo/python-list
Re: best way to determine sequence ordering?
John Salerno wrote: If I want to make a list of four items, e.g. L = ['C', 'A', 'D', 'B'], and then figure out if a certain element precedes another element, what would be the best way to do that? Looking at the built-in list functions, I thought I could do something like: if L.index('A') L.index('D'): # do some stuff Ok, since, as happens some times, the discussion here has gotten extremely sidetracked from the original question, as a public service ;) I thought I'd give a brief summary of the options discussed and when they might be useful: * The original:: if L.index('A') L.index('D'): # do some stuff If you're doing exactly one comparison, this is probably your best bet in most cases as .index() is coded in C. It's clear, concise and correct. * Justin Azoff's before():: def before(lst, a, b): for x in lst: if x == a: return True if x == b: return False if before(L, 'A', 'D'): # do some stuff You might gain a bit from this version if one of the elements you're looking for appears early in the list. It only iterates through the list once, but performs two comparisons each time, so you'll only gain from it if you comparisons aren't too costly (e.g. you're comparing single character strings). * building a dict of indicies:: positions = dict((item, i) for i, item in enumerate(L)) if positions['A'] positions['D']: # do some stuff You'll only get a gain from this version if you need to do several comparisons instead of just one. And most importantly, as Edward Elliot put it: Remember kids: 1. Numbers can show anything 2. Know your data set 3. Premature optimizations are evil HTH, STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Can we create an_object = object() and add attribute like fora class?
Pierre Rouleau [EMAIL PROTECTED] wrote: Fredrik Lundh wrote: Pierre Rouleau wrote: I can understand the design decision not to give object a __dict__, but I wonder if i'd be a good idea to have a class that derives from object and has a __dict__ to be in the standard library. so you can replace one line of code in some of your programs with an import statement ? ok... I should have said something like the built-in object type instead of standard library... I'm -1 on adding a new built-in for this functionality -- it's just not important enough to warrant a built-in (there are already too many built-ins!). Putting a namespace type in the standard library could provide enough helpful functionality to make an import well warranted, so I'm +1 on adding such a type to the standard library (in 2.6 -- I think it's too late for 2.6). Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: resume picking items from a previous list
kpp9c wrote: I have a several list of songs that i pick from, lets, say that there are 10 songs in each list and there are 2 lists. For a time i pick from my songs, but i only play a few of the songs in that list... now my wife, Jessica Alba, comes home, and i start playing from Jessica's list of songs. After playing a few songs, Jessica, who needs her beauty sleep, goes to bed, and i start my play loop which starts picking from my songs again... The wrinkle: only now i want it to pick first from among the 6 songs yet not played from the first time around, and *then* when the list is exhausted, shuffle the whole original list of songs and start again. Here is some working but hilariously bad code that does most of this funny biz... I've gotten this far, but can't figure out how to get the loops to keep track of what was played and what wasn't and how to pick-up the list where it left off. I know this is a dumb thing to want to do, but you know, being married to bona-fide star is not easy. # --- #!/usr/bin/env python import random import os def shuffleloop(iterable): An iterator like itertools cycle, which returns elements from the iterable and saves a copy of each. When the iterable is exhausted, it return elements from the saved copy. The added wrinkle here is that the saved copy is randomly shuffled. Repeats indefinitely. saved = [] for element in iterable: yield element saved.append(element) while saved: random.shuffle(saved) for element in saved: yield element def playall_reload(startime, playdur, smpl_lst): '''a loop that shuffles and plays all sounds in a list. If the sequence is exhausted the list is reloaded, re-shuffled, and plyed through again. It does this as many times as needed to fill the time specified. Also returns the end of the last duration so that the begining of the next section can be fed to the next function or loop. ''' event = 0; incr = 0; lst_len = len(smpl_lst) random.shuffle(smpl_lst) smpl_loop = shuffleloop(smpl_lst) endpoint = startime + playdur while startime endpoint: sample = smpl_loop.next() splt = os.path.split(sample) # get the duration of the current soundfile # (hard wire it for now) #incr = DUR() dur = 10 #load the sample play it # # input(sample) # PLAY(startime, dur) # print event %d @ %.4f -- [%s] dur: %.4f % (event+1, startime, splt[1], dur) incr = dur startime = startime + incr event = event + 1 if (event lst_len): print \n\n*** Heads-up yo: the input sequence was not exhausted ***\n\n return startime def test(): kevins = ['/Users/kevin/snd/songs/loveisintheair.aif', '/Users/kevin/snd/songs/boymeetsgirl.aif', '/Users/kevin/snd/songs/yourcheatingheart.aif', '/Users/kevin/snd/songs/kindletheflame.aif', '/Users/kevin/snd/songs/mywifeissohot.aif', '/Users/kevin/snd/songs/haha.aif', '/Users/kevin/snd/songs/blueberryorstrawberry.aif', '/Users/kevin/snd/songs/didyoupaytheelectricbill.aif', '/Users/kevin/snd/songs/whereistheremote.aif', '/Users/kevin/snd/songs/youspenthowmuchforthoseshoes.aif'] jessicas = ['/Users/kevin/snd/quiet_songs/iloveu.aif', '/Users/kevin/snd/quiet_songs/uloveme.aif', '/Users/kevin/snd/quiet_songs/wearehappy.aif', '/Users/kevin/snd/quiet_songs/wearesad.aif', '/Users/kevin/snd/quiet_songs/letsbreakup.aif', '/Users/kevin/snd/quiet_songs/letsgetbacktogether.aif', '/Users/kevin/snd/quiet_songs/walkinthesunshine.aif', '/Users/kevin/snd/quiet_songs/iloveutruly.aif', '/Users/kevin/snd/quiet_songs/whosefootisthat.aif', '/Users/kevin/snd/quiet_songs/ohbaby.aif'] print one = playall_reload(1.00, 20.00, kevins) print two = playall_reload(one, 180, jessicas) print three = playall_reload(two, 40.00, kevins) if __name__ == '__main__': test() I didn't read your code, but a class might make it simpler: class Playah(object): def __init__(self, playlist): self.playlist = playlist self.reset() def reset(self): self._order = randrange(len(self.playlist)) self._i = 0 def next(): song = self.playlist(self._i) self._i += 1 if self._i len(self.playlist): self.reset() return song You could probably
how not use memmove when insert a object in the list
Hi : python list object like a stl vector, if insert a object in the front or the middle of it, all the object after the insert point need to move backward. look at this code ( in python 2.4.3) static int ins1(PyListObject *self, int where, PyObject *v) { int i, n = self-ob_size; PyObject **items; if (v == NULL) { PyErr_BadInternalCall(); return -1; } if (n == INT_MAX) { PyErr_SetString(PyExc_OverflowError, cannot add more objects to list); return -1; } if (list_resize(self, n+1) == -1) return -1; if (where 0) { where += n; if (where 0) where = 0; } if (where n) where = n; items = self-ob_item; for (i = n; --i = where; ) /// here, why not use memmove? it would be more speed then this loop. items[i+1] = items[i]; Py_INCREF(v); items[where] = v; return 0; } Kyo. -- http://mail.python.org/mailman/listinfo/python-list
Re: resume picking items from a previous list
James Stroud wrote: kpp9c wrote: I have a several list of songs that i pick from, lets, say that there are 10 songs in each list and there are 2 lists. For a time i pick from my songs, but i only play a few of the songs in that list... now my wife, Jessica Alba, comes home, and i start playing from Jessica's list of songs. After playing a few songs, Jessica, who needs her beauty sleep, goes to bed, and i start my play loop which starts picking from my songs again... The wrinkle: only now i want it to pick first from among the 6 songs yet not played from the first time around, and *then* when the list is exhausted, shuffle the whole original list of songs and start again. Here is some working but hilariously bad code that does most of this funny biz... I've gotten this far, but can't figure out how to get the loops to keep track of what was played and what wasn't and how to pick-up the list where it left off. I know this is a dumb thing to want to do, but you know, being married to bona-fide star is not easy. # --- #!/usr/bin/env python import random import os def shuffleloop(iterable): An iterator like itertools cycle, which returns elements from the iterable and saves a copy of each. When the iterable is exhausted, it return elements from the saved copy. The added wrinkle here is that the saved copy is randomly shuffled. Repeats indefinitely. saved = [] for element in iterable: yield element saved.append(element) while saved: random.shuffle(saved) for element in saved: yield element def playall_reload(startime, playdur, smpl_lst): '''a loop that shuffles and plays all sounds in a list. If the sequence is exhausted the list is reloaded, re-shuffled, and plyed through again. It does this as many times as needed to fill the time specified. Also returns the end of the last duration so that the begining of the next section can be fed to the next function or loop. ''' event = 0; incr = 0; lst_len = len(smpl_lst) random.shuffle(smpl_lst) smpl_loop = shuffleloop(smpl_lst) endpoint = startime + playdur while startime endpoint: sample = smpl_loop.next() splt = os.path.split(sample) # get the duration of the current soundfile # (hard wire it for now) #incr = DUR() dur = 10 #load the sample play it # # input(sample) # PLAY(startime, dur) # print event %d @ %.4f -- [%s] dur: %.4f % (event+1, startime, splt[1], dur) incr = dur startime = startime + incr event = event + 1 if (event lst_len): print \n\n*** Heads-up yo: the input sequence was not exhausted ***\n\n return startime def test(): kevins = ['/Users/kevin/snd/songs/loveisintheair.aif', '/Users/kevin/snd/songs/boymeetsgirl.aif', '/Users/kevin/snd/songs/yourcheatingheart.aif', '/Users/kevin/snd/songs/kindletheflame.aif', '/Users/kevin/snd/songs/mywifeissohot.aif', '/Users/kevin/snd/songs/haha.aif', '/Users/kevin/snd/songs/blueberryorstrawberry.aif', '/Users/kevin/snd/songs/didyoupaytheelectricbill.aif', '/Users/kevin/snd/songs/whereistheremote.aif', '/Users/kevin/snd/songs/youspenthowmuchforthoseshoes.aif'] jessicas = ['/Users/kevin/snd/quiet_songs/iloveu.aif', '/Users/kevin/snd/quiet_songs/uloveme.aif', '/Users/kevin/snd/quiet_songs/wearehappy.aif', '/Users/kevin/snd/quiet_songs/wearesad.aif', '/Users/kevin/snd/quiet_songs/letsbreakup.aif', '/Users/kevin/snd/quiet_songs/letsgetbacktogether.aif', '/Users/kevin/snd/quiet_songs/walkinthesunshine.aif', '/Users/kevin/snd/quiet_songs/iloveutruly.aif', '/Users/kevin/snd/quiet_songs/whosefootisthat.aif', '/Users/kevin/snd/quiet_songs/ohbaby.aif'] print one = playall_reload(1.00, 20.00, kevins) print two = playall_reload(one, 180, jessicas) print three = playall_reload(two, 40.00, kevins) if __name__ == '__main__': test() I didn't read your code, but a class might make it simpler: class Playah(object): def __init__(self, playlist): self.playlist = playlist self.reset() def reset(self): self._order = randrange(len(self.playlist)) self._i = 0 def next(): song = self.playlist(self._i) self._i += 1 if self._i len(self.playlist): self.reset() return song You could probably make it an iterable if you tried. James Oops, I meant that self._order = randrange(len(self.playlist)) should be self._order = range(len(self.playlist)) random.shuffle(self._order) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles,