[ANNOUNCE] PyGtkSourceView 2.7.0 - unstable
I am pleased to announce version 2.7.0 of the Gtksourceview Python bindings. Once the mirrors have sync correctly it will be available at: http://ftp.gnome.org/pub/GNOME/sources/pygtksourceview/2.7/ The bindings are updated with the new Gtksourceview API News in 2.7.0 = o Add new 2.8.0 gtksourceview API. (Gian Mario) o Some misc bug fix (Gian Mario) o Fix build with libtool 2.x. (Gian Mario) o Autogenerate Changelog from git logs (Gian Mario) Blurb: == gtksourceview is a library that provides a widget for source code display and editing, derived from Gtk's TextView, and used by gedit and nemiver, among others. gtksourceview has recently been released 2.7.3 PyGtksourceview requires: = o Gtksourceview = 2.3.0 o PyGObject = 2.15.2 o PyGTK = 2.8.0 Bug reports should go to: http://bugzilla.gnome.org/browse.cgi?product=pygtksourceview cheers -- Gian Mario Tagliaretti GNOME Foundation member gia...@gnome.org -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
Re: define class over 2 files
On Mon, 17 Aug 2009 21:45:57 -0700, naveen wrote: Is it possible to split up a class definition over multiple files? Not exactly, but you can do variations of this: In file A.py, create: class Parent: def method(self): return Method In file B.py, do this: import A class Child(B.parent): def another_method(self): return Another Method Now your class Child has two methods, method() and another_method(). Similarly, you can do this: # File A.py def function(x, y): return x+y # or something more complicated # File B.py import A def MyClass(object): def func(self, x, y): return A.function(x, y) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: XML parsing with python
inder wrote: On Aug 17, 8:31 pm, John Posner jjpos...@optimum.net wrote: Use the iterparse() function of the xml.etree.ElementTree package. http://effbot.org/zone/element-iterparse.htm http://codespeak.net/lxml/parsing.html#iterparse-and-iterwalk Stefan iterparse() is too big a hammer for this purpose, IMO. How about this: from xml.etree.ElementTree import ElementTree tree = ElementTree(None, myfile.xml) for elem in tree.findall('//book/title'): print elem.text -John Thanks for the prompt reply . I feel let me try using iterparse. Will it be slower compared to SAX parsing ... ultimately I will have a huge xml file to parse ? If you use the cElementTree module, it may even be faster. Another question , I will also need to validate my xml against xsd . I would like to do this validation through the parsing tool itself . In that case, you can use lxml instead of ElementTree. http://codespeak.net/lxml/ Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: XML parsing with python
John Posner wrote: Use the iterparse() function of the xml.etree.ElementTree package. iterparse() is too big a hammer for this purpose, IMO. How about this: from xml.etree.ElementTree import ElementTree tree = ElementTree(None, myfile.xml) for elem in tree.findall('//book/title'): print elem.text Is that really so much better than an iterparse() version? from xml.etree.ElementTree import ElementTree for _, elem in ElementTree.iterparse(myfile.xml): if elem.tag == 'book': print elem.findtext('title') elem.clear() Stefan -- http://mail.python.org/mailman/listinfo/python-list
Changing Python Opcodes
Hi, I know this is not the best way to do it. But I have to do it at least to make it *hard* to decompile the python bytecode. I want to distribute a software written in Python without the source. So I compiled Python from source changing some opcode values (Taking care of HAVE_ARGUMENT value) and distributed with the .pyc files. It did compile but when I'm installing additional python modules using easy_install, the import fails with a segmentation fault. It worked in a 32 bit Centos 5.2 but not on 64bit Centos 5.2. I am using python 2.5.4 source. I changed only the Include/opcode.py source with my jumbled opcode values. Was I correct here ? I would like to know what all changes to be made as to successfully compile a custom python with different opcode values ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting DD MM YYYY into YYYY-MM-DD?
Thanks everyone for the help. This script is just a one-shot thingie on my work host, not as a web script or anything professional. On Mon, 17 Aug 2009 17:05:28 -0700 (PDT), Jonathan Gardner jgard...@jonathangardner.net wrote: Unfortunately, there isn't any string to date parsers in the built- ins. Not to worry, though, since writing your own is easy, especially if you use regular expressions from the re module. I suggest using an RE such as: r(?Pdate\d+)\s+(?Pmonth\w+)\s+(?Pyear\d+) I've never seen regexes like this. I'm curious to know what those mean: r = Unicode? (?Pdate = ? means that it shouldn't be greedy, what about Pdate? -- http://mail.python.org/mailman/listinfo/python-list
Re: define class over 2 files
Is it possible to split up a class definition over multiple files? Not exactly, but you can do variations of this: ... [subclass a class] Steven Thanks Steven. I guess I will just preprocess the script: class.sh cat partA.py class.py cat partB class.py python class.py /class.sh -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting DD MM YYYY into YYYY-MM-DD?
Gilles Ganault nos...@nospam.com writes: Thanks everyone for the help. This script is just a one-shot thingie on my work host, not as a web script or anything professional. On Mon, 17 Aug 2009 17:05:28 -0700 (PDT), Jonathan Gardner jgard...@jonathangardner.net wrote: r(?Pdate\d+)\s+(?Pmonth\w+)\s+(?Pyear\d+) I've never seen regexes like this. I'm curious to know what those mean: Luckily, you have access to the documentation to find out. r = Unicode? URL:http://docs.python.org/reference/lexical_analysis.html#string-literals (?Pdate = ? means that it shouldn't be greedy, what about Pdate? URL:http://docs.python.org/library/re#regular-expression-syntax -- \ “We reserve the right to serve refuse to anyone.” —restaurant, | `\ Japan | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: define class over 2 files
naveen naveen.g...@gmail.com writes: I guess I will just preprocess the script: class.sh cat partA.py class.py cat partB class.py python class.py /class.sh This, to me, is a programming smell; not necessarily bad, but an indicator of bad practice. What is the problem you're trying to solve? I'll wager there are better ways to address it. -- \ “Laugh and the world laughs with you; snore and you sleep | `\alone.” —anonymous | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing Python Opcodes
Sreejith K schrieb: Hi, I know this is not the best way to do it. But I have to do it at least to make it *hard* to decompile the python bytecode. I want to distribute a software written in Python without the source. So I compiled Python from source changing some opcode values (Taking care of HAVE_ARGUMENT value) and distributed with the .pyc files. It did compile but when I'm installing additional python modules using easy_install, the import fails with a segmentation fault. It worked in a 32 bit Centos 5.2 but not on 64bit Centos 5.2. I am using python 2.5.4 source. I changed only the Include/opcode.py source with my jumbled opcode values. Was I correct here ? I would like to know what all changes to be made as to successfully compile a custom python with different opcode values ? As you are the one who modified your Python, you are the one responsible for debugging that - noone else can. Did you try installing the egg *without* pyc-files in there? Because naturally those shouldn't work. They shouldn't crash the interpreter either, but then again - you *did* modify it. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing Python Opcodes
On Aug 18, 12:19 pm, Diez B. Roggisch de...@nospam.web.de wrote: Did you try installing the egg *without* pyc-files in there? Because naturally those shouldn't work. They shouldn't crash the interpreter either, but then again - you *did* modify it. Hi Diez, thanks for the immediate reply :) I installed the setuptools using ez_setup.py script. Then I used the easy_install to install additional modules. When importing the installed modules segfault occurs. The module I installed was TurboGears. Then I thought that it happened maybe because the easy_install script is downloading eggs for original python (I'm not sure if it is what easy_install is doing). So I also tried to install the module by downloading all the dependencies (tar.gz files) and building it. Even then segfault occured. Is there any problem in changing only the opcodes.py file ? I did something horribly wrong here. Hope someone will help... -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting DD MM YYYY into YYYY-MM-DD?
On Tue, 18 Aug 2009 17:10:50 +1000, Ben Finney ben+pyt...@benfinney.id.au wrote: Luckily, you have access to the documentation to find out. I never used groups before. Thanks for showing me. At this point, the script is almost done, but the regex fails if the month contains accented characters (eg. Août, but fine if eg. Jan). Adding a line to load the French locale doesn't help :-/ Any idea what I could do to keep the regex happy? Thank you. == import re import apsw import locale #In case error due to accent in month name, but no soup 4 U locale.setlocale(locale.LC_ALL, 'FR') connection=apsw.Connection(test.sqlite) cursor=connection.cursor() re_inscription = re.compile(r(?Pdate\d+)\s+(?Pmonth\w+)\s+(?Pyear\d+)) sql = 'SELECT id,dateinscription,dateconnexion FROM mytable' rows=list(cursor.execute(sql)) for row in rows: dateinscription = row[1] dateconnexion = row[2] #Prints OK print dateinscription m = re_inscription.search(dateinscription) if m: day = m.group(date) month = m.group(month) year = m.group(year) print %s-%s-%s % (year,month,day) else: print No go == -- http://mail.python.org/mailman/listinfo/python-list
Re: Data visualization in Python
Am 2009-08-17 21:10, schrieb kj: I'm looking for a good Python package for visualizing scientific/statistical data. (FWIW, the OS I'm interested in is Mac OS X). The users of this package will be experimental biologists with little programming experience (but currently learning Python). SciDAVis is a free application for Scientific Data Analysis and Visualization. http://scidavis.sourceforge.net/ Veusz is a scientific plotting and graphing package written in Python. http://home.gna.org/veusz/ Open source data visualization and analysis for novice and experts. Data mining through visual programming or Python scripting. Extensions for bioinformatics and text mining. Comprehensive, flexible and fast. http://www.ailab.si/orange/ (I normally visualize data using R or Mathematica, but I don't want to saddle these novices with the task of learning yet another language.) hth Herbert -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting DD MM YYYY into YYYY-MM-DD?
Could you let me know which platform this is on (Windows, *nix)? It may be a locale encoding issue -- the locale.setlocale() function allows the second argument to be a tuple of (locale_code, encoding), as below: locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) Since this is for a one-shot (and presumably threading-agnostic) program, and a fairly trivially formatted date-string, I would suggest using datetime.strptime (http://docs.python.org/library/datetime.html#datetime.datetime.strptime) and not regular expressions (which IIRC have Issues with non-ASCII characters). Rami Chowdhury Ninety percent of everything is crap. -- Sturgeon's Law 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Tuesday 18 August 2009 00:49:41 Gilles Ganault wrote: On Tue, 18 Aug 2009 17:10:50 +1000, Ben Finney ben+pyt...@benfinney.id.au wrote: Luckily, you have access to the documentation to find out. I never used groups before. Thanks for showing me. At this point, the script is almost done, but the regex fails if the month contains accented characters (eg. Août, but fine if eg. Jan). Adding a line to load the French locale doesn't help :-/ Any idea what I could do to keep the regex happy? Thank you. == import re import apsw import locale #In case error due to accent in month name, but no soup 4 U locale.setlocale(locale.LC_ALL, 'FR') connection=apsw.Connection(test.sqlite) cursor=connection.cursor() re_inscription = re.compile(r(?Pdate\d+)\s+(?Pmonth\w+)\s+(?Pyear\d+)) sql = 'SELECT id,dateinscription,dateconnexion FROM mytable' rows=list(cursor.execute(sql)) for row in rows: dateinscription = row[1] dateconnexion = row[2] #Prints OK print dateinscription m = re_inscription.search(dateinscription) if m: day = m.group(date) month = m.group(month) year = m.group(year) print %s-%s-%s % (year,month,day) else: print No go == -- http://mail.python.org/mailman/listinfo/python-list
Mercurial migration: help needed
This is a repost from two weeks ago. It didn't get much feedback last time. I still keep trying, reposting to python-list also this time. In this thread, I'd like to collect things that ought to be done but where Dirkjan has indicated that he would prefer if somebody else did it. Item 1 -- The first item is build identification. If you want to work on this, please either provide a patch (for trunk and/or py3k), or (if you are a committer) create a subversion branch. It seems that Barry and I agree that for the maintenance branches, sys.subversion should be frozen, so we need actually two sets of patches: one that removes sys.subversion entirely, and the other that freezes the branch to the respective one, and freezes the subversion revision to None. The patch should consider what Dirkjan proposes as the branching strategy: clones to separate 2.x and 3.x, as well as for features, and branches with the clones for releases and maintenance (see the PEP for details). Anybody working on this should have good knowledge of the Python source code, Mercurial, and either autoconf or Visual Studio (preferably both). Item 2 -- The second item is line conversion hooks. Dj Gilcrease has posted a solution which he considers a hack himself. Mark Hammond has also volunteered, but it seems some volunteer needs to be in charge, keeping track of a proposed solution until everybody agrees that it is a good solution. It may be that two solutions are necessary: a short-term one, that operates as a hook and has limitations, and a long-term one, that improves the hook system of Mercurial to implement the proper functionality (which then might get shipped with Mercurial in a cross-platform manner). Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting DD MM YYYY into YYYY-MM-DD?
On Tue, 18 Aug 2009 01:11:20 -0700, Rami Chowdhury rami.chowdh...@gmail.com wrote: Could you let me know which platform this is on (Windows, *nix)? It may be a locale encoding issue -- the locale.setlocale() function allows the second argument to be a tuple of (locale_code, encoding), as below: locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) It's on XP, and I'm using ActivePython 2.5.1.1. http://www.activestate.com/activepython/ Python doesn't like the above: #locale.Error: unsupported locale setting locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) Maybe it was introduced in more recent versions of Python? Since this is for a one-shot (and presumably threading-agnostic) program, and a fairly trivially formatted date-string, I would suggest using datetime.strptime (http://docs.python.org/library/datetime.html#datetime.datetime.strptime) and not regular expressions (which IIRC have Issues with non-ASCII characters). If the regex library can only handle basic latin characters, I'll wait until a script I'm running is done, and I'll upgrade to the 2.6.2.2 to see how it goes. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] Mercurial migration: help needed
On Tue, Aug 18, 2009 at 10:12, Martin v. Löwismar...@v.loewis.de wrote: In this thread, I'd like to collect things that ought to be done but where Dirkjan has indicated that he would prefer if somebody else did it. I think the most important item here is currently the win32text stuff. Mark Hammond said he would work on this; Mark, when do you have time for this? Then I could set apart some time for it as well. Have stalled a bit on the fine-grained branch processing, hope to move that forward tomorrow. Cheers, Dirkjan -- http://mail.python.org/mailman/listinfo/python-list
conversion of Python object to perl object
Hi, I have to call a perl method which takes a hash as its argument from a python module. Is there a way to convert python dictionary to perl hash ( not hash ref)? Thanks, Srini See the Web#39;s breaking stories, chosen by people like you. Check out Yahoo! Buzz. http://in.buzz.yahoo.com/ -- http://mail.python.org/mailman/listinfo/python-list
sub-list extraction, logical indexation
Hello Everyone, I would like to know if it is possible to extract a sub-list from a list ? typically if : L =[[1, 2, 3],[4, 5, 6],[3] ] How to extract easily the elements 0 and 2 of L in order to get : L2 =[[1, 2, 3],[3] ] Moreover, I would like to know if it is possible to use logical indexation such that : index = [ True, False, True] L2 = L or usual indexation, something like index=[0, 2] L2 = L I tried, but failed... Thanks for your help Pierre -- http://mail.python.org/mailman/listinfo/python-list
Re: zip codes
On 2009-08-17, Sjoerd Mullender sjo...@acm.org wrote: Also in The Netherlands, ZIP codes are much more fine-grained than in some other countries: ZIP code plus house number together are sufficient to uniquely identify an address. I.e. you don't need the street name. E.g., my work address has ZIP code 1098 XG and house number 123, so together they indicate that I work at Science Park 123, Amsterdam. In other words, a simple city - ZIP mapping is not sufficient. Same here in the US. A 5-digit zip code narrows it down to a neghborhood within a city, and a full 9-digit zip code is shared with perhaps 5-10 houses -- generally I believe it identifies one side of a one-block section of a street in a single-family-home residential area. In apartment or office buildings a 9-digit zip code generally identifies a specific floor in a specific building. Most companies of any size have their own zip code (or codes). My company only has ~40 employees, and we have our own unique zip code. -- Grant Edwards grante Yow! Here I am at the flea at market but nobody is buying visi.commy urine sample bottles ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Strongly typed list
هاني الموصلي schrieb: Please could you lead me to a way or a good IDE that makes developing huge projects in python more easier than what i found.Now i am using eclips. Actually it is very hard to remember all my classes methods and attributes or copy and paste them each time. Thanks very much for your interest Hani Almousli. There are many really big projects written in Python - none of them with the aid of intelli-sense. What python lacks in that respect due to it's dynamic typing, it more than compensates by being faster to develop and having to write much less code. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Xah's Edu Corner: The importance of syntax notations.
http://www.stephenwolfram.com/publications/recent/mathml/index.html i was trying to find the publication date and context, but didn't find it last time after a couple min. Yesterday, on rereading, i did. The article in question is: « Mathematical Notation: Past and Future (2000) Stephen Wolfram October 20, 2000 Transcript of a keynote address presented at MathML and Math on the Web: MathML International Conference 2000 » so, it's a speech for MathML conf in 2000. so, this explains the error on the plimpton 322. The latest discovery on that is published in 2002 and later. the date of this speech also explains parts of the writings about some mysterious “fundamental science work”, which now we know is his controversial book A New Kind Of Science (2002). Xah ∑ http://xahlee.org/ ☄ -- Xah Lee wrote: Personally, particular interesting info i've learned is that, for all my trouble in the past decade expressing problems of traditional math notation, i learned from his article this single-phrase summary: “traditional math notation lacks a grammar”. The article is somewhat disappointing though. I was expecting he'd go into some details about the science of math notations, or, as he put it aptly: “linguistics of math notations”. However, he didn't touch the subject, except saying that it haven't been studied. upon a more detailed reading of Stephen's article, i discovered some errors. On this page:http://www.stephenwolfram.com/publications/recent/mathml/ mathml2.html he mentions the Plimpton 322 tablet. It is widely taught in math history books, that this table is pythagorean triples. On reading his article, i wanted to refresh my understanding of the subject, so i looked up Wikipedia: http://en.wikipedia.org/wiki/Plimpton_322 and behold! apparantly, in recent academic publications, it is suggested that this is not pythagorean triples, but rather: “a list of regular reciprocal pairs”. Xah ∑http://xahlee.org/ ☄ -- http://mail.python.org/mailman/listinfo/python-list
Re: conversion of Python object to perl object
On Mon, Aug 17, 2009 at 3:47 AM, srinivasan srinivassri_anna...@yahoo.co.in wrote: Hi, I have to call a perl method which takes a hash as its argument from a python module. Is there a way to convert python dictionary to perl hash ( not hash ref)? How are you calling the Perl method from Python in the first place? Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Social problems of Python doc [was Re: Python docs disappointing]
On 18 Aug, 05:19, ru...@yahoo.com wrote: Yes, I agree. I should have mentioned this as an exception in my wikis suck diatribe. Although it far better than most wiki's I've seen, it is still pretty easy to find signs of typical wiki-ness. On the Documentation page my first click was on AnnotableDocumentation: 404. Well, Annotatable Documentation is an external link. All we can do in such cases is to tidy such stuff up, mark it as invalid, or remove it. Second try, DoumentationDiscussion: two very short paragraphs dated 2003. Right. There are parts of the Wiki which were used actively in the past but which have fallen into disrepair. Some pages lack focus - they've been created according to old school Wiki conventions which I regard as being somewhat obsolete (just creating new pages all over the place to cover whatever happens to be in the writer's head at the time) - and every now and again, I attempt to rationalise these pages and focus their content. After that I found some useful (in general though not what I was looking for) information but not a good first impression. (Well not exactly first, in fairness I have used other wiki sections such as the Templating page and found them very useful.) It needs work, of course. [...] I took a look at the PHP docs last night which seem pretty well done. The User Comments looked rather as I expected, there was useful info but most did not contain documentation quality writing. So if they are used as a source for improving the docs, there clearly must be a pretty large amount of editorial effort required, although much of it is probably just filtering out comments that don't provide any information appropriate for inclusion in the docs. They list 38 names under User Note Maintainers (http://www.php.net/manual/en/preface.php) Unfortunately I couldn't find a description of what these people actually do. I don't know how much work was involved in removing the comments that are no longer there. Indeed. There's always the editorial bottleneck unless it's a total free-for-all situation. I've remarked before about how user comments don't necessarily add significantly to documentation, which is an assertion that some people make, and there definitely does need to be a process of integrating the best feedback into the main work. The crucial difference between a Wiki and an annotation system is the combination of the contribution and editorial aspects in a Wiki - you edit the actual work, and people can decide whether it's a good edit or not - in contrast to their separation in most annotation systems. In some cases, strict annotation systems are probably better: the GPLv3 annotation system was oriented towards discussion of the text, and that's not so effectively done in a Wiki. Again, I don't mean to sound like I am dissing the idea of annotatable docs -- I think it is a good idea and will provide useful supplementary information. Where there's a separation of annotation and editing, I worry about the editorial bottleneck. I also worry about handprint edits more generally, where people just want to leave their touch on the work without actually contributing anything of substance. But I continue to question whether this will result in improvements in the docs themselves (which is my main interest) unless: 1. The purpose of the wiki is clearly marketed as soliciting suggestions, rewrites, etc destined ultimately for inclusion in the docs. I'm happy to see tangential work rather than stuff which fills exactly the same role as the current documentation. For example, the Python module of the week articles (PyMOTW, [1]) are exactly the kind of tangential work that could be encouraged, even though that is not so much a collaborative work itself. Paul [1] http://www.doughellmann.com/PyMOTW/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting DD MM YYYY into YYYY-MM-DD?
Python doesn't like the above: #locale.Error: unsupported locale setting locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) Maybe it was introduced in more recent versions of Python? Hmm, that's odd. According to the docs (http://docs.python.org/library/locale.html#locale.setlocale) it's been that way since 2.0, but I've just checked this on my Windows (Vista) machine and you're right, it returns an error. This worked for me on 32-bit Vista: locale.setlocale(locale.LC_ALL, 'FR') It uses Windows-1252 for the encoding, but that seems to deal with the circonflexe in 'Août' just fine, so it should work for this purpose. Rami Chowdhury Never attributed to malice that which can be attributed to stupidity. -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Tuesday 18 August 2009 01:19:53 Gilles Ganault wrote: On Tue, 18 Aug 2009 01:11:20 -0700, Rami Chowdhury rami.chowdh...@gmail.com wrote: Could you let me know which platform this is on (Windows, *nix)? It may be a locale encoding issue -- the locale.setlocale() function allows the second argument to be a tuple of (locale_code, encoding), as below: locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) It's on XP, and I'm using ActivePython 2.5.1.1. http://www.activestate.com/activepython/ Python doesn't like the above: #locale.Error: unsupported locale setting locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) Maybe it was introduced in more recent versions of Python? Since this is for a one-shot (and presumably threading-agnostic) program, and a fairly trivially formatted date-string, I would suggest using datetime.strptime (http://docs.python.org/library/datetime.html#datetime.datetime.strptime) and not regular expressions (which IIRC have Issues with non-ASCII characters). If the regex library can only handle basic latin characters, I'll wait until a script I'm running is done, and I'll upgrade to the 2.6.2.2 to see how it goes. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: XML parsing with python
On Aug 18, 11:24 am, Stefan Behnel stefan...@behnel.de wrote: inder wrote: On Aug 17, 8:31 pm, John Posner jjpos...@optimum.net wrote: Use the iterparse() function of the xml.etree.ElementTree package. http://effbot.org/zone/element-iterparse.htm http://codespeak.net/lxml/parsing.html#iterparse-and-iterwalk Stefan iterparse() is too big a hammer for this purpose, IMO. How about this: from xml.etree.ElementTree import ElementTree tree = ElementTree(None, myfile.xml) for elem in tree.findall('//book/title'): print elem.text -John Thanks for the prompt reply . I feel let me try using iterparse. Will it be slower compared to SAX parsing ... ultimately I will have a huge xml file to parse ? If you use the cElementTree module, it may even be faster. Another question , I will also need to validate my xml against xsd . I would like to do this validation through the parsing tool itself . In that case, you can use lxml instead of ElementTree. http://codespeak.net/lxml/ Stefan Hi , Is lxml part of standard python package ? I am having python 2.5 . I might not be able to use any additional package other than the standard python . Could you please suggest something part of standard python package ? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing Python Opcodes
Sreejith K wrote: On Aug 18, 12:19 pm, Diez B. Roggisch de...@nospam.web.de wrote: Did you try installing the egg *without* pyc-files in there? Because naturally those shouldn't work. They shouldn't crash the interpreter either, but then again - you *did* modify it. Hi Diez, thanks for the immediate reply :) I installed the setuptools using ez_setup.py script. Then I used the easy_install to install additional modules. When importing the installed modules segfault occurs. The module I installed was TurboGears. Then I thought that it happened maybe because the easy_install script is downloading eggs for original python (I'm not sure if it is what easy_install is doing). Yep, that's actually it's main purpose. So I also tried to install the module by downloading all the dependencies (tar.gz files) and building it. Even then segfault occured. Is there any problem in changing only the opcodes.py file ? I did something horribly wrong here. Hope someone will help... I don't know. You modified this yourself. If I were in your situation, what I would have done is to - modify the version-information stored in my PYC-files so that I'm sure I don't accidentally load any normal PYC-files. Python does check that through some magic number, make sure you use your own. - fire up the debugger and see where the segfault actually happens. Nobody can be helping you there, because it's *your* code, not Python anymore. And giving others access to it defies somewhat the purpose of the whole exercise Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting DD MM YYYY into YYYY-MM-DD?
On Tue, 18 Aug 2009 10:52:41 +0200, Gilles Ganault nos...@nospam.com wrote: I find it odd that the regex library can't handle European characters :-/ Ha, found it! :-) http://www.regular-expressions.info/python.html = # -*- coding: latin-1 -*- import locale import re locale.setlocale(locale.LC_ALL, 'FR') re_inscription = re.compile(r(?Pdate\d+)\s+(?Pmonth\w+)\s+(?Pyear\d+),re.LOCALE) dateinscription = 11 Août 2008 m = re_inscription.search(dateinscription) if m: day = m.group(date) month = m.group(month) year = m.group(year) print %s-%s-%s % (year,month,day) else: print Yuck = Thanks everyone! -- http://mail.python.org/mailman/listinfo/python-list
Re: Social problems of Python doc [was Re: Python docs disappointing]
ru...@yahoo.com writes: I took a look at the PHP docs last night which seem pretty well done. The User Comments looked rather as I expected, there was useful info but most did not contain documentation quality writing. So if they are used as a source for improving the docs, there clearly must be a pretty large amount of editorial effort required, although much of it is probably just filtering out comments that don't provide any information appropriate for inclusion in the docs. The comments section contains questions from users and answers to those questions from other users. What you may be missing is the part of the comments useful to the doc maintainers is primarily the user questions, rather than the user answers. The questions show the doc writer exactly what parts of the official doc are unclear or incomplete. The user-written answers may be wrong or generally crap, but the doc writer now knows what to do to improve the doc. That's why it's such a win to have the comments on the same page as the official docs. See also the user-commented http://book.realworldhaskell.org/read/ where the comments really helped clarify the finished (dead tree) text. -- http://mail.python.org/mailman/listinfo/python-list
Re: XML parsing with python
inder wrote: Is lxml part of standard python package ? I am having python 2.5 . No, that's why I suggested ElementTree first. I might not be able to use any additional package other than the standard python . Could you please suggest something part of standard python package ? No, there isn't any XMLSchema support in the stdlib. However, you may still be able to use lxml locally for development and with validation enabled, and switch to non-validating ElementTree on distribution/pre-prod-testing/whatever. Just use a conditional import and write a bit of setup code. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Need cleanup advice for multiline string
On Monday 17 August 2009 23:06:04 Carl Banks wrote: On Aug 17, 10:03 am, Jean-Michel Pichavant jeanmic...@sequans.com wrote: I'm no English native, but I already heard women/men referring to a group as guys, no matter that group gender configuration. It's even used for group composed exclusively of women. Moreover it looks like a *very* friendly form, so there is really nothing to worry about it. I like how being very friendly means calling people after a guy who tried to blow up the English Parliament. +1 QOTW - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting DD MM YYYY into YYYY-MM-DD?
Gilles Ganault nos...@nospam.com writes: dateinscription = 11 Août 2008 For any text string that's not ASCII, you should specify it as Unicode. (Actually, you should specify text as Unicode anyway.) For a literal text string: dateinscription = u11 Août 2008 If you're using exclusively Python 3, you will get Unicode text literals by default; but I assume you're using Python 2 based on existing discussion. The principles of handling text in Python: Get it to internal Unicode objects as soon as possible, handle it as Unicode for as long as possible, and only encode it to some byte stream for output as late as possible. -- \ “When a well-packaged web of lies has been sold to the masses | `\over generations, the truth will seem utterly preposterous and | _o__)its speaker a raving lunatic.” —Dresden James | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Diversity in Python (was Re: Need cleanup advice for multiline string)
On Tuesday 18 August 2009 06:45:39 Aahz wrote: In article pan.2009.08.18.04.34...@remove.this.cybersource.com.au, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: The comments were made a week ago -- why the sudden flurry of attention? Mainly an opportunity to flog the new diversity list. Here my English fails me - flog as in whip, or flog as in sell? - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
urlopen errors in script
I'm scripting a superkaramba theme using python and have intgrated output from amarok. I have also would like to show the artist and song title from a radio stream i've added to my playlist. If I open a python console and add the following: import urllib2 from urllib2 import urlopen nowplaying = str.split(urlopen('http://www.hearteastmids.co.uk// jsfiles/NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net%2Ffeeds% 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% 2F6854.xmll=6854tzc=8at=HeartEastMids').read(),'') print test[4][:-3] this works and displays the artist and song title. However, when I add this to my script I get the following errors: superkaramba(28855) ThemesDlg::addThemeToList: addThemeToList() file: / home/sleepy/dev/MyTheme/ MyTheme.theme superkaramba(28855) Karamba::startKaramba: Loading script module: MyTheme.py superkaramba(28855) KarambaInterface::initInterpreter: Using python script: /home/sleepy/dev/MyTheme/ MyTheme.py Kross: Loading the interpreter library for python Kross: Successfully loaded Interpreter instance from library. Kross: PythonScript::Constructor. Kross: PythonScript::execute Kross: PythonInterpreter::extractException: File /home/sleepy/dev/MyTheme/MyTheme.py, line 4, in module #this import statement allows access to the karamba functions File /home/sleepy/dev/MyTheme/MyTheme.py, line 9, in module import urllib2 File string, line 18, in _import File /usr/lib/python2.6/urllib2.py, line 92, in module import httplib File string, line 18, in _import File /usr/lib/python2.6/httplib.py, line 1054, in module import ssl File string, line 18, in _import File /usr/lib/python2.6/ssl.py, line 81, in module class SSLSocket (socket): Kross: Error error=Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) lineno=81 trace= File /home/sleepy/dev/MyTheme/MyTheme.py, line 4, in module #this import statement allows access to the karamba functions File /home/sleepy/dev/MyTheme/MyTheme.py, line 9, in module import urllib2 File string, line 18, in _import File /usr/lib/python2.6/urllib2.py, line 92, in module import httplib File string, line 18, in _import File /usr/lib/python2.6/httplib.py, line 1054, in module import ssl File string, line 18, in _import File /usr/lib/python2.6/ssl.py, line 81, in module class SSLSocket (socket): TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Error in sys.excepthook: Traceback (most recent call last): File /usr/lib/python2.6/dist-packages/apport_python_hook.py, line 38, in apport_excepthook from apport.packaging_impl import impl as packaging File string, line 18, in _import File /usr/lib/python2.6/dist-packages/apport/__init__.py, line 1, in module from apport.report import Report File string, line 18, in _import File /usr/lib/python2.6/dist-packages/apport/report.py, line 21, in module import fileutils File string, line 18, in _import File /usr/lib/python2.6/dist-packages/apport/fileutils.py, line 16, in module from packaging_impl import impl as packaging File string, line 18, in _import File /usr/lib/python2.6/dist-packages/apport/packaging_impl.py, line 18, in module import apt File string, line 18, in _import File /usr/lib/python2.6/dist-packages/apt/__init__.py, line 7, in module from apt.package import Package File string, line 18, in _import File /usr/lib/python2.6/dist-packages/apt/package.py, line 23, in module import httplib File string, line 18, in _import File /usr/lib/python2.6/httplib.py, line 1054, in module import ssl File string, line 18, in _import File /usr/lib/python2.6/ssl.py, line 81, in module class SSLSocket (socket): TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Original exception was: TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Kross: PythonScript::Destructor. Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
urlopen errors in script
I'm scripting a superkaramba theme using python and have intgrated output from amarok. I have also would like to show the artist and song title from a radio stream i've added to my playlist. If I open a python console and add the following: import urllib2 from urllib2 import urlopen nowplaying = str.split(urlopen('http://www.hearteastmids.co.uk// jsfiles/NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net%2Ffeeds% 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% 2F6854.xmll=6854tzc=8at=HeartEastMids').read(),'') print test[4][:-3] this works and displays the artist and song title. However, when I add this to my script I get the following errors: superkaramba(28855) ThemesDlg::addThemeToList: addThemeToList() file: / home/sleepy/dev/MyTheme/ MyTheme.theme superkaramba(28855) Karamba::startKaramba: Loading script module: MyTheme.py superkaramba(28855) KarambaInterface::initInterpreter: Using python script: /home/sleepy/dev/MyTheme/ MyTheme.py Kross: Loading the interpreter library for python Kross: Successfully loaded Interpreter instance from library. Kross: PythonScript::Constructor. Kross: PythonScript::execute Kross: PythonInterpreter::extractException: File /home/sleepy/dev/MyTheme/MyTheme.py, line 4, in module #this import statement allows access to the karamba functions File /home/sleepy/dev/MyTheme/MyTheme.py, line 9, in module import urllib2 File string, line 18, in _import File /usr/lib/python2.6/urllib2.py, line 92, in module import httplib File string, line 18, in _import File /usr/lib/python2.6/httplib.py, line 1054, in module import ssl File string, line 18, in _import File /usr/lib/python2.6/ssl.py, line 81, in module class SSLSocket (socket): Kross: Error error=Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) lineno=81 trace= File /home/sleepy/dev/MyTheme/MyTheme.py, line 4, in module #this import statement allows access to the karamba functions File /home/sleepy/dev/MyTheme/MyTheme.py, line 9, in module import urllib2 File string, line 18, in _import File /usr/lib/python2.6/urllib2.py, line 92, in module import httplib File string, line 18, in _import File /usr/lib/python2.6/httplib.py, line 1054, in module import ssl File string, line 18, in _import File /usr/lib/python2.6/ssl.py, line 81, in module class SSLSocket (socket): TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Error in sys.excepthook: Traceback (most recent call last): File /usr/lib/python2.6/dist-packages/apport_python_hook.py, line 38, in apport_excepthook from apport.packaging_impl import impl as packaging File string, line 18, in _import File /usr/lib/python2.6/dist-packages/apport/__init__.py, line 1, in module from apport.report import Report File string, line 18, in _import File /usr/lib/python2.6/dist-packages/apport/report.py, line 21, in module import fileutils File string, line 18, in _import File /usr/lib/python2.6/dist-packages/apport/fileutils.py, line 16, in module from packaging_impl import impl as packaging File string, line 18, in _import File /usr/lib/python2.6/dist-packages/apport/packaging_impl.py, line 18, in module import apt File string, line 18, in _import File /usr/lib/python2.6/dist-packages/apt/__init__.py, line 7, in module from apt.package import Package File string, line 18, in _import File /usr/lib/python2.6/dist-packages/apt/package.py, line 23, in module import httplib File string, line 18, in _import File /usr/lib/python2.6/httplib.py, line 1054, in module import ssl File string, line 18, in _import File /usr/lib/python2.6/ssl.py, line 81, in module class SSLSocket (socket): TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Original exception was: TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Kross: PythonScript::Destructor. Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: Using a Callback Function - ftplib
On Mon, Aug 17, 2009 at 11:10:25AM -0700, seldan24 wrote: I didn't even notice the higher level methods. I changed the retrieval line to: ftp.nlst(testfile*.txt) This works great. The result is even captured in an array. I really have no idea what the difference between a LIST and NLST is within FTP. Never delved that deep into it. I did notice that an NLST will return a specific FTP code if a file doesn't exist, whereas a LIST doesn't. So, I ended up using NLST as that'll generate an ftplib.error_perm exception. Based on if the job cares if a file is not available or not (some do, some don't), I'll either exit, or continue on with the file loop. The following thread from a NetBSD mailing list may help clarify this issue: http://mail-index.netbsd.org/netbsd-users/2001/01/30/0016.html NLST returns a machine-readable list of names, while LIST returns a human-readable list. Hene the presence of the FTP code in the case of NLST. -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting DD MM YYYY into YYYY-MM-DD?
On Tue, 18 Aug 2009 20:03:47 +1000, Ben Finney ben+pyt...@benfinney.id.au wrote: The principles of handling text in Python: Get it to internal Unicode objects as soon as possible, handle it as Unicode for as long as possible, and only encode it to some byte stream for output as late as possible. Thanks much for the tip. I'll keep that in mind when I have strings with accents. -- http://mail.python.org/mailman/listinfo/python-list
Re: Strongly typed list
On Tue, 2009-08-18 at 08:46 +0200, Diez B. Roggisch wrote: هاني الموصلي schrieb: Please could you lead me to a way or a good IDE that makes developing huge projects in python more easier than what i found.Now i am using eclips. Actually it is very hard to remember all my classes methods and attributes or copy and paste them each time. Thanks very much for your interest Hani Almousli. There are many really big projects written in Python - none of them with the aid of intelli-sense. What python lacks in that respect due to it's dynamic typing, it more than compensates by being faster to develop and having to write much less code. But this class can do *anything*! It .slice()s.. It .dice()s... ... sorry, couldn't resist ;-) -a -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting DD MM YYYY into YYYY-MM-DD?
Gilles Ganault nos...@nospam.com writes: On Tue, 18 Aug 2009 20:03:47 +1000, Ben Finney ben+pyt...@benfinney.id.au wrote: The principles of handling text in Python: Get it to internal Unicode objects as soon as possible, handle it as Unicode for as long as possible, and only encode it to some byte stream for output as late as possible. Thanks much for the tip. I'll keep that in mind when I have strings with accents. Again, note that these recommendations hold for *any* text in Python, with or without accents; once you accept that text is best handled in Unicode, there's little sense in making an exception for the limited subset that happens to be representable in ASCII. -- \“The Bermuda Triangle got tired of warm weather. It moved to | `\ Alaska. Now Santa Claus is missing.” —Steven Wright | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Diversity in Python
Hendrik van Rooyen hend...@microcorp.co.za writes: On Tuesday 18 August 2009 06:45:39 Aahz wrote: Mainly an opportunity to flog the new diversity list. Here my English fails me - flog as in whip, or flog as in sell? Yes :-) -- \ “The most common of all follies is to believe passionately in | `\the palpably not true. It is the chief occupation of mankind.” | _o__)—Henry L. Mencken | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode
Xah Lee wrote: This feature is important in practical ways. For example, when you work with “tab separated line” files (CSV) that's a common format for importing/exporting address books or spreadsheets. CSV stands for comma separated values and the import facilities of any spreadsheet application lets the user define the field separator character. Rui Maciel -- http://mail.python.org/mailman/listinfo/python-list
Re: urlopen errors in script
Sleepy Cabbage wrote: I'm scripting a superkaramba theme using python and have intgrated output from amarok. I have also would like to show the artist and song title from a radio stream i've added to my playlist. If I open a python console and add the following: import urllib2 from urllib2 import urlopen nowplaying = str.split(urlopen('http://www.hearteastmids.co.uk// jsfiles/NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net%2Ffeeds% 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% 2F6854.xmll=6854tzc=8at=HeartEastMids').read(),'') print test[4][:-3] this works and displays the artist and song title. However, when I add this to my script I get the following errors: Please give a minimal version of your script that produces the error, not some arbitrary excerpt that you ran successfully on the command line. If I were to guess: you are doing something like import socket socket.socket = socket somewhere, thus confusing the socket class with the module of the same name. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Need cleanup advice for multiline string
MRAB wrote: Carl Banks wrote: On Aug 17, 10:03 am, Jean-Michel Pichavant jeanmic...@sequans.com wrote: I'm no English native, but I already heard women/men referring to a group as guys, no matter that group gender configuration. It's even used for group composed exclusively of women. Moreover it looks like a *very* friendly form, so there is really nothing to worry about it. I like how being very friendly means calling people after a guy who tried to blow up the English Parliament. Guy Fawkes adopted the name Guido while fighting for the Spanish in the Low Countries: http://en.wikipedia.org/wiki/Guy_Fawkes I didn't get Carl's reference. The only thing I know about blowing the parliament is from the movie V for Vendetta (no comment please !). Now thanks to your link: In 18th-century England, the term guy was used to refer to an effigy http://en.wikipedia.org/wiki/Effigy of Fawkes, which would be paraded around town by children on the anniversary of the conspiracy Well, my knowledge is much too low to get this kind of reference from the start. :-/ JM -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] Mercurial migration: help needed
On 18/08/2009 6:20 PM, Dirkjan Ochtman wrote: On Tue, Aug 18, 2009 at 10:12, Martin v. Löwismar...@v.loewis.de wrote: In this thread, I'd like to collect things that ought to be done but where Dirkjan has indicated that he would prefer if somebody else did it. I think the most important item here is currently the win32text stuff. Mark Hammond said he would work on this; Mark, when do you have time for this? Then I could set apart some time for it as well. I can make time, somewhat spasmodically, starting fairly soon. Might I suggest that as a first task I can resurrect my old stale patch, and you can arrange to install win32text locally and start experimenting with how mixed line-endings can work for you. Once we are all playing in the same ballpark I think we should be able to make good progress. I-said-ballpark-yet-I-call-myself-an-aussie? ly, Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: Strongly typed list
I think i found a good managable solution. Actually it is trivial but may help (I used it now). When i wnat to access the list then i assign the object which i want to access to a variable ex: 1)x=AutomataBranch() 2)x=self.cfgAutomata[i] The first line is used only to make the IDE knows that x is from AutomatBranch type.After that when i press x. then all methods and properties are visualized. I think it is some how good. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 'for' loop is memory inefficient
On 03:56 am, tjre...@udel.edu wrote: exar...@twistedmatrix.com wrote: There's a lot of things in Python that I don't strictly *need*. That doesn't mean that they wouldn't be welcome if I could have them. Getting rid of the range/xrange dichotomy would improve things. The developers agreed a couple of years ago. Starting using 3.1 if you want this. And there was much rejoicing, et cetera. Since 'range' could refer to a user-defined object, rather than the builtin function, there is no way the interpreter should substitute 'xrange'. See the earlier parts of this thread for the reasons this isn't true. :) Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: [Python-Dev] Mercurial migration: help needed
On Tue, Aug 18, 2009 at 13:32, Mark Hammondmhamm...@skippinet.com.au wrote: I can make time, somewhat spasmodically, starting fairly soon. Might I suggest that as a first task I can resurrect my old stale patch, and you can arrange to install win32text locally and start experimenting with how mixed line-endings can work for you. Once we are all playing in the same ballpark I think we should be able to make good progress. Sounds good to me. Cheers, Dirkjan -- http://mail.python.org/mailman/listinfo/python-list
Re: urlopen errors in script
On Tue, 18 Aug 2009 13:21:59 +0200, Peter Otten wrote: Sleepy Cabbage wrote: I'm scripting a superkaramba theme using python and have intgrated output from amarok. I have also would like to show the artist and song title from a radio stream i've added to my playlist. If I open a python console and add the following: import urllib2 from urllib2 import urlopen nowplaying = str.split(urlopen('http://www.hearteastmids.co.uk// jsfiles/NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net% 2Ffeeds% 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% 2F6854.xmll=6854tzc=8at=HeartEastMids').read(),'') print test[4][:-3] this works and displays the artist and song title. However, when I add this to my script I get the following errors: Please give a minimal version of your script that produces the error, not some arbitrary excerpt that you ran successfully on the command line. If I were to guess: you are doing something like import socket socket.socket = socket somewhere, thus confusing the socket class with the module of the same name. Peter Thanks Peter. This is the script up to where the error seems to fall: #!/usr/bin/env superkaramba # -*- coding: iso-8859-1 -*- import karamba import subprocess from subprocess import Popen, PIPE, STDOUT, call import urllib from urllib import urlopen #this is called when your widget is initialized def initWidget(widget): clkPause = karamba.createClickArea(widget, 156, 470, 35, 35, qdbus org.kde.amarok /Player Pause) nowplaying = urllib.urlopen('http://www.hearteastmids.co.uk//jsfiles/ NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net%2Ffeeds% 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% 2F6854.xmll=6854tzc=8at=HeartEastMids').read() Hope this can enlighten things -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting DD MM YYYY into YYYY-MM-DD?
Ben Finney wrote: The principles of handling text in Python: Get it to internal Unicode objects as soon as possible, handle it as Unicode for as long as possible, and only encode it to some byte stream for output as late as possible. Again, note that these recommendations hold for *any* text in Python, with or without accents; once you accept that text is best handled in Unicode, there's little sense in making an exception for the limited subset that happens to be representable in ASCII. If the QOTW wasn't meant for fun, I'd vote for this. This is very good advice. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: urlopen errors in script
Sleepy Cabbage wrote: This is the script up to where the error seems to fall: #!/usr/bin/env superkaramba # -*- coding: iso-8859-1 -*- import karamba import subprocess from subprocess import Popen, PIPE, STDOUT, call import urllib from urllib import urlopen #this is called when your widget is initialized def initWidget(widget): clkPause = karamba.createClickArea(widget, 156, 470, 35, 35, qdbus org.kde.amarok /Player Pause) nowplaying = urllib.urlopen('http://www.hearteastmids.co.uk//jsfiles/ NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net%2Ffeeds% 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% 2F6854.xmll=6854tzc=8at=HeartEastMids').read() Hope this can enlighten things While there isn't any obvious blunder apart from the odd quotes that you wrap around every line there seem to be other files missing to run the script. I'm sorry, but I'm not prepared to invest much more than $ sudo aptitude install superkaramba into the problem. Perhaps an actual user of superkaramba can step in. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Need cleanup advice for multiline string
On Tue, 18 Aug 2009 13:36:49 +0200, Jean-Michel Pichavant wrote: MRAB wrote: Carl Banks wrote: On Aug 17, 10:03 am, Jean-Michel Pichavant jeanmic...@sequans.com wrote: I'm no English native, but I already heard women/men referring to a group as guys, no matter that group gender configuration. It's even used for group composed exclusively of women. Moreover it looks like a *very* friendly form, so there is really nothing to worry about it. I like how being very friendly means calling people after a guy who tried to blow up the English Parliament. Guy Fawkes adopted the name Guido while fighting for the Spanish in the Low Countries: http://en.wikipedia.org/wiki/Guy_Fawkes I didn't get Carl's reference. The only thing I know about blowing the parliament is from the movie V for Vendetta (no comment please !). Now thanks to your link: In 18th-century England, the term guy was used to refer to an effigy http://en.wikipedia.org/wiki/Effigy of Fawkes, which would be paraded around town by children on the anniversary of the conspiracy Well, my knowledge is much too low to get this kind of reference from the start. :-/ Guy is an old English name, related to the old French name Gy and Italian Guido. It's originally derived from the Old German for wood or warrior. After Guy Fawkes tried to blow up the English Parliament house, and was executed, the British government encouraged people to burn effigies of him. These became known as guys, which eventually became slang for an ugly man, which later became slang for any man, and in recent years, any person. So the irony is that the friendly term guys, referring to a group of people, is derived from the name of an 18th century religious terrorist. One can only wonder whether in 200 years time people will walk into the office and say Hey you osamas, they're giving away free donuts down stairs, anyone want some? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Diversity in Python (was Re: Need cleanup advice for multiline string)
On Tue, 18 Aug 2009 12:12:14 +0200, Hendrik van Rooyen wrote: On Tuesday 18 August 2009 06:45:39 Aahz wrote: In article pan.2009.08.18.04.34...@remove.this.cybersource.com.au, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: The comments were made a week ago -- why the sudden flurry of attention? Mainly an opportunity to flog the new diversity list. Here my English fails me - flog as in whip, or flog as in sell? Almost certainly flog as in sell. But not literally sell, for money, but sell in the sense of convincing others it is a good list to join. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: urlopen errors in script
Thanks for the time you've spent anyway Peter. I have superkaramba installed and the rest of the script is running fine, it's only when I put the urlopen part in that it comes back with errors. The quotes are just to make it readable on here as my first attempt at posting muted the text. -- http://mail.python.org/mailman/listinfo/python-list
Re: Strongly typed list
هاني الموصلي wrote: I think i found a good managable solution. Actually it is trivial but may help (I used it now). When i wnat to access the list then i assign the object which i want to access to a variable ex: 1)x=AutomataBranch() 2)x=self.cfgAutomata[i] The first line is used only to make the IDE knows that x is from AutomatBranch type.After that when i press x. then all methods and properties are visualized. I think it is some how good. Unless x=AutomataBranch() is something that is expensive. And to be honest: changing code (possibly introducing bugs!!!) to work around short-comings in either your IDE or your way you insist to work strikes me as odd. I understand the desire to have autocompletion. But it's not *that* important. Maybe fabrio (who's maintaining the PyDev-eclipse-plugin) could be asked to add something like this: #...@x:AutomataBranch to the plugin - so that when pydev reads that comment, it has a hint on what to use for autocompletion. Diez -- http://mail.python.org/mailman/listinfo/python-list
Compare content of two XML files
I need to compare a REST XML response with a 'gold standard' response (one that we have already verified is correct). The problem is, sometimes the REST response comes back and it is logically correct, but the order of attributes and elements is different than what is in the 'gold standard' file. For example: 'Gold Standard': ?xml version=1.0encoding=UTF-8 standalone=yes? Response Service id=1523/ CustomerInformation Networks Network CUR=EUR LOC=GB type=text/ /Networks /Response REST Response: ?xml version=1.0 standalone=yes encoding=UTF-8? Response Service id=1523/ CustomerInformation Networks Network type=text CUR=EUR LOC=GB / /Networks /Response Notice how the attributes in xml and network are in different order. The response is correct, but obviously doesn't match the 'gold standard'. Does anyone know how I would be able to compare these two files and verify they match, even though the order of attributes and elements may be different between the two? Is there a module I should be using for this? -- http://mail.python.org/mailman/listinfo/python-list
Re: define class over 2 files
indicator of bad practice. What is the problem you're trying to solve? Ben Finney No major problem. I was just trying to make some experimental changes to autokey. My repo: http://github.com/tinku99/autokey.git/ Didn't want to subclass or reorganize a class just yet. -- http://mail.python.org/mailman/listinfo/python-list
Code formatting question: conditional expression
While refactoring some code, I ran across an opportunity to use a conditional expression. Original: if total P.BASE: excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True) else: excessblk = None Is there any consensus on how to format a conditional expression that is too long for one line? How about this: excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total P.BASE else None) The above format separates the values from the if-then-else machinery. Too many lines? Would it be better to line up if and else vertically? ... excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total P.BASE else None) PEP 308 is silent on this topic. -John -- http://mail.python.org/mailman/listinfo/python-list
ANNOUNCEMENT: Tinybooker accounting released
Tinybooker 0.2.2 released at http://tinybooker.org/ Tinybooker is an accounting program offering the dual accounting core functionality for moderate size accountings: * Assisted establishing new accountings * Localized scheme templates * Easy entering and saving new entries * Standard reports in plain text or HTML: Income Statement, Balance Sheet, Journal, Nominal Ledger, Final Statement and Scheme * Assisted opening the next financial year * Accounting example as a demo * Open for auditing, all files human readable plain text * All written in pure Python * License GPL3 This early release is for Linux only. Later Tinybooker will be ported to Windows. Developers, more translations wanted, join the project contacting me at https://sourceforge.net/sendmessage.php?touser=2524141. -- http://mail.python.org/mailman/listinfo/python-list
ANN: PySide has been released
Hi, The PySide team is pleased to announce the first public release of PySide: Python for Qt! PySide, its documentation, and developer resources are available at the project website, http://www.pyside.org . What is it? --- PySide is a project providing an LGPL'd set of Python bindings for the Qt framework. PySide already provides a full set of Qt bindings as well as automated binding generation tools. Since the whole toolset has been made available, the team expects PySide to be valuable not only to Qt software developers, but to people willing to create Python bindings to any Qt-based library, or to any C++ library in general. Although based on a different technical approach, PySide will initially be API-compatible with existing Python bindings for Qt. PySide is still a work in progress, and some work is still required to stabilize the codebase. This being said, the team believes it is already in a usable state, especially if an occasional rough edge and unpainted surface can be tolerated. Due to practical reasons, the initial development efforts have been focused on Linux, but the team hopes people to join in porting the code to other platforms and to further develop the bindings and tools. Regards, PySide team -- Lauro Moura (lmoura on Freenode) http://lauro.wordpress.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Code formatting question: conditional expression
John Posner wrote: While refactoring some code, I ran across an opportunity to use a conditional expression. Original: if total P.BASE: excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True) else: excessblk = None Is there any consensus on how to format a conditional expression that is too long for one line? How about this: excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total P.BASE else None) The above format separates the values from the if-then-else machinery. Too many lines? Would it be better to line up if and else vertically? ... excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total P.BASE else None) My choice would be excessblk = None if total P.BASE: excessblk = ... You don't lose any vertical space, and it's much more readable IMHO. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Code formatting question: conditional expression
Diez B. Roggisch wrote: John Posner wrote: While refactoring some code, I ran across an opportunity to use a conditional expression. Original: if total P.BASE: excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True) else: excessblk = None Is there any consensus on how to format a conditional expression that is too long for one line? How about this: excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total P.BASE else None) The above format separates the values from the if-then-else machinery. Too many lines? Would it be better to line up if and else vertically? ... excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total P.BASE else None) My choice would be excessblk = None if total P.BASE: excessblk = ... You don't lose any vertical space, and it's much more readable IMHO. Diez +1, I'm using such layout whenever possible. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: Need cleanup advice for multiline string
On 2009-08-17, Carl Banks pavlovevide...@gmail.com wrote: On Aug 17, 10:03?am, Jean-Michel Pichavant jeanmic...@sequans.com wrote: I'm no English native, but I already heard women/men referring to a group as guys, no matter that group gender configuration. It's even used for group composed exclusively of women. Moreover it looks like a *very* friendly form, so there is really nothing to worry about it. I like how being very friendly means calling people after a guy who tried to blow up the English Parliament. Everybody likes fireworks! -- Grant Edwards grante Yow! Where do your SOCKS at go when you lose them in visi.comth' WASHER? -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI interface builder for python
On 17 Aug, 17:19, Che M cmpyt...@gmail.com wrote: Boa (Boa Constructor) is really nice for wxPython GUI work, but it has some bugs when using Linux that might be dealbreakers for the user. At least I have had problems on Ubuntu 8.10 64 bit (but none or very few I prefer wxFormBuilder over Boa. -- http://mail.python.org/mailman/listinfo/python-list
Re: Code formatting question: conditional expression
On Tue, 18 Aug 2009 10:04:36 -0400, John Posner wrote: While refactoring some code, I ran across an opportunity to use a conditional expression. Original: if total P.BASE: excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True) else: excessblk = None Is there any consensus on how to format a conditional expression that is too long for one line? Er, that defeats the purpose of using a conditional expression. If it's too long for one line, leave it as an if...else statement. How about this: excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total P.BASE else None) If you insist on using the conditional expression, my preference would be: excessblk = ( Block(total - P.BASE, srccol, carry_button_suppress=True) if total P.BASE else None ) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Code formatting question: conditional expression
My choice would be excessblk = None if total P.BASE: excessblk = ... Diez and Jean-Michel, Ha! Your suggestion above was my *original* coding. It looks like I'm evolving backwards! But doesn't it violate the DRY principle? The token excessblk appears twice instead of once. Thanks again, John -- http://mail.python.org/mailman/listinfo/python-list
simplest way to visit 3 subdirectories with a command?
hi all, could you inform how to compose a py-file (for soft installation), that will visit 3 subdirectories (eg subdir1, subdir2, subdir3) and invoke a command python setup.py install in each subdirectory? I know there should be a simple solution available in Python documentation, but I have an awful lots of other things to be done, so could someone write these several lines of code? Thank you in advance, D. -- http://mail.python.org/mailman/listinfo/python-list
Re: Code formatting question: conditional expression
John Posner jjpos...@optimum.net wrote in message news:mailman.26.1250604346.2854.python-l...@python.org... if total P.BASE: excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True) else: excessblk = None I wonder if it is appropriate to replace the None sentinel with one that is an instance of Block() e.g. size = total - P.BASE excessblk = Block(size, srccol, carry_button_suppress=True, empty_block=(size = 0) ) -- http://mail.python.org/mailman/listinfo/python-list
Start-up program
How difficult is to create a program that will be executed when Windows Vista is started? As Windows Calendar does, for example. I am actually more interested in the Python tools that might be used for this task. I hope that this question is not inappropriate for the list. :-\ --V -- http://mail.python.org/mailman/listinfo/python-list
Re: Code formatting question: conditional expression
John Posner wrote: My choice would be excessblk = None if total P.BASE: excessblk = ... Diez and Jean-Michel, Ha! Your suggestion above was my *original* coding. It looks like I'm evolving backwards! But doesn't it violate the DRY principle? The token excessblk appears twice instead of once. Thanks again, John I don't see any problem in that. You are hunting poor readability, not redundancy, it's up to you to decide of you priorities. I would still advise that readability should rule your world. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: Need cleanup advice for multiline string
Robert Dailey: [...] It's a figure of speech. And besides, why would I want programming advice from a woman? lol. Thanks for the help. Sorry, Robert, simply not acceptable. Whether designed to be funny or not it's the kind of inane remark I would be really happy never to see again. The problem is that we can't just let these things go by all the time (even though we aren't discussing a major crime here). If we do that it encourages (at best) an atmosphere of complacency and a feeling that it's OK to demean people in Python forums. I'd really like to see those *not* get a hold. regards Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Start-up program
Virgil Stokes wrote: How difficult is to create a program that will be executed when Windows Vista is started? As Windows Calendar does, for example. I am actually more interested in the Python tools that might be used for this task. I hope that this question is not inappropriate for the list. There are many discussions here about creating an exe (py2exe) that you could start in autostart, and how to run scripts as windows services, which is the other option. Just google a bit. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Start-up program
Virgil Stokes wrote: How difficult is to create a program that will be executed when Windows Vista is started? As Windows Calendar does, for example. I am actually more interested in the Python tools that might be used for this task. I hope that this question is not inappropriate for the list. :-\ --V Well put your program in your startup folder or configure it as a service in the service manager of windows. Now your problem becomes How difficult is to create a program for which there is no easy answer as it really depends on the kind of program. JM -- http://mail.python.org/mailman/listinfo/python-list
Mac OS 9.2
hi, i have to work with mac OS 9.2 for legacy reasons...is there a compiled version of python for this os ? i need to get input about variable values from the user and then print out some text files that make use of this input. a gui would be nice, but keyboard based input would be ok too... thanks much, suresh ps. if there isn't a version of pythn that will work, perhaps you could suggest some other scripting language for 0S 9.2 ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Start-up program
Virgil Stokes wrote: How difficult is to create a program that will be executed when Windows Vista is started? As Windows Calendar does, for example. I am actually more interested in the Python tools that might be used for this task. I hope that this question is not inappropriate for the list. :-\ Look for the Windows Startup folder. A quick search with Google found: http://www.bleepingcomputer.com/forums/topic85142.html -- http://mail.python.org/mailman/listinfo/python-list
Re: problem with interface of operator.itemgetter
2009/8/17 Simon Forman sajmik...@gmail.com You can use a little helper function to create your itemgetter like this: def makeItemGetter(indexes): I = itemgetter(*indexes) if len(indexes) 1: return I return lambda thing: (I(thing),) If indexes contains only one index the itemgetter is wrapped in a lambda that turns its output into a tuple. Thanks. I just thought if the stdlib could support some function like item*s *getter would be better, it always returns tuple instead of a item or a tuple of items. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need cleanup advice for multiline string
Steve Holden wrote: Robert Dailey: [...] It's a figure of speech. And besides, why would I want programming advice from a woman? lol. Thanks for the help. Sorry, Robert, simply not acceptable. Whether designed to be funny or not it's the kind of inane remark I would be really happy never to see again. The problem is that we can't just let these things go by all the time (even though we aren't discussing a major crime here). If we do that it encourages (at best) an atmosphere of complacency and a feeling that it's OK to demean people in Python forums. I'd really like to see those *not* get a hold. regards Steve Did you read the original post (this is an old one) ? Because quoting a joke out of its context is totally unfair. Anyway the hysteria that is surrounding this thread is just amazing. I'm waiting for more. JM -- http://mail.python.org/mailman/listinfo/python-list
Identifying a class type - bad practice?
I am writing some code to form a tree of nodes of different types. The idea is to define one class per node type such as class node_type_1(node): specific properties by name including other node types class node_type_2(node): specific properties by name including other node types etc (Class node would hold any common properties). When walking the tree I need to know what type of node I'm dealing with so polymorphism isn't generally useful. The action to be taken depends on the node type. Two options appear to be useful: __class__ and isinstance. I know the latter will match the instance against any superclass and the former will match one class only. My question is: is this the Pythonic way to deal with such a tree? Is there a better way? In C I would use structs where one field was a tag indicating the kind of struct. James -- http://mail.python.org/mailman/listinfo/python-list
Re: simplest way to visit 3 subdirectories with a command?
could you inform how to compose a py-file (for soft installation), that will visit 3 subdirectories (eg subdir1, subdir2, subdir3) and invoke a command python setup.py install in each subdirectory? I know there should be a simple solution available in Python If you're executing python setup.py install, that sounds like you're operating at the shell level, not within python. In which case, I'd just use my shell's iteration capabilities: # running bash on a *nix-like OS bash$ for dir in subdir1 subdir2 subdir3; do pushd $dir; python setup.py install; popd; done # running within Win32's cmd.exe c:\temp\ for %f in (subdir1 subdir2 subdir3) do pushd %f python setup.py install popd or something of the sort. Remember in Win32 that the variables have to be escaped if you put them in a batch file (%%f instead of %f) -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Mac OS 9.2
ok, i found macpython 2.3 at this site: http://homepages.cwi.nl/~jack/macpython/macpython-older.html is this the best option for me in terms of using python on os 9.2 ? thanks much !! suresh On Aug 18, 6:04 pm, madzientist madzient...@gmail.com wrote: hi, i have to work with mac OS 9.2 for legacy reasons...is there a compiled version of python for this os ? i need to get input about variable values from the user and then print out some text files that make use of this input. a gui would be nice, but keyboard based input would be ok too... thanks much, suresh ps. if there isn't a version of pythn that will work, perhaps you could suggest some other scripting language for 0S 9.2 ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Code formatting question: conditional expression
I wonder if it is appropriate to replace the None sentinel with one that is an instance of Block() e.g. size = total - P.BASE excessblk = Block(size, srccol, carry_button_suppress=True, empty_block=(size = 0) ) In this particular case, Richard, I don't think so. The Block class is an application-level wrapper for a graphical object. I don't want to worry about zero-size objects. (Is this column really empty, or does it contain one or more zero-size blocks?) If you're interested, take a look at BlockHead at www.jjposner.net. BTW, from the (admittedly few) responses to my original post, it seems there's some sentiment that conditional expressions are a non-Pythonic misfeature. Interesting ... -John -- http://mail.python.org/mailman/listinfo/python-list
xlutils 1.4.0 released!
Hi All, I'm pleased to announce a new release of xlutils. This is a small collection of utilities that make use of both xlrd and xlwt to process Microsoft Excel files. The changes for this release are as follows: - Add sheet density information and onesheet option to xlutils.margins. - Reduced the memory footprint of xlutils.filter.ColumnTrimmer at the expense of speed. - Fixed incorrect warnings about boolean cells in xlutils.filter.ErrorFilter. xlwt has always supported boolean cells. - xlutils.filter.BaseReader now opens workbooks with on_demand = True - Added support for xlrd Books opened with on_demand as True passed to open_workbook. - Fixed bug when copying error cells. - Requires the latest versions of xlrd (0.7.1) and xlwt (0.7.2). To find out more, please read here: http://www.simplistix.co.uk/software/python/xlutils In case you're not aware, xlrd and xlwt are two excellent pure-python libraries for reading and writing Excel files. They run on any platform and, likely, any implementation of Python without the need for horrific things like binding to Excel via COM and so needing a Windows machine. If you use any of xlrd, xlwt or xlutils, the following google group will be of use: http://groups.google.com.au/group/python-excel Hope some of this is of interest, I'd love to hear from anyone who ends up using it! cheers, Chris -- Simplistix - Content Management, Zope Python Consulting - http://www.simplistix.co.uk -- http://mail.python.org/mailman/listinfo/python-list
Parallelization in Python 2.6
I'm looking for a way to parallelize my python script without using typical threading primitives. For example, C++ has pthreads and TBB to break things into tasks. I would like to see something like this for python. So, if I have a very linear script: doStuff1() doStuff2() I can parallelize it easily like so: create_task( doStuff1 ) create_task( doStuff2 ) Both of these functions would be called from new threads, and once execution ends the threads would die. I realize this is a simple example and I could create my own classes for this functionality, but I do not want to bother if a solution already exists. Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: Code formatting question: conditional expression
John Posner wrote: BTW, from the (admittedly few) responses to my original post, it seems there's some sentiment that conditional expressions are a non-Pythonic misfeature. Interesting ... -John I didn't read it that way. One of the (to me) core points of Pythonic is readability. A conditional expression on one line is fine -- a conditional expression on more than one line is less readable than the standard if-else structure. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Parallelization in Python 2.6
Robert Dailey wrote: I'm looking for a way to parallelize my python script without using typical threading primitives. For example, C++ has pthreads and TBB to break things into tasks. I would like to see something like this for python. So, if I have a very linear script: doStuff1() doStuff2() I can parallelize it easily like so: create_task( doStuff1 ) create_task( doStuff2 ) Both of these functions would be called from new threads, and once execution ends the threads would die. I realize this is a simple example and I could create my own classes for this functionality, but I do not want to bother if a solution already exists. I think the canonical answer is to use the threading module or (preferably) the multiprocessing module, which is new in Py2.6. http://docs.python.org/library/threading.html http://docs.python.org/library/multiprocessing.html Both share a (mostly) common interface and are simple enough to use. They are pretty close to the above interface already. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Identifying a class type - bad practice?
James Harris wrote: I am writing some code to form a tree of nodes of different types. The idea is to define one class per node type such as class node_type_1(node): specific properties by name including other node types class node_type_2(node): specific properties by name including other node types etc (Class node would hold any common properties). When walking the tree I need to know what type of node I'm dealing with so polymorphism isn't generally useful. The action to be taken depends on the node type. Two options appear to be useful: __class__ and isinstance. I know the latter will match the instance against any superclass and the former will match one class only. My question is: is this the Pythonic way to deal with such a tree? Is there a better way? In C I would use structs where one field was a tag indicating the kind of struct. James I would recommend going with isinstance. An instance of node_type_2 will not be an instance node_type_1, so no worries there, and it leaves open the option of subclassing further if you need to later on. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Identifying a class type - bad practice?
On Aug 18, 2:09 pm, James Harris james.harri...@googlemail.com wrote: I am writing some code to form a tree of nodes of different types. The idea is to define one class per node type such as class node_type_1(node): specific properties by name including other node types class node_type_2(node): specific properties by name including other node types etc (Class node would hold any common properties). When walking the tree I need to know what type of node I'm dealing with so polymorphism isn't generally useful. The action to be taken depends on the node type. Two options appear to be useful: __class__ and isinstance. I know the latter will match the instance against any superclass and the former will match one class only. My question is: is this the Pythonic way to deal with such a tree? Is there a better way? In C I would use structs where one field was a tag indicating the kind of struct. James I would probably go with hasattr(instance, 'what_I_want') André -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing XML files to eachother
On Mon, Aug 17, 2009 at 3:51 PM, David Brochubrochu...@gmail.com wrote: I need to compare one xml document to another to see if the content matches. Unfortunately, the formatting (spacing) and order of elements may change between files from run to run. I have looked into xml dom minidom but can't seem to find how to accomplish this. Does anyone know how I can do a compare between two XML documents using the STL? It seems to me that you're going to have to normalize the documents to be able to compare them. (I.e. strip or ignore spacing differences, sort the elements to be in the same order, etc..) -- http://mail.python.org/mailman/listinfo/python-list
Inheriting dictionary
I want a dictionary that will transparently inherit from a parent dictionary. So, for example: a = InheritDict({1: one, 2: two, 4: four}) b = InheritDict({3: three, 4: foobar}, inherit_from=a) a[1] # one a[4] # four b[1] # one b[3] # three b[4] # foobar I've written something like this in Python already, but I'm wondering if something like this already exists, preferably written in C, for speed. -- http://mail.python.org/mailman/listinfo/python-list
Re: Code formatting question: conditional expression
18-08-2009 Steven D'Aprano st...@remove-this-cybersource.com.au wrote: On Tue, 18 Aug 2009 10:04:36 -0400, John Posner wrote: [snip] How about this: excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total P.BASE else None) If you insist on using the conditional expression, my preference would be: excessblk = ( Block(total - P.BASE, srccol, carry_button_suppress=True) if total P.BASE else None ) Generally I'd prefer: excessblk = (Block() if total P.BASE else None) But it this case first line would be too long, then I'd try using: excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total P.BASE else None) or excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total P.BASE else None) I'd use conditional expression only (rather) in situation when the first expression-part was 'common' and the other (after else) was 'rare'. Cheers, *j -- Jan Kaliszewski (zuo) z...@chopin.edu.pl -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheriting dictionary
18-08-2009 o 21:44:55 Pavel Panchekha pavpanche...@gmail.com wrote: I want a dictionary that will transparently inherit from a parent dictionary. So, for example: a = InheritDict({1: one, 2: two, 4: four}) b = InheritDict({3: three, 4: foobar}, inherit_from=a) a[1] # one a[4] # four b[1] # one b[3] # three b[4] # foobar I've written something like this in Python already, but I'm wondering if something like this already exists, preferably written in C, for speed. AFAIN -- no. But you can easily implement it in Python with rather small loss of speed... class InheritDict(dict): class NoParent(object): def __getitem__(self, key): raise KeyError('There is no %r key in the hierarchy' % key) def __nonzero__(self): return False noparent = NoParent() def __init__(self, *args, **kwargs): parent = kwargs.pop('inherit_from', self.noparent) dict.__init__(self, *args, **kwargs) self.parent = parent def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return self.parent[key] Did you do it in similar way? (just curiosity) :-) Regards, *j -- Jan Kaliszewski (zuo) z...@chopin.edu.pl -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheriting dictionary
On Tue, Aug 18, 2009 at 2:44 PM, Pavel Panchekha pavpanche...@gmail.comwrote: I want a dictionary that will transparently inherit from a parent dictionary. So, for example: a = InheritDict({1: one, 2: two, 4: four}) b = InheritDict({3: three, 4: foobar}, inherit_from=a) a[1] # one a[4] # four b[1] # one b[3] # three b[4] # foobar I've written something like this in Python already, but I'm wondering if something like this already exists, preferably written in C, for speed. Why complicate this with a custom object? Just use regular dicts and make b a copy of a. a = {1: 'one', 2: 'two', 4: 'four'} b = dict(a) b[3] = 'three' b[4] = 'foobar' -- http://mail.python.org/mailman/listinfo/python-list
How to create functors?
Hello, I want to simply wrap a function up into an object so it can be called with no parameters. The parameters that it would otherwise have taken are already filled in. Like so: print1 = lambda: print( Foobar ) print1() However, the above code fails with: File C:\IT\work\distro_test\distribute_radix.py, line 286 print1 = lambda: print( Foobar ) ^ SyntaxError: invalid syntax How can I get this working? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create functors?
Robert Dailey rcdai...@gmail.com wrote: Hello, I want to simply wrap a function up into an object so it can be called with no parameters. The parameters that it would otherwise have taken are already filled in. Like so: print1 = lambda: print( Foobar ) print1() However, the above code fails with: File C:\IT\work\distro_test\distribute_radix.py, line 286 print1 = lambda: print( Foobar ) ^ SyntaxError: invalid syntax How can I get this working? def print1(): print Foobar It looks like in your version of Python print isn't a function. It always helps if you say the exact version you are using in your question as the exact answer you need may vary. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create functors?
On Aug 18, 3:31 pm, Duncan Booth duncan.bo...@invalid.invalid wrote: Robert Dailey rcdai...@gmail.com wrote: Hello, I want to simply wrap a function up into an object so it can be called with no parameters. The parameters that it would otherwise have taken are already filled in. Like so: print1 = lambda: print( Foobar ) print1() However, the above code fails with: File C:\IT\work\distro_test\distribute_radix.py, line 286 print1 = lambda: print( Foobar ) ^ SyntaxError: invalid syntax How can I get this working? def print1(): print Foobar It looks like in your version of Python print isn't a function. It always helps if you say the exact version you are using in your question as the exact answer you need may vary. I'm using Python 2.6. And using the legacy syntax in the lambda does not work either. I want to avoid using a def if possible. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheriting dictionary
On Aug 18, 4:23 pm, Jan Kaliszewski z...@chopin.edu.pl wrote: 18-08-2009 o 21:44:55 Pavel Panchekha pavpanche...@gmail.com wrote: I want a dictionary that will transparently inherit from a parent dictionary. So, for example: a = InheritDict({1: one, 2: two, 4: four}) b = InheritDict({3: three, 4: foobar}, inherit_from=a) a[1] # one a[4] # four b[1] # one b[3] # three b[4] # foobar I've written something like this in Python already, but I'm wondering if something like this already exists, preferably written in C, for speed. AFAIN -- no. But you can easily implement it in Python with rather small loss of speed... class InheritDict(dict): class NoParent(object): def __getitem__(self, key): raise KeyError('There is no %r key in the hierarchy' % key) def __nonzero__(self): return False noparent = NoParent() def __init__(self, *args, **kwargs): parent = kwargs.pop('inherit_from', self.noparent) dict.__init__(self, *args, **kwargs) self.parent = parent def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return self.parent[key] Did you do it in similar way? (just curiosity) :-) Regards, *j -- Jan Kaliszewski (zuo) z...@chopin.edu.pl I implemented it in a similar way (instead of a try block, an if block, which works a tiny bit faster; also have a multiple-parents case, but its rare, and I could do that in Python without much loss of speed). Pity that there's no C version; this InheritDict is kind of the core of my application (in a very basic test, I have 329901 calls to __getitem__). Oh well; I'll see if I can optimize the __getattr__ function with minor tweaking. Thanks for your help. -- http://mail.python.org/mailman/listinfo/python-list
Re: define class over 2 files
On Tue, Aug 18, 2009 at 1:57 AM, Steven D'Apranoste...@remove.this.cybersource.com.au wrote: On Mon, 17 Aug 2009 21:45:57 -0700, naveen wrote: Is it possible to split up a class definition over multiple files? Not exactly, but you can do variations of this: In file A.py, create: class Parent: def method(self): return Method In file B.py, do this: import A class Child(B.parent): class Child(A.Parent): -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create functors?
On Aug 18, 3:31 pm, Duncan Booth duncan.bo...@invalid.invalid wrote: Robert Dailey rcdai...@gmail.com wrote: Hello, I want to simply wrap a function up into an object so it can be called with no parameters. The parameters that it would otherwise have taken are already filled in. Like so: print1 = lambda: print( Foobar ) print1() However, the above code fails with: File C:\IT\work\distro_test\distribute_radix.py, line 286 print1 = lambda: print( Foobar ) ^ SyntaxError: invalid syntax How can I get this working? def print1(): print Foobar It looks like in your version of Python print isn't a function. It always helps if you say the exact version you are using in your question as the exact answer you need may vary. Seems like it works fine on everything else except for print(). For example: print1 = lambda: MyFunction( FooBar ) The syntax above is accepted by the interpreter. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to create functors?
On Tue, Aug 18, 2009 at 1:32 PM, Robert Daileyrcdai...@gmail.com wrote: On Aug 18, 3:31 pm, Duncan Booth duncan.bo...@invalid.invalid wrote: Robert Dailey rcdai...@gmail.com wrote: Hello, I want to simply wrap a function up into an object so it can be called with no parameters. The parameters that it would otherwise have taken are already filled in. Like so: print1 = lambda: print( Foobar ) print1() However, the above code fails with: File C:\IT\work\distro_test\distribute_radix.py, line 286 print1 = lambda: print( Foobar ) ^ SyntaxError: invalid syntax How can I get this working? def print1(): print Foobar It looks like in your version of Python print isn't a function. It always helps if you say the exact version you are using in your question as the exact answer you need may vary. I'm using Python 2.6. And using the legacy syntax in the lambda does not work either. I want to avoid using a def if possible. Thanks. ch...@morpheus ~ $ python Python 2.6.2 (r262:71600, May 14 2009, 16:34:51) [GCC 4.0.1 (Apple Inc. build 5484)] on darwin Type help, copyright, credits or license for more information. print1 = lambda: print( Foobar ) File stdin, line 1 print1 = lambda: print( Foobar ) ^ SyntaxError: invalid syntax from __future__ import print_function print1 = lambda: print( Foobar ) print1() Foobar Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: define class over 2 files
18-08-2009 o 06:58:58 Xavier Ho cont...@xavierho.com wrote: On Tue, Aug 18, 2009 at 2:45 PM, naveen naveen.g...@gmail.com wrote: Is it possible to split up a class definition over multiple files? - Answer in short, I don't think so. Why not? - File a.py: class MyClass: def foo(self, x): return x * 6 - File b.py: import a def bar(self): print 'bar' def baz(self, a): print self.f(a) # adding methods by hand: a.MyClass.bar = bar a.MyClass.baz = baz - File c.py import a def f(self, a): return a * self.foo(4) def baaar(self): print self.baz('tralala') def bazzz(self): print 'bzz' # adding methods more automaticly: for name, obj in globals().values(): setattr(a.MyClass, name, obj) Now why would you want to do that? It's a good question. As others said it's very probable that some other solution would be better (e.g. inheritance). Cheers, *j -- Jan Kaliszewski (zuo) z...@chopin.edu.pl -- http://mail.python.org/mailman/listinfo/python-list
Re: Parallelization in Python 2.6
On Aug 18, 11:19 am, Robert Dailey rcdai...@gmail.com wrote: I'm looking for a way to parallelize my python script without using typical threading primitives. For example, C++ has pthreads and TBB to break things into tasks. I would like to see something like this for python. So, if I have a very linear script: doStuff1() doStuff2() I can parallelize it easily like so: create_task( doStuff1 ) create_task( doStuff2 ) Both of these functions would be called from new threads, and once execution ends the threads would die. I realize this is a simple example and I could create my own classes for this functionality, but I do not want to bother if a solution already exists. If you haven't heard of the Python GIL, you'll want to find out sooner rather than later. Short summary: Python doesn't do threading very well. There are quite a few parallelization solutions out there for Python, however. (I don't know what they are off the top of my head, however.) The way they work is they have worker processes that can be spread across machines. When you want to parallelize a task, you send off a function to those worker threads. There are some serious caveats and problems, not the least of which is sharing code between the worker threads and the director, so this isn't a great solution. If you're looking for highly parallelized code, Python may not be the right answer. Try something like Erlang or Haskell. -- http://mail.python.org/mailman/listinfo/python-list