ANN: SciPy 2009 conference schedule posted
The SciPy conference committee is pleased to announce the schedule of the conference: http://conference.scipy.org/schedule This year’s program is very rich. In order to limit the number of interesting talks that we had to turn down, we decided to reduce the length of talks. Although this results in many short talks, we hope that it will foster discussions, and give new ideas. Many subjects are covered, both varying technical subject in the scientific computing spectrum, and covering a lot of different research areas. I would personally like to thank the members of the program committee, who spent time reviewing the proposed abstracts and giving the chairs feedback. Fernando Perez and the tutorial presenters are hard at work finishing planning all the details of the two-day tutorial session that will precede the conference. An introduction tutorial track and an advanced tutorial track, both covering various aspect of scientific computing in Python, presented by experts in the field, should help many people getting up to speed on the amazing technology driving this community. The SciPy 2009 program committee * Co-Chair Gaël Varoquaux, Applied Mathematics and Neuroscience, Neurospin, CEA - INRIA Saclay (France) * Co-Chair Stéfan van der Walt, Applied Mathematics, University of Stellenbosch (South Africa) * Michael Aivazis, Center for Advanced Computing Research, California Institute of Technology (USA) * Brian Granger, Physics Department, California Polytechnic State University, San Luis Obispo (USA) * Aric Hagberg, Theoretical Division, Los Alamos National Laboratory (USA) * Konrad Hinsen, Centre de Biophysique Moléculaire, CNRS Orléans (France) * Randall LeVeque, Mathematics, University of Washington, Seattle (USA) * Travis Oliphant, Enthought (USA) * Prabhu Ramachandran, Department of Aerospace Engineering, IIT Bombay (India) * Raphael Ritz, International Neuroinformatics Coordinating Facility (Sweden) * William Stein, Mathematics, University of Washington, Seattle (USA) Conference Chair: Jarrod Millman, Neuroscience Institute, UC Berkeley (USA) -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
ANN: gensei-2009.2 released
I am pleased to announce release 2009.2 of gensei (generator of serial images). http://code.google.com/p/gensei/ What does it do? The code generates images corresponding to slices of a block specimen filled with ellipsoids of known geometrical properties such as the volume fraction within the block, dimensions, volumes of individual ellipsoids, a length-to-width ratio and number. Why? Its purpose is to verify results, obtained by various software for reconstructing 3D data (e.g. a living tissue microstructure) given a set of 2D slices using usually stereological methods, on a dataset with well-defined and known properties. Release notes - This is the first public release. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
Enthought Tool Suite (ETS) 3.3.0 released
Hello, I'm pleased to announce that Enthought Tool Suite (ETS) version 3.3.0 has been tagged and released! Please see below for a partial list of changes for this release. PyPi has been updated with the release, including the availability of both Windows binaries (.egg) and source distributions (.tar.gz). A full install of ETS can be done using a command like: easy_install -U ETS[nonets] == 3.3.0 HOWEVER, it is important to note that there are still package dependencies that are outside the scope of easy_install. Therefore, we recommend that you have the following installed prior to installing ETS: setuptools: minimum version 0.6c9 VTK: minimum version 5.0, recommended 5.2 or later And at least one of: wxPython: minimum version 2.8.7.1 PyQt: minimum version 4.4 For additional installation information, see: https://svn.enthought.com/enthought/wiki/Install What Is ETS? === The Enthought Tool Suite (ETS) is a collection of components developed by Enthought and the open-source community, which we use every day to construct scientific applications. It includes a wide variety of components, including: * an extensible application framework * application building blocks * 2-D and 3-D graphics libraries * scientific and math libraries * developer tools The cornerstone on which these tools rest is the Traits package, which provides explicit type declarations in Python; its features include initialization, validation, delegation, notification, and visualization of typed attributes. More information on ETS is available from the development home page: http://code.enthought.com/projects/index.php ETS 3.3.0 is a feature-added update to ETS 3.2.0, including numerous bug-fixes. Some of the notable changes include (sub-projects listed in alphabetical order): Chaco 3.2.0 (July 15, 2009) === Enhancements * Bounded grids - Horizontal and Vertical grid line start and end points can now be set to a fixed value in data space, or to be the return value of an arbitrary callable. The start and end tick can also be configured via the data_min and data_max traits. * Added dictionary interface to ArrayPlotData * Added a Traits UI view to the ScalesAxis * Added a new chaco.overlays subpackage and a new overlay, the DataBox. * Improved appearance of PlotToolbar * Changed add_default_axis() in the plot_factory module to take an axis class as a keyword argument. * Refactored contour plots into a common base class and implemented proper event handling when their colormaps or data ranges change. * Changed default colormap on img_plot() and contour_plot() method of Plot to be Spectral instead of Jet. * Added two more color palettes to the auto color palette, and created a default_colors module. * Added CandlePlot renderer * Changed Plot Labels to able to display inside the plot area, instead of only on the outside * Added optional title attribute to plot legends * Updated all containers to respect and use the new fixed_preferred_size trait on enable.Component * New Examples: * Interval trait editor as a Chaco example (from Stefan van der Walt) * embedding an interactive Chaco plot inside a VTK RenderWindow using the new Enable VTK backend * lasso tool on an image plot * bounded grid * candle plot Fixes - * Fixed call signature of ShowAllTickGenerator.get_ticks() * Plot.title_font is now a delegate to the underlying PlotLabel object (from Chris Colbert) * Fixed mouse event handling bug in RangeSelection (from Stefan van der Walt) * ImagePlots now redraw when their input data changes. * Fixed cached image invalidation in colormapped image plots * Optimized ScatterPlot.map_index() when index_only is True and the index data is sorted * Changed ColormappedScatterPlot to no longer incorrectly apply the fill_alpha to the outline color * Improved date ticking heuristics in chaco.scales subpackage, specifically eliminating the bug where all times between, midnight and 1am would be formatted at too course of a time resolution. * Cleanup of various examples (titles, appearance) * The spectrum.py (audio spectrograph) example now properly closes the audio stream. Enable 3.2.0 (July 15th, 2009) == enthought.enable Enhancements - * Added Slider and Compass widgets * Added an OverlayContainer (almost identical to the one in Chaco) * Added ImageGraphicsContextEnable class so that one can always import a Kiva Image backend-based GraphicsContextEnable * renaming marker_trait to MarkerTrait (the old name is still permitted for backwards compatibility, but should be avoided) * Moved the scatter_markers module from Chaco to Enable, so that Enable components can use MarkerTrait * Added an experimental VTK backend for Enable, along with an example * Changed SVGButtonEditor toggle to draw
TkDocs: new tutorial and resources for TkInter/ttk
TkDocs is a language-neutral resource for developers who are interested in using Tk as their GUI. The highlight is an extensive tutorial that illustrates how to use the newest generation of Tk features and best practices to create modern and attractive user interfaces. I'm pleased to announce that the tutorial and other parts of the site has been updated with the latest Python-oriented Tk material, corresponding to tkinter and ttk from Python 3.1. You'll now find all the examples and code snippets available in Python (and also Tcl, Ruby and Perl for those so inclined). Please visit the site at http://www.tkdocs.com I hope this site is valuable for both new and existing Python GUI developers; for the latter group it will help you upgrade away from all the outdated ugly constructs that Tk is so famous for. ;-) I'd greatly appreciate any feedback, corrections or suggestions on the site. Thanks Mark -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
ANN: gnupg v0.2.0 released
A new version of the Python module which wraps GnuPG has been released. What Changed? = The module was refactored slightly to support Python 3.0. The current version now passes all tests on Windows (Python 2.4, 2.5) and Ubuntu (Python 2.4, 2.5, 2.6 and 3.0). What Does It Do? The gnupg module allows Python programs to make use of the functionality provided by the Gnu Privacy Guard (abbreviated GPG or GnuPG). Using this module, Python programs can encrypt and decrypt data, digitally sign documents and verify digital signatures, manage (generate, list and delete) encryption keys, using proven Public Key Infrastructure (PKI) encryption technology based on OpenPGP. This module is expected to be used with Python versions = 2.4, as it makes use of the subprocess module which appeared in that version of Python. This module is a newer version derived from earlier work by Andrew Kuchling, Richard Jones and Steve Traugott. A test suite using unittest is included with the source distribution. Simple usage: import gnupg gpg = gnupg.GPG(gnupghome='/path/to/keyring/directory') gpg.list_keys() [{ ... 'fingerprint': 'F819EE7705497D73E3CCEE65197D5DAC68F1AAB2', 'keyid': '197D5DAC68F1AAB2', 'length': '1024', 'type': 'pub', 'uids': ['', 'Gary Gross (A test user) gary.gr...@gamma.com']}, { ... 'fingerprint': '37F24DD4B918CC264D4F31D60C5FEFA7A921FC4A', 'keyid': '0C5FEFA7A921FC4A', 'length': '1024', ... 'uids': ['', 'Danny Davis (A test user) danny.da...@delta.com']}] encrypted = gpg.encrypt(Hello, world!, ['0C5FEFA7A921FC4A']) str(encrypted) '-BEGIN PGP MESSAGE-\nVersion: GnuPG v1.4.9 (GNU/Linux)\n \nhQIOA/6NHMDTXUwcEAf ... -END PGP MESSAGE-\n' decrypted = gpg.decrypt(str(encrypted), passphrase='secret') str(decrypted) 'Hello, world!' signed = gpg.sign(Goodbye, world!, passphrase='secret') verified = verified = gpg.verify(str(signed)) print Verified if verified else Not verified 'Verified' For more information, visit http://code.google.com/p/python-gnupg/ - as always, your feedback is most welcome (especially bug reports, patches and suggestions for improvement). Enjoy! Cheers Vinay Sajip Red Dove Consultants Ltd. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
ANN: psyco V2
Announcing Psyco V2 source release -- This is the long awaited announcement of Psyco V2. Psyco V2 is a continuation of the well-known psyco project, which was called finished and was dis-continued by its author Armin Rigo in 2005, in favor of the PyPy project. This is a new project, using Psyco's code base with permission of Armin. Questions aqnd complaints should go to me (tis...@stackless.com) or the mailing list (psyco-de...@lists.sourceforge.net); Armin is explicitly not in charge of (t)his project any longer! As one of the founders and an active member of the PyPy project, I was very happy to be invited to work on Psyco V2, by FATTOC, LLC. Psyco V2 tries to extend on the original Psyco approach an extension module that just makes Python faster. Psyco is a just-in-time compiler that accelerates arbitrary Python code by specialization. We believe that Psyco's approach can be carried out much further than it was tried so far, when it's first version was abandoned. This first V2 release is source-only. There is no web-site, yet, and there are no binaries for download. These will be available in a few days on http://www.psyco.org . For the time being, please stick with subversion access, building the extension module from source code. The repository is here: http://codespeak.net/svn/psyco/v2/dist Check-out the repository, and run the setup.py script, given that you have access to a C compiler. Psyco V2 will run on X86 based 32 bit Linux, 32 bit Windows, and Mac OS X. Psyco is not supporting 64 bit, yet. But it is well being considered. The current improvements are, shortly: - Support for Python 2.4, 2.5 and 2.6 - a lot of new builtins - generators, fast and fully supported. More information is coming soon on http://www.psyco.org . This is the beginning of a series of new Psyco versions. Many more improvements are prepared and about to be published, soon, starting with the current version 2.0.0 . Stay tuned, this is just the beginning of psyco's re-birth! For questions about Psyco V2, please join the mailing list psyco-de...@lists.sourceforge.net or contact me on IRC: #psyco on irc.freenode.net . Psyco V2 is fundamentally supported by FATTOC, LLC. See http://www.fattoc.com . Without their continuous support, this work would not have been possible at all. I wish to express my deepest thanks to FATTOC, for allowing me to continue on Psyco with all the energy that this ambitious project needs, and will need. Further special thanks are going to Armin Rigo, John Benediktsson, David Salomon, Miki Tebeka, Raymond Hettinger, Fabrizio Milo, Michael Foord, Dinu Gherman, Stephan Diehl, Laura Creighton and Andrea Tismer, for all the support and discussions. Looking forward to a great future of Psyco! July 17, 2009 -- Christian Tismer :^) mailto:tis...@stackless.com tismerysoft GmbH : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9A :*Starship* http://starship.python.net/ 14109 Berlin : PGP key - http://wwwkeys.pgp.net/ work +49 30 802 86 56 mobile +49 173 24 18 776 fax +49 30 80 90 57 05 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
Re: Why not enforce four space indentations in version 3.x?
On Jul 15, 2009, at 4:26 PM, David Bolen wrote: Miles Kaufmann mile...@umich.edu writes: On Jul 14, 2009, at 5:06 PM, David Bolen wrote: Are you sure? It seems to restrict them in the same block, but not in the entire file. At least I was able to use both space and tab indented blocks in the same file with Python 3.0 and 3.1. It seems to me that, within an indented block, Python 3.1 requires that you are consistent in your use of indentation characters *for that indentation level*. For example, the following code seems to be allowed: Um, right - in other words, what I said :-) I wasn't trying to correct you, just being more explicit. :) After reading your post, I still wasn't sure if the restriction on mixing spaces and tabs applied to nested blocks--I was surprised that the code sample I included was allowed. -Miles -- http://mail.python.org/mailman/listinfo/python-list
Why aren't OrderedDicts comparable with etc?
Hi, I'm just wondering why , =, =, and are not supported by collections.OrderedDict: d1 = collections.OrderedDict(((a,1),(z,2),(k,3))) d2 = d1.copy() d2[z] = 4 d1 == d2 False d1 d2 Traceback (most recent call last): File pyshell#6, line 1, in module d1 d2 TypeError: unorderable types: OrderedDict() OrderedDict() It just seems to me that since the items in ordered dictionaries are ordered, it would make sense to do an item by item comparison from first to last item in exactly the same way that Python compares lists or tuples? -- http://mail.python.org/mailman/listinfo/python-list
Re: import module unbelieveable behaviour
On Thursday 16 July 2009 07:38:23 Carl Banks wrote: On Jul 15, 10:16 pm, Peter Fodrek peter.fod...@stuba.sk wrote: On Wednesday 15 July 2009 17:41:54 Diez B. Roggisch wrote: Peter Fodrek wrote: .. What does import nc print nc.__file__ python Python 2.6 (r26:66714, Feb 3 2009, 20:49:49) [GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2 Type help, copyright, credits or license for more information. import nc print nc.__file__ nc/__init__.pyc What does it do if you run this from a script? Ouch, I am and python rookie, that was needed to try to edit undocumented script from German author this answers everything /home/opt/HeeksCAD8/HeeksCNC python ./test.py /usr/local/lib/heekscnc/nc/__init__.py and it is because begining of the script # -*- coding: utf-8 -*- import sys sys.path.insert(0,'/usr/local/lib/heekscnc/') import kurve import kurve_funcs from nc.nc import * import nc print nc.__file__ import nc.rez and ls -a /usr/local/lib/heekscnc/nc . emc2_read.pyhpgl2dv_read.py iso_codes.py nc_read.py .. hpgl2d.py hpgl3d.pyiso.pynum_reader.py attach.py hpgl2d_read.py hpgl3d_read.py iso_read.py siegkx1.py emc2.pyhpgl2dv.py __init__.py nc.py siegkx1_read.py Thank you for your help, once more. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: import module unbelieveable behaviour
On Thursday 16 July 2009 08:38:57 Peter Fodrek wrote: On Thursday 16 July 2009 07:38:23 Carl Banks wrote: On Jul 15, 10:16 pm, Peter Fodrek peter.fod...@stuba.sk wrote: On Wednesday 15 July 2009 17:41:54 Diez B. Roggisch wrote: sys.path.insert(0,'/usr/local/lib/heekscnc/') I was mentioned that this adds system path to multipath list(As $PATH) and it replaces path instead. That was problem.. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Why aren't OrderedDicts comparable with etc?
On Thu, Jul 16, 2009 at 2:21 AM, Mark Summerfieldl...@qtrac.plus.com wrote: Hi, I'm just wondering why , =, =, and are not supported by collections.OrderedDict: d1 = collections.OrderedDict(((a,1),(z,2),(k,3))) d2 = d1.copy() d2[z] = 4 d1 == d2 False d1 d2 Traceback (most recent call last): File pyshell#6, line 1, in module d1 d2 TypeError: unorderable types: OrderedDict() OrderedDict() It just seems to me that since the items in ordered dictionaries are ordered, it would make sense to do an item by item comparison from first to last item in exactly the same way that Python compares lists or tuples? import this In the face of ambiguity, refuse the temptation to guess. It isn't an OrderedDict thing, it is a comparison thing. Two regular dicts also raise an error if you try to LT them. What does it mean for a dict to be greater than or less than its peer? Nothing, so we refuse to guess. -Jack -- http://mail.python.org/mailman/listinfo/python-list
Re: Why aren't OrderedDicts comparable with etc?
On 16 July, 08:12, Jack Diederich jackd...@gmail.com wrote: On Thu, Jul 16, 2009 at 2:21 AM, Mark Summerfieldl...@qtrac.plus.com wrote: Hi, I'm just wondering why , =, =, and are not supported by collections.OrderedDict: d1 = collections.OrderedDict(((a,1),(z,2),(k,3))) d2 = d1.copy() d2[z] = 4 d1 == d2 False d1 d2 Traceback (most recent call last): File pyshell#6, line 1, in module d1 d2 TypeError: unorderable types: OrderedDict() OrderedDict() It just seems to me that since the items in ordered dictionaries are ordered, it would make sense to do an item by item comparison from first to last item in exactly the same way that Python compares lists or tuples? import this In the face of ambiguity, refuse the temptation to guess. It isn't an OrderedDict thing, it is a comparison thing. Two regular dicts also raise an error if you try to LT them. What does it mean for a dict to be greater than or less than its peer? Nothing, so we refuse to guess. -Jack You are right that it doesn't make sense to compare two dicts. But OrderedDicts can be viewed logically as lists of (key,value) tuples so they are much more like lists or tuples when it comes to comparisons. For example: l = [(a, 1), (z, 2), (k, 3)] l1 = l[:] l1[1] = (z, 5) l l1 True But if you do: d = collections.OrderedDict(l) d1 = collections.OrderedDict(l1) You can't use , =, =, or , even though ordered dictionaries preserve the order and their items are just as comparable as those in a list or tuple of tuples. -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeEncodeError: 'ascii' codec can't encode character u'\xb7' in position 13: ordinal not in range(128)
akhil1988 wrote: Sorry, it is sgmllib.py and not sgmmlib.py Oh, that bug again. See http://bugs.python.org/issue1651995 It's a bug in SGMLParser. When Python 2.5 restricted ASCII to 0..127, SGMLParser needed to be modified, but wasn't. I reported that bug in February 2007. It was fixed in Python 2.6 and 3.0 on March 31, 2009. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Why aren't OrderedDicts comparable with etc?
On Wed, Jul 15, 2009 at 11:21 PM, Mark Summerfieldl...@qtrac.plus.com wrote: Hi, I'm just wondering why , =, =, and are not supported by collections.OrderedDict: d1 = collections.OrderedDict(((a,1),(z,2),(k,3))) d2 = d1.copy() d2[z] = 4 d1 == d2 False d1 d2 Traceback (most recent call last): File pyshell#6, line 1, in module d1 d2 TypeError: unorderable types: OrderedDict() OrderedDict() It just seems to me that since the items in ordered dictionaries are ordered, it would make sense to do an item by item comparison from first to last item in exactly the same way that Python compares lists or tuples? Use case? I'm curious. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: missing 'xor' Boolean operator
Hrvoje Niksic hnik...@x..s.org wrote: Note that in Python A or B is in fact not equivalent to not(not A and not B). De Morgan would turn in his grave. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: missing 'xor' Boolean operator
On Thu, 16 Jul 2009 09:43:53 +0200, Hendrik van Rooyen wrote: Hrvoje Niksic hnik...@x..s.org wrote: Note that in Python A or B is in fact not equivalent to not(not A and not B). De Morgan would turn in his grave. No he wouldn't. Python isn't Boolean algebra, and there is no requirement to limit Python's operators to the semantics of Boolean algebra. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: missing 'xor' Boolean operator
Nobody wrote: On Wed, 15 Jul 2009 21:05:16 +0200, Jean-Michel Pichavant wrote: So if I resume: - not 'foo' = False - 'foo' or 'foo' = 'foo' I may be missing something, but honestly, Guido must have smoked some heavy stuff to write such logic, has he ? Several languages (e.g. Lisp, Bourne shell) behave the same way, i.e. or returns the first element which is considered true while and returns the last element provided that all preceding elements are considered true. [snip] Ok then, why or does not return True, if the first element is considered True ? Why returning the element itself. Any reason for that ? Because it's confusing, maybe people used to that logic find it obvious, but I really don't. JM -- http://mail.python.org/mailman/listinfo/python-list
How to search this newsgroup by a python script.
Hi, I haven't found anything with Google's group search, so let me ask it (again?). How can I search this newsgroup from within a Python script. (Perhaps by searching Google Groups or Gmane by some Python code.) Many thanks for a hint, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: Why aren't OrderedDicts comparable with etc?
Mark l...@qtrac.plus.com (M) wrote: M You are right that it doesn't make sense to compare two dicts. M But OrderedDicts can be viewed logically as lists of (key,value) M tuples so they are much more like lists or tuples when it comes to M comparisons. M For example: l = [(a, 1), (z, 2), (k, 3)] l1 = l[:] l1[1] = (z, 5) l l1 M True M But if you do: d = collections.OrderedDict(l) d1 = collections.OrderedDict(l1) M You can't use , =, =, or , even though ordered dictionaries M preserve the order and their items are just as comparable as those in M a list or tuple of tuples. But why should the order be as if the OrderedDict was a list of tuples. A dict can be considered as a mapping and then you might want to treat either the key or the value as contravariant (the key I guess). So there is ambiguity. Why would the view as a list of tuples for the ordering be the `natural' view? Maybe you may expect some kind of monotonicity such that d1d2 implies d1[x]d2[x], but that doesn't work for d1 = {1:10, 2:20} and d2 = {1:15, 2:5}. So maybe there is only a partial ordering? -- Piet van Oostrum p...@cs.uu.nl URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org -- http://mail.python.org/mailman/listinfo/python-list
Re: A Bug By Any Other Name ...
On Jul 7, 2:00 pm, Steven D'Aprano st...@remove-this- cybersource.com.au wrote: On Mon, 06 Jul 2009 22:18:20 -0700, Chris Rebert wrote: Not so rare. Decimal uses unary plus. Don't assume +x is a no-op. [...] Well, yes, but when would you apply it twice in a row? My point was that unary + isn't a no-op, and therefore neither is ++. For Decimal, I can't think why you'd want to apply ++x, but for other objects, who knows? Here's a toy example: class Spam(str): ... def __pos__(self): ... return self.__class__(spam + self) ... s = Spam() s 'spam spam spam spam ' Here's another toy example: class Toy(int): def __init__(self, value): self._incrd = False int.__init__(self, value) def incrHalf(self): self._incrd = True def __pos__(self): if self._incrd: return self.__class__(self+1) else: p = self.__class__(self) p.incrHalf() return p def __add__(self, other): return self.__class__(int(self)+other) nows122[126]~% python -i toy.py i=Toy(5) +i 5 ++i 6 +++i 6 +i++i 10 +(+i++i) 10 (++i)++i 11 -- http://mail.python.org/mailman/listinfo/python-list
Re: How to search this newsgroup by a python script.
On Thu, Jul 16, 2009 at 2:12 AM, Helmut Jarauschjarau...@igpm.rwth-aachen.de wrote: Hi, I haven't found anything with Google's group search, so let me ask it (again?). How can I search this newsgroup from within a Python script. (Perhaps by searching Google Groups or Gmane by some Python code.) 1. Generate URL of the form: http://search.gmane.org/?query=foogroup=gmane.comp.python.general where foo is the search terms, with proper URL escaping applied. 2. Fetch URL using urllib - http://docs.python.org/library/urllib.html 3. Parse resulting HTML page (e.g. using BeautifulSoup) 4. Extract desired information from search results using the parse tree. 5. ??? 6. Profit! Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to search this newsgroup by a python script.
Chris Rebert wrote: On Thu, Jul 16, 2009 at 2:12 AM, Helmut Jarauschjarau...@igpm.rwth-aachen.de wrote: Hi, I haven't found anything with Google's group search, so let me ask it (again?). How can I search this newsgroup from within a Python script. (Perhaps by searching Google Groups or Gmane by some Python code.) 1. Generate URL of the form: http://search.gmane.org/?query=foogroup=gmane.comp.python.general where foo is the search terms, with proper URL escaping applied. 2. Fetch URL using urllib - http://docs.python.org/library/urllib.html 3. Parse resulting HTML page (e.g. using BeautifulSoup) 4. Extract desired information from search results using the parse tree. 5. ??? 6. Profit! Alternatively, you could do something with the mailing list archive: http://mail.python.org/pipermail/python-list/ The .gz files are gzipped mbox format so can be dropped into, eg, Thunderbird for offline browsing, or searched with the email package from the stdlib. TJG -- http://mail.python.org/mailman/listinfo/python-list
using timers to force an execution time
hello. based upon previuos suggestions, i tried to write a program in which i would like to have a certain code fragment to execute only for a specified amount of time (say 3 seconds), then bail out. but i get the following: $ cat tmr004.py #!/usr/bin/python -u import threading , time e = threading.Event() t = threading.Timer(3.0, e.set) t.start() print time.asctime(time.localtime(time.time())) while not e.isSet(): for repeat in range(10): print time.time() time.sleep(0.66) print time.asctime(time.localtime(time.time())) $ ./tmr004.py Thu Jul 16 12:31:27 2009 1247740287.44 1247740288.1 1247740288.76 1247740289.42 1247740290.08 1247740290.74 1247740291.4 1247740292.06 1247740292.72 1247740293.38 Thu Jul 16 12:31:34 2009 $ see? the while body ran for about 7 seconds... i bet it has to do with the fact that the timer does not control inner loops... any suggestion? $ python -V Python 2.3.4 $ uname -a Linux fisso 2.4.24 #1 Thu Feb 12 19:49:02 CET 2004 i686 GNU/Linux $ bye -- http://mail.python.org/mailman/listinfo/python-list
Re: using timers to force an execution time
On Thu, Jul 16, 2009 at 6:34 PM, superpollo u...@example.net wrote: hello. based upon previuos suggestions, i tried to write a program in which i would like to have a certain code fragment to execute only for a specified amount of time (say 3 seconds), then bail out. snip see? the while body ran for about 7 seconds... i bet it has to do with the fact that the timer does not control inner loops... any suggestion? I'm guessing it has to do with a sleep of 0.66 seconds x 10 times = sleep for 6.6 seconds, and then it checks for e.isSet(). Best regards, Ching-Yun Xavier Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: cont...@xavierho.com Website: http://xavierho.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Why aren't OrderedDicts comparable with etc?
On 16 July, 10:21, Piet van Oostrum p...@cs.uu.nl wrote: Mark l...@qtrac.plus.com (M) wrote: M You are right that it doesn't make sense to compare two dicts. M But OrderedDicts can be viewed logically as lists of (key,value) M tuples so they are much more like lists or tuples when it comes to M comparisons. M For example: l = [(a, 1), (z, 2), (k, 3)] l1 = l[:] l1[1] = (z, 5) l l1 M True M But if you do: d = collections.OrderedDict(l) d1 = collections.OrderedDict(l1) M You can't use , =, =, or , even though ordered dictionaries M preserve the order and their items are just as comparable as those in M a list or tuple of tuples. But why should the order be as if the OrderedDict was a list of tuples. A dict can be considered as a mapping and then you might want to treat either the key or the value as contravariant (the key I guess). So there is ambiguity. Why would the view as a list of tuples for the ordering be the `natural' view? Maybe you may expect some kind of monotonicity such that d1d2 implies d1[x]d2[x], but that doesn't work for d1 = {1:10, 2:20} and d2 = {1:15, 2:5}. So maybe there is only a partial ordering? OK, that seems to me to be a convincing argument against supporting ordering. -- http://mail.python.org/mailman/listinfo/python-list
turtle dump
hi there. is there a way to dump the content of a turtle window to a file or a file object? bye -- http://mail.python.org/mailman/listinfo/python-list
Re: Why aren't OrderedDicts comparable with etc?
On 16 July, 08:51, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: On Thu, 16 Jul 2009 00:30:26 -0700, Chris Rebert wrote: On Wed, Jul 15, 2009 at 11:21 PM, Mark Summerfieldl...@qtrac.plus.com wrote: Hi, I'm just wondering why , =, =, and are not supported by collections.OrderedDict: d1 = collections.OrderedDict(((a,1),(z,2),(k,3))) d2 = d1.copy() d2[z] = 4 d1 == d2 False d1 d2 Traceback (most recent call last): File pyshell#6, line 1, in module d1 d2 TypeError: unorderable types: OrderedDict() OrderedDict() It just seems to me that since the items in ordered dictionaries are ordered, it would make sense to do an item by item comparison from first to last item in exactly the same way that Python compares lists or tuples? Use case? I'm curious. Surely it would be the same use case as for comparing two lists? There doesn't need to be a special OrderedDict use case beyond an OrderedDict is just like a list of (key,value) tuples, but searches are faster. Or maybe not. If OrderedDicts are sequences as well as mappings, then we should be able to sort them. And that seems a bit much even for me. -- Steven One thing that I've just noticed is that you can use , =, =, and with sets: s1 = {1,2,3} s2 = {1,2,4} s1 == s2 False s1 s2 False s1 = s2 False s2 s1 False s2 = s1 False s1 != s2 True It seems a bit inconsistent that with sets you always get False when using an ordering operator but with an ordered dict you get an exception? -- http://mail.python.org/mailman/listinfo/python-list
Re: using timers to force an execution time
superpollo wrote: hello. based upon previuos suggestions, i tried to write a program in which i would like to have a certain code fragment to execute only for a specified amount of time (say 3 seconds), then bail out. but i get the following: $ cat tmr004.py #!/usr/bin/python -u import threading , time e = threading.Event() t = threading.Timer(3.0, e.set) t.start() print time.asctime(time.localtime(time.time())) while not e.isSet(): for repeat in range(10): print time.time() time.sleep(0.66) print time.asctime(time.localtime(time.time())) $ ./tmr004.py Thu Jul 16 12:31:27 2009 1247740287.44 1247740288.1 1247740288.76 1247740289.42 1247740290.08 1247740290.74 1247740291.4 1247740292.06 1247740292.72 1247740293.38 Thu Jul 16 12:31:34 2009 $ see? the while body ran for about 7 seconds... i bet it has to do with the fact that the timer does not control inner loops... any suggestion? Of course the inner loop isn't affected by the set event - how should it be, if you don't check it. if you rewrite it as this: while True: for repeat in range(10): if e.isSet(): break print time.time() time.sleep(.66) it should terminate earlier. What you can't achieve in python without major black magic hackery that is very dangerous is to terminate a thread while it is executing. Termination has to be co-operative. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Why aren't OrderedDicts comparable with etc?
On 16 July, 11:58, Mark l...@qtrac.plus.com wrote: On 16 July, 08:51, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: On Thu, 16 Jul 2009 00:30:26 -0700, Chris Rebert wrote: On Wed, Jul 15, 2009 at 11:21 PM, Mark Summerfieldl...@qtrac.plus.com wrote: Hi, I'm just wondering why , =, =, and are not supported by collections.OrderedDict: d1 = collections.OrderedDict(((a,1),(z,2),(k,3))) d2 = d1.copy() d2[z] = 4 d1 == d2 False d1 d2 Traceback (most recent call last): File pyshell#6, line 1, in module d1 d2 TypeError: unorderable types: OrderedDict() OrderedDict() It just seems to me that since the items in ordered dictionaries are ordered, it would make sense to do an item by item comparison from first to last item in exactly the same way that Python compares lists or tuples? Use case? I'm curious. Surely it would be the same use case as for comparing two lists? There doesn't need to be a special OrderedDict use case beyond an OrderedDict is just like a list of (key,value) tuples, but searches are faster. Or maybe not. If OrderedDicts are sequences as well as mappings, then we should be able to sort them. And that seems a bit much even for me. -- Steven One thing that I've just noticed is that you can use , =, =, and with sets: s1 = {1,2,3} s2 = {1,2,4} s1 == s2 False s1 s2 False s1 = s2 False s2 s1 False s2 = s1 False s1 != s2 True It seems a bit inconsistent that with sets you always get False when using an ordering operator but with an ordered dict you get an exception? Ooops---disregard the above---I forgot that these do subset and superset comparisions! -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeEncodeError: 'ascii' codec can't encode character u'\xb7' in position 13: ordinal not in range(128)
I have switched to python 3.1 , but now I am getting some syntax errors in the code: File ./customWikiExtractor.py, line 81 __char_entities = {'nbsp;' :u'\u00A0', 'iexcl;' :u'\u00A1', 'cent;':u'\u00A2', ^ SyntaxError: invalid syntax line 81 is: __char_entities = {'nbsp;' :u'\u00A0', 'iexcl;' :u'\u00A1', 'cent;' :u'\u00A2', 'pound;' :u'\u00A3', 'curren;':u'\u00A4', 'yen;' :u'\u00A5', 'brvbar;' :u'\u00A6', 'sect;' :u'\u00A7', 'uml;' :u'\u00A8', 'copy;' :u'\u00A9', 'ordf;' :u'\u00AA', 'laquo;' :u'\u00AB', 'not;':u'\u00AC', 'shy;' :u'\u00AD', 'reg;' :u'\u00AE', 'macr;' :u'\u00AF', 'deg;' :u'\u00B0', 'plusmn;' :u'\u00B1', 'sup2;' :u'\u00B2', 'sup3;' :u'\u00B3', 'acute;' :u'\u00B4', 'micro;' :u'\u00B5', 'para;' :u'\u00B6', 'middot;' :u'\u00B7', 'cedil;' :u'\u00B8', 'sup1;' :u'\u00B9', 'ordm;':u'\u00BA',} --Akhil John Nagle-2 wrote: akhil1988 wrote: Sorry, it is sgmllib.py and not sgmmlib.py Oh, that bug again. See http://bugs.python.org/issue1651995 It's a bug in SGMLParser. When Python 2.5 restricted ASCII to 0..127, SGMLParser needed to be modified, but wasn't. I reported that bug in February 2007. It was fixed in Python 2.6 and 3.0 on March 31, 2009. John Nagle -- http://mail.python.org/mailman/listinfo/python-list -- View this message in context: http://www.nabble.com/UnicodeEncodeError%3A-%27ascii%27-codec-can%27t-encode-character-u%27%5Cxb7%27-in-position-13%3A-ordinal-not-in-range%28128%29-tp24509879p24514309.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeEncodeError: 'ascii' codec can't encode character u'\xb7' in position 13: ordinal not in range(128)
Please click reply on the post and then read this reply in the editor. Actually, some sequences have been replaced to their graphical form when this post is published. So the python code is being displayed, what actually it is not. --Akhil akhil1988 wrote: I have switched to python 3.1 , but now I am getting some syntax errors in the code: File ./customWikiExtractor.py, line 81 __char_entities = {'nbsp;' :u'\u00A0', 'iexcl;' :u'\u00A1', 'cent;':u'\u00A2', ^ SyntaxError: invalid syntax line 81 is: __char_entities = {'nbsp;' :u'\u00A0', 'iexcl;' :u'\u00A1', 'cent;' :u'\u00A2', 'pound;' :u'\u00A3', 'curren;':u'\u00A4', 'yen;' :u'\u00A5', 'brvbar;' :u'\u00A6', 'sect;' :u'\u00A7', 'uml;' :u'\u00A8', 'copy;' :u'\u00A9', 'ordf;' :u'\u00AA', 'laquo;' :u'\u00AB', 'not;':u'\u00AC', 'shy;' :u'\u00AD', 'reg;' :u'\u00AE', 'macr;' :u'\u00AF', 'deg;' :u'\u00B0', 'plusmn;' :u'\u00B1', 'sup2;' :u'\u00B2', 'sup3;' :u'\u00B3', 'acute;' :u'\u00B4', 'micro;' :u'\u00B5', 'para;' :u'\u00B6', 'middot;' :u'\u00B7', 'cedil;' :u'\u00B8', 'sup1;' :u'\u00B9', 'ordm;':u'\u00BA',} --Akhil John Nagle-2 wrote: akhil1988 wrote: Sorry, it is sgmllib.py and not sgmmlib.py Oh, that bug again. See http://bugs.python.org/issue1651995 It's a bug in SGMLParser. When Python 2.5 restricted ASCII to 0..127, SGMLParser needed to be modified, but wasn't. I reported that bug in February 2007. It was fixed in Python 2.6 and 3.0 on March 31, 2009. John Nagle -- http://mail.python.org/mailman/listinfo/python-list -- View this message in context: http://www.nabble.com/UnicodeEncodeError%3A-%27ascii%27-codec-can%27t-encode-character-u%27%5Cxb7%27-in-position-13%3A-ordinal-not-in-range%28128%29-tp24509879p24514367.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: using timers to force an execution time
Diez B. Roggisch wrote: What you can't achieve in python without major black magic hackery that is very dangerous is to terminate a thread while it is executing. Termination has to be co-operative. i see. thanks a lot. bye -- http://mail.python.org/mailman/listinfo/python-list
Re: using timers to force an execution time
Diez B. Roggisch wrote: superpollo wrote: hello. based upon previuos suggestions, i tried to write a program in which i would like to have a certain code fragment to execute only for a specified amount of time (say 3 seconds), then bail out. but i get the following: $ cat tmr004.py #!/usr/bin/python -u import threading , time e = threading.Event() t = threading.Timer(3.0, e.set) t.start() print time.asctime(time.localtime(time.time())) while not e.isSet(): for repeat in range(10): print time.time() time.sleep(0.66) print time.asctime(time.localtime(time.time())) $ ./tmr004.py Thu Jul 16 12:31:27 2009 1247740287.44 1247740288.1 1247740288.76 1247740289.42 1247740290.08 1247740290.74 1247740291.4 1247740292.06 1247740292.72 1247740293.38 Thu Jul 16 12:31:34 2009 $ see? the while body ran for about 7 seconds... i bet it has to do with the fact that the timer does not control inner loops... any suggestion? Of course the inner loop isn't affected by the set event - how should it be, if you don't check it. if you rewrite it as this: while True: for repeat in range(10): if e.isSet(): break print time.time() time.sleep(.66) it should terminate earlier. This is of course wrong, remove the outer while Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: using timers to force an execution time
Diez B. Roggisch wrote: superpollo wrote: see? the while body ran for about 7 seconds... i bet it has to do with the fact that the timer does not control inner loops... any suggestion? Of course the inner loop isn't affected by the set event - how should it be, if you don't check it. if you rewrite it as this: while True: for repeat in range(10): if e.isSet(): break print time.time() time.sleep(.66) it should terminate earlier. so it seems almost impossible to allocate a certain amount of time to a code fragment *without* somehow rewriting its logic? am i wrong? bye -- http://mail.python.org/mailman/listinfo/python-list
Re: using timers to force an execution time
superpollo wrote: Diez B. Roggisch wrote: superpollo wrote: see? the while body ran for about 7 seconds... i bet it has to do with the fact that the timer does not control inner loops... any suggestion? Of course the inner loop isn't affected by the set event - how should it be, if you don't check it. if you rewrite it as this: while True: for repeat in range(10): if e.isSet(): break print time.time() time.sleep(.66) it should terminate earlier. so it seems almost impossible to allocate a certain amount of time to a code fragment *without* somehow rewriting its logic? am i wrong? No, you are right, for threads that is. You can try trick around with the trace-functionality of python, and some ctypes-based system-thread-module-tricks that are, as mentioned before, black-magic a spinning gatling gun pointed to your very own lower extremities. The only reliable way of terminating an asynchronous computation is to use processes, since python2.6 that's rather convenient with the multiprocessing-module. However, that imposes some limits to what you can do. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: using timers to force an execution time
Diez B. Roggisch wrote: superpollo wrote: am i wrong? No, you are right, for threads that is. You can try trick around with the trace-functionality of python, and some ctypes-based system-thread-module-tricks that are, as mentioned before, black-magic a spinning gatling gun pointed to your very own lower extremities. OUCH. The only reliable way of terminating an asynchronous computation is to use processes, since python2.6 that's rather convenient with the multiprocessing-module. However, that imposes some limits to what you can do. fair enough. very helpful indeed. bye -- http://mail.python.org/mailman/listinfo/python-list
Re: turtle dump
superpollo wrote: hi there. is there a way to dump the content of a turtle window to a file or a file object? Why should I want to dump a turtle? They are very benign creatures, dumping them is going to hurt them needlessly. Without a cheek-in-tongue: how are we supposed to know what aturtle window is, how you create it, what features it uses? You need to give more details, such as the module you are using, on what system that runs and so forth. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: turtle dump
Diez B. Roggisch wrote: superpollo wrote: hi there. is there a way to dump the content of a turtle window to a file or a file object? Why should I want to dump a turtle? They are very benign creatures, dumping them is going to hurt them needlessly. lol. ;-) the title was indeed supposed to stir a bit of curiosity upon the reader... Without a cheek-in-tongue: how are we supposed to know what aturtle window is, how you create it, what features it uses? You need to give more details, such as the module you are using, on what system that runs and so forth. in fact i was looking for a *platform independent* way to draw into a graphics file (say, a postscript or a png) using the turtle module. so i understand that dumping a window is not a good expression... maybe redirecting graphics commands to a file instead of a window? bye -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeEncodeError: 'ascii' codec can't encode character u'\xb7' in position 13: ordinal not in range(128)
On Jul 16, 9:00 pm, akhil1988 akhilan...@gmail.com wrote: I have switched to python 3.1 , but now I am getting some syntax errors in the code: Python 3.x was a major release that endeavoured to clean up a number of lingering issues with the language, the upshot being that it isn't entirely backwards compatible with past versions. Unicode became the default string type, which is what is causing the error here: the u- prefix is no longer required (or even allowed). However, Py3.x _does_ come with a handy tool for automatically converting Python 2.x code to 3.x, called 2to3. One of the things it should do is convert Py2.x unicode values into their correct representation in 3.x. With any luck, it should be able to convert the code you're using entirely. Let us know how it goes. -- http://mail.python.org/mailman/listinfo/python-list
Re: turtle dump
On Jul 16, 9:18 pm, superpollo u...@example.net wrote: lol. ;-) the title was indeed supposed to stir a bit of curiosity upon the reader... Which isn't really useful when trying to obtain assistance... you want certainty, not curiosity. in fact i was looking for a *platform independent* way to draw into a graphics file (say, a postscript or a png) using the turtle module. so i understand that dumping a window is not a good expression... maybe redirecting graphics commands to a file instead of a window? You didn't actually answer Diez question. The turtle module is only a recent (2.6/3.0) addition to Python and is probably obscure enough not to have tracked across everyone's radar. So _if_ you're talking about the standard lib turtle module, you're not looking to 'dump a window', you're looking to write the contents of turtle.Canvas to file. Canvas only supports writing to postscript, so you'll have to do something like this (untested): import turtle screen = turtle.Screen() # go go gadget turtle... screen._canvas.postscript(file='turtle.ps') Or it may be open('turtle.ps','w').write(screen._canvas.postscript ())... I couldn't find a definitive answer. Try looking through the Tk docs, it should be covered there. Note that this is a postscript _text_ file, so you'll also need to find something to render it with. Hope this helps point you in the right direction. -- http://mail.python.org/mailman/listinfo/python-list
Re: turtle dump
alex23 wrote: On Jul 16, 9:18 pm, superpollo u...@example.net wrote: lol. ;-) the title was indeed supposed to stir a bit of curiosity upon the reader... Which isn't really useful when trying to obtain assistance... you want certainty, not curiosity. ok. my bad. in fact i was looking for a *platform independent* way to draw into a graphics file (say, a postscript or a png) using the turtle module. so i understand that dumping a window is not a good expression... maybe redirecting graphics commands to a file instead of a window? You didn't actually answer Diez question. The turtle module is only a recent (2.6/3.0) addition to Python and is probably obscure enough not to have tracked across everyone's radar. actually i am still using 2.3.4, which means that... screen = turtle.Screen() ... is not possible Hope this helps point you in the right direction. it certainly did, tahnks. bye -- http://mail.python.org/mailman/listinfo/python-list
Re: turtle dump
Superchicken: is there a way to dump the content of a turtle window to a file or a file object? A possible low-tech solution is to append to a list the sequence of your plotting commands (using a decorator too, even, something like the logging decorator), and then save all of them at the end into a text file :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Persistent variable in subprocess using multiprocessing?
mheavner miheav...@gmail.com (m) wrote: m I'm using multiprocessing to spawn several subprocesses, each of which m uses a very large data structure (making it impractical to pass it via m pipes / pickling). I need to allocate this structure once when the m process is created and have it remain in memory for the duration of m the process. The way the multiprocessing module is set up, only the m 'run' method runs within the subprocess - so creating a wrapper class m with a constructor that allocates the structure in __init__ will not m work, as far as I know, as this will still be within the parent m process. m If I were working in C/C++, I would declare the variable static m within the function body - is there any way with the multiprocessing m module to have persistent data members within subprocesses? m Any ideas?? Your post is not entirely clear. Is `the process' the same as `the subprocess'? Assuming it is, what is the problem? You can create the datastructure first thing in the run method can't you? Like this: from multiprocessing import Process from time import sleep from random import random class MyProcess(Process): def __init__(self, number): self.number = number Process.__init__(self) def run(self): print Process %s started % self.number self.data = range(self.number * 10, (self.number + 1) * 10) self.doit() def doit(self): for i in range(5): sleep(3 * random()) self.data[i] += i print self.data[i] processes = [] for k in range(10): p = MyProcess(k) p.start() processes.append(p) for p in processes: p.join() -- Piet van Oostrum p...@cs.uu.nl URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org -- http://mail.python.org/mailman/listinfo/python-list
Re: turtle dump
superpollo wrote: alex23 wrote: On Jul 16, 9:18 pm, superpollo u...@example.net wrote: lol. ;-) the title was indeed supposed to stir a bit of curiosity upon the reader... Which isn't really useful when trying to obtain assistance... you want certainty, not curiosity. ok. my bad. in fact i was looking for a *platform independent* way to draw into a graphics file (say, a postscript or a png) using the turtle module. so i understand that dumping a window is not a good expression... maybe redirecting graphics commands to a file instead of a window? You didn't actually answer Diez question. The turtle module is only a recent (2.6/3.0) addition to Python and is probably obscure enough not to have tracked across everyone's radar. actually i am still using 2.3.4, which means that... screen = turtle.Screen() ... is not possible Tested on 2.4: import turtle turtle.reset() for i in range(4): ... turtle.forward(50) ... turtle.right(90) ... turtle._canvas.postscript(file=tmp.ps) '' I think the big rewrite has happened in 2.6, so the above should also work in 2.3. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: turtle dump
Peter Otten wrote: Tested on 2.4: import turtle turtle.reset() for i in range(4): ... turtle.forward(50) ... turtle.right(90) ... turtle._canvas.postscript(file=tmp.ps) '' I think the big rewrite has happened in 2.6, so the above should also work in 2.3. Peter mr otten, you are great. bye -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing python list from C to python
/* the first telling */ (...) /* the third telling */ (...) /* the third telling */ - If you had loosened up on the sarcasm I would probably have read what you wrote more thoroughly instead of just skimming through it. Thanks for the help, but you should seriously consider doing something with your patronizing attitude. HTH, Hartley -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing python list from C to python
/* the first telling */ (...) /* the second telling */ (...) /* the third telling */ - If you had loosened up on the sarcasm I would probably have read what you wrote more thoroughly instead of just skimming through it. Thanks for the help, but you should seriously consider doing something with your patronizing attitude. HTH, Hartley -- http://mail.python.org/mailman/listinfo/python-list
Re: turtle dump
I got success with the following code (python 2.6.2): import turtle turtle.reset() for i in range(4): turtle.forward(50) turtle.right(90) can=turtle.getscreen().getcanvas() can.postscript(file=tmp.ps) -- The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing. - Vinod Valloppillil http://www.catb.org/~esr/halloween/halloween4.html -- http://mail.python.org/mailman/listinfo/python-list
Re: How to check if any item from a list of strings is in a big string?
Hi all, This was more a question of programming aesthetics for me than one of great practical significance. I was looking to perform a certain function on files in a directory so long as those files weren't found in certain standard directories. In other words, I was using os.walk () to get multiple root directory strings, and the lists of files in each directory. The function was to be performed on those files, so long as certain terms weren't in the root directory string. In actuality, I could have stuck with the helper function I created, but I'm always curious to see how well multiple lines of code can turn into fewer lines of code in python and retain the same functional value :) Matt On Jul 15, 6:46 am, denis denis-bz...@t-online.de wrote: Sure, Aho-Corasick is fast for fixedstrings; but without real numbers / a concrete goal Matt, how many words are you looking for, in how long a string ? a simple solution is good enough, satisficing. Matt asked how to make that function look nicer? but nice has many dimensions -- bicycles are nice for some tasks, Ferraris for others. Bythewayhttp://en.wikipedia.org/wiki/Aho-Corasick_algorithmhas a link to a Python implementation, alsohttp://en.wikipedia.org/wiki/Worse_is_Betteris fun. -- http://mail.python.org/mailman/listinfo/python-list
Re: Persistent variable in subprocess using multiprocessing?
On Jul 16, 8:39 am, Piet van Oostrum p...@cs.uu.nl wrote: mheavner miheav...@gmail.com (m) wrote: m I'm using multiprocessing to spawn several subprocesses, each of which m uses a very large data structure (making it impractical to pass it via m pipes / pickling). I need to allocate this structure once when the m process is created and have it remain in memory for the duration of m the process. The way the multiprocessing module is set up, only the m 'run' method runs within the subprocess - so creating a wrapper class m with a constructor that allocates the structure in __init__ will not m work, as far as I know, as this will still be within the parent m process. m If I were working in C/C++, I would declare the variable static m within the function body - is there any way with the multiprocessing m module to have persistent data members within subprocesses? m Any ideas?? Your post is not entirely clear. Is `the process' the same as `the subprocess'? Assuming it is, what is the problem? You can create the datastructure first thing in the run method can't you? Like this: from multiprocessing import Process from time import sleep from random import random class MyProcess(Process): def __init__(self, number): self.number = number Process.__init__(self) def run(self): print Process %s started % self.number self.data = range(self.number * 10, (self.number + 1) * 10) self.doit() def doit(self): for i in range(5): sleep(3 * random()) self.data[i] += i print self.data[i] processes = [] for k in range(10): p = MyProcess(k) p.start() processes.append(p) for p in processes: p.join() -- Piet van Oostrum p...@cs.uu.nl URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org 'The process' refers to the subprocess. I could do as you say, load the data structure each time, but the problem is that takes a considerable amount of time compared to the the actual computation with the data it contains. I'm using these processes within a loop as follows: # Don't recreate processes or Queues pop1 = Queue() pop2 = Queue() pop_out = Queue() p1 = CudaProcess(0, args=(costf,pop1,pop_out)) p2 = CudaProcess(1, args=(costf,pop2,pop_out)) # Main loop for i in range(maxiter): print 'ITERATION: '+str(i) if log != None: l = open(log,'a') l.write('Iteration: '+str(i)+'\n') l.close() # Split population in two pop1.putmany(pop[0:len(pop)/2]) pop2.putmany(pop[len(pop)/2:len(pop)]) # Start two processes if not p1.isAlive(): p1.start() print 'started %s'%str(p1.getPid()) else: p1.run() if not p2.isAlive(): p2.start() print 'started %s'%str(p2.getPid()) else: p2.run() . . . So I'd like to load that data into memory once and keep there as long as the process is alive (ideally when the subprocess is created, storing some sort of pointer to it), rather than loading it each time run is called for a process within the loop. Could be my CudaProcess class - I'll check out what Diez suggested and post back. -- http://mail.python.org/mailman/listinfo/python-list
Re: missing 'xor' Boolean operator
On Jul 15, 8:32 pm, Paul Rubin http://phr...@nospam.invalid wrote: Among other things, that uses quadratic time! Why do you want to keep popping items from that list instead of iterating through it anyway? Anyway, I think you wrote something close to this: ... Very true! I didn't think about the problems with pop(). I was using it as a shortcut for pulling off the first operand. I forgot that if you start with an initial operand of False, the result will be the same (0 xor X = X) While I'm not sure how useful it would be, here's a version of the first function that returns one of the operands (ala AND and OR), except in the case where there is an even number of True elements, where it returns False: def xor(*operands): r, rprime = False, False for x in operands: xprime = bool(x) if rprime: if xprime: r, rprime = False, False else: r, rprime = x, xprime return r xor(0, 0) 0 xor(0, 1) 1 xor(1, 0) 1 xor(1, 1) False xor(0, 1, 2) False xor(0, 1, 2, 3) 3 xor(None, []) [] -- http://mail.python.org/mailman/listinfo/python-list
Re: missing 'xor' Boolean operator
On 7/16/2009 2:06 AM Jean-Michel Pichavant said... Ok then, why or does not return True, if the first element is considered True ? Why returning the element itself. Any reason for that ? Because it's confusing, maybe people used to that logic find it obvious, but I really don't. For example, I sometimes use it to set defaults: daysInAdvance = int(inputVar) or 25 Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: using timers to force an execution time
superpollo u...@example.net wrote: Diez B. Roggisch wrote: superpollo wrote: am i wrong? No, you are right, for threads that is. You can try trick around with the trace-functionality of python, and some ctypes-based system-thread-module-tricks that are, as mentioned before, black-magic a spinning gatling gun pointed to your very own lower extremities. OUCH. The only reliable way of terminating an asynchronous computation is to use processes, since python2.6 that's rather convenient with the multiprocessing-module. However, that imposes some limits to what you can do. fair enough. Or if you are on unix you can use signals... It is probably just about acceptable to raise an exception in a signal handler like this code does. import signal, os, time class TimeOut(Exception): Thrown on alarm pass def sig_alarm(signum, frame): raise TimeOut() def time_out(t, fn, *args, **kwargs): Calls fn with the args and kwargs returning its result or raising a TimeOut exception if it doesn't complete within t seconds # Turn alarm off and read old value old_alarm = signal.alarm(0) # Install new handler remembering old old_handler = signal.signal(signal.SIGALRM, sig_alarm) # Set the timer going signal.alarm(t) try: rc = fn(*args, **kwargs) finally: # Restore the old handler signal.signal(signal.SIGALRM, old_handler) signal.alarm(0) def test(): for repeat in range(10): print time.time() time.sleep(0.66) if __name__ == __main__: try: time_out(3, test) except TimeOut: print timed out -- Nick Craig-Wood n...@craig-wood.com -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not enforce four space indentations in version 3.x?
On Jul 10, 7:35 pm, Ben Finney ben+pyt...@benfinney.id.au wrote: walterbyrd walterb...@iname.com writes: I believe Guido himself has said that all indentions should be four spaces - no tabs. Yes. That's a “should” and not a “must”, even though PEP 8 says it with a simple imperative:: Use 4 spaces per indentation level. That actually sounds pretty weird. Don't do {foo}. Really, I mean *really* don't do {foo}. Oh, also, the interpreter allows you to do {foo}. But don't do it! I mean it!. Very ... perlish, if you ask me. I realize that a small portion of the community likes the tabs. They're sold on the tabs. They like the tabs. But tabs are an archaic holdover from an era when typewriters had physical tabstops on them. Actually, after *that* they're a holdover from a program called `make` whose designers unfortunately decided to use tab characters to prefix commands. The tab is vestigial. Your text editor can treat 4 consecutive spaces as a unit if you wish. Let tabs go away. Stop using them. If your editor keeps irrationally inserting them, make it stop. -- http://mail.python.org/mailman/listinfo/python-list
Re: Persistent variable in subprocess using multiprocessing?
On Jul 16, 9:18 am, mheavner miheav...@gmail.com wrote: On Jul 16, 8:39 am, Piet van Oostrum p...@cs.uu.nl wrote: mheavner miheav...@gmail.com (m) wrote: m I'm using multiprocessing to spawn several subprocesses, each of which m uses a very large data structure (making it impractical to pass it via m pipes / pickling). I need to allocate this structure once when the m process is created and have it remain in memory for the duration of m the process. The way the multiprocessing module is set up, only the m 'run' method runs within the subprocess - so creating a wrapper class m with a constructor that allocates the structure in __init__ will not m work, as far as I know, as this will still be within the parent m process. m If I were working in C/C++, I would declare the variable static m within the function body - is there any way with the multiprocessing m module to have persistent data members within subprocesses? m Any ideas?? Your post is not entirely clear. Is `the process' the same as `the subprocess'? Assuming it is, what is the problem? You can create the datastructure first thing in the run method can't you? Like this: from multiprocessing import Process from time import sleep from random import random class MyProcess(Process): def __init__(self, number): self.number = number Process.__init__(self) def run(self): print Process %s started % self.number self.data = range(self.number * 10, (self.number + 1) * 10) self.doit() def doit(self): for i in range(5): sleep(3 * random()) self.data[i] += i print self.data[i] processes = [] for k in range(10): p = MyProcess(k) p.start() processes.append(p) for p in processes: p.join() -- Piet van Oostrum p...@cs.uu.nl URL:http://pietvanoostrum.com[PGP8DAE142BE17999C4] Private email: p...@vanoostrum.org 'The process' refers to the subprocess. I could do as you say, load the data structure each time, but the problem is that takes a considerable amount of time compared to the the actual computation with the data it contains. I'm using these processes within a loop as follows: # Don't recreate processes or Queues pop1 = Queue() pop2 = Queue() pop_out = Queue() p1 = CudaProcess(0, args=(costf,pop1,pop_out)) p2 = CudaProcess(1, args=(costf,pop2,pop_out)) # Main loop for i in range(maxiter): print 'ITERATION: '+str(i) if log != None: l = open(log,'a') l.write('Iteration: '+str(i)+'\n') l.close() # Split population in two pop1.putmany(pop[0:len(pop)/2]) pop2.putmany(pop[len(pop)/2:len(pop)]) # Start two processes if not p1.isAlive(): p1.start() print 'started %s'%str(p1.getPid()) else: p1.run() if not p2.isAlive(): p2.start() print 'started %s'%str(p2.getPid()) else: p2.run() . . . So I'd like to load that data into memory once and keep there as long as the process is alive (ideally when the subprocess is created, storing some sort of pointer to it), rather than loading it each time run is called for a process within the loop. Could be my CudaProcess class - I'll check out what Diez suggested and post back. Essentially, I'd like to sneak that allocation in somewhere after the fork is done (in start()) in the context of the subprocess, holding a pointer to that structure, but before all of the run() calls are done -- http://mail.python.org/mailman/listinfo/python-list
Re: turtle dump
On Jul 16, 10:11 pm, superpollo u...@example.net wrote: actually i am still using 2.3.4, which means that... screen = turtle.Screen() ... is not possible Ah, sorry about that. My belief that turtle was a new module was based on a line from http://us.pycon.org/media/2009/talkdata/PyCon2009/065/SevenWaysToUseTurtle-PyCon2007.pdf Since Python 2.6/3.0, Python has had a new turtle module. At which point I stopped reading and missed the following line: Its development was based entirely on the previous one. In my defence, I _had_ been drinking. Thankfully Peter stepped up with a more appropriate solution, and Michiel pointed out the more suitable API calls over dealing directly with the underlying implementation :) Good work guys! -- http://mail.python.org/mailman/listinfo/python-list
Re: using timers to force an execution time
2009/7/16 superpollo u...@example.net: hello. based upon previuos suggestions, i tried to write a program in which i would like to have a certain code fragment to execute only for a specified amount of time (say 3 seconds), then bail out. but i get the following: $ cat tmr004.py #!/usr/bin/python -u import threading , time e = threading.Event() t = threading.Timer(3.0, e.set) t.start() print time.asctime(time.localtime(time.time())) while not e.isSet(): for repeat in range(10): print time.time() time.sleep(0.66) print time.asctime(time.localtime(time.time())) $ ./tmr004.py Thu Jul 16 12:31:27 2009 1247740287.44 1247740288.1 1247740288.76 1247740289.42 1247740290.08 1247740290.74 1247740291.4 1247740292.06 1247740292.72 1247740293.38 Thu Jul 16 12:31:34 2009 $ see? the while body ran for about 7 seconds... i bet it has to do with the fact that the timer does not control inner loops... any suggestion? Clearly, this isn't what you are actually trying to do. For this case, your event is getting set when you expect, but your main thread does not check the event often enough to let it stop in a timely manner. To fix this, remove the inner for repeat in range(10) loop. But I assume that your real code isn't something that you can fix this easily. If you describe your real requirement, it may be possible to give you a better answer. (But that answer will almost certainly not be a way of interrupting one thread from another - that's not really possible with Python - but rather a way of achieving your goal without *needing* to interrupt one thread from another). Paul. PS If you really must interrupt one thread from another, you can use C code (or ctypes) to call the PyThreadState_SetAsyncExc API. But I'm not going to tell you how, as it's almost certainly *not* what you want to do in practice :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: using timers to force an execution time
Nick Craig-Wood wrote: superpollo u...@example.net wrote: ... Or if you are on unix you can use signals... It is probably just about acceptable to raise an exception in a signal handler like this code does. ... neat! -- http://mail.python.org/mailman/listinfo/python-list
Re: missing 'xor' Boolean operator
Emile van Sebille wrote: On 7/16/2009 2:06 AM Jean-Michel Pichavant said... Ok then, why or does not return True, if the first element is considered True ? Why returning the element itself. Any reason for that ? Because it's confusing, maybe people used to that logic find it obvious, but I really don't. For example, I sometimes use it to set defaults: daysInAdvance = int(inputVar) or 25 Emile Sure this looks like an elegant way to set default values and I will use this form , but I'm not sure this justifies by itself the trickery. Python has extended the algebra definition of or and and top any type, but it is so unintuitive (I'm no LISP programmer). I think than using the short-circuiting mechanism of bool operators along with the python tricks is just error prone and may result in bug difficult to spot, unless you are very aware of all python boolean mechanisms. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing handlers between bound c++ libs
On Jul 14, 7:07 pm, Freyr freyr.magnus...@gmail.com wrote: I have a python bound physics library that uses handler to process events. The passing of handlers between c++ and python causes a huge overhead slowing down the process. Can I implement a handler in my custom python bound c++ lib B and pass it to blackbox python bound c++ lib A so that A would call B directly without passing through the python layer? Or to phrase the question differently: Can I pass a handler from B through python to A so that A will invoke B with out calling into python code? Depending on your exact configuration you may be able to wrap that C++ library using the SIMPL toolkit and get at your data with a message.There is some hello world demo code here: http://www.icanprogram.com/06py/main.html bob -- http://mail.python.org/mailman/listinfo/python-list
Re: using timers to force an execution time
Nick Craig-Wood wrote: ... import signal, os, time ... importing os is useless of course... -- http://mail.python.org/mailman/listinfo/python-list
Re: missing 'xor' Boolean operator
On 2009-07-16, Emile van Sebille em...@fenx.com wrote: On 7/16/2009 2:06 AM Jean-Michel Pichavant said... Ok then, why or does not return True, if the first element is considered True ? Why returning the element itself. Any reason for that ? Because it's confusing, maybe people used to that logic find it obvious, but I really don't. For example, I sometimes use it to set defaults: daysInAdvance = int(inputVar) or 25 I don't get it. That doesn't work right when inputVar == 0. -- Grant Edwards grante Yow! What I want to find at out is -- do parrots know visi.commuch about Astro-Turf? -- http://mail.python.org/mailman/listinfo/python-list
Re: How to search this newsgroup by a python script.
On 2009-07-16, Chris Rebert c...@rebertia.com wrote: On Thu, Jul 16, 2009 at 2:12 AM, Helmut Jarauschjarau...@igpm.rwth-aachen.de wrote: Hi, I haven't found anything with Google's group search, so let me ask it (again?). How can I search this newsgroup from within a Python script. (Perhaps by searching Google Groups or Gmane by some Python code.) 1. Generate URL of the form: http://search.gmane.org/?query=foogroup=gmane.comp.python.general where foo is the search terms, with proper URL escaping applied. 2. Fetch URL using urllib - http://docs.python.org/library/urllib.html 3. Parse resulting HTML page (e.g. using BeautifulSoup) 4. Extract desired information from search results using the parse tree. 5. ??? 6. Profit! The underpants gnomes would be proud. -- Grant Edwards grante Yow! I'm encased in the at lining of a pure pork visi.comsausage!! -- http://mail.python.org/mailman/listinfo/python-list
This is a mess...
I've been coding python for about a week now, and i'm trying to make an object oriented version of a program i just wrote. in this post is the original program. the next post will include the new programs and the traceback. i'm sure there are many underlying problems, but have been stuck on this for 2 days now... email me for input files since they are big and i don't see a way to upload a file here(~5 mB) this program works, and inputing the same file twice you should get a Q values of ~1 (.99...) ##CODE# #9July09 #Compute the covariance overlap of two results #Read in _U.asc files for both ensembles to find e-vectors #Read in _ .asc files for both ensembles to find sqrt e-values #strip out matrix info #compute corvariance import sys import math from math import sqrt if len(sys.argv) != 3: print print The corrent usage is 'python covariance.py file1 file2' print where the _U.asc and _s.asc will be appended when needed print exit(1) Input the first prefix1_U.asc file: this is the first eigen vector matrix prefix1 = sys.argv[1] + _U.asc fileholder = open(prefix1) text = fileholder.readlines() fields = text[1].split() num_rows = int(fields[1]) num_cols = int(fields[2]) U1_matrix = [] for line in text[2: num_rows+2]: fields = line.split() for i in range(len(fields)): fields[i] = float(fields[i]) U1_matrix.append(fields) Input the second prefix2_U.asc file: this is the 2nd eigen vector matrix prefix2 = sys.argv[2] + _U.asc fileholder = open(prefix2) text = fileholder.readlines() fields = text[1].split() num_rows = int(fields[1]) num_cols = int(fields[2]) #print look here nick:, fields U2_matrix = [] for line in text[2: num_rows+2]: fields = line.split() for i in range(len(fields)): fields[i] = float(fields[i]) U2_matrix.append(fields) Then Read in the first eigen values 1st 2 lines are header and need to be stripped away prefix3 = sys.argv[1] + _s.asc fileholder = open(prefix3) text = fileholder.readlines() fields = text[1].split() num_vals1 = int(fields[1]) #add check to see if correct # of values added print square if, len(U1_matrix), =, len(U2_matrix), =, len (U1_matrix[1]), =, len(U2_matrix[1]) #the list of sqrt e vals sqrt_s1 = [float(line) for line in text[2: num_vals1+2]] s1 = [float(line) * float(line) for line in text[2: num_vals1+2]] Finally, read in the 2nd set of eigen vals prefix4 = sys.argv[2] + _s.asc fileholder = open(prefix4) text = fileholder.readlines() fields = text[1].split() num_vals2 = int(fields[1]) #add check to see if correct # of values added #the list of sqrt e vals sqrt_s2 = [float(line) for line in text[2: num_vals1+2]] s2 = [float(line) * float(line) for line in text[2: num_vals1+2]] #= double summation (the 2nd term) doublesum = 0.0 for i in range(len(U1_matrix[1])): #print i = , i v1 = U1_matrix[i] sum = 0 for j in range(len(U2_matrix)): v2 = U2_matrix[j] dot = 0 for k in range(len(U1_matrix)): dot += v1[k] * v2[k] root = sqrt_s1[i] * sqrt_s2[j] sum += root * dot * dot doublesum += sum print double sum: , doublesum single summation (the 1st term and denominator) singsum = 0.0 for k in range(len(s1)): singsum += s1[k] + s2[k] print sing sum:, singsum Put it all together Q = 1 - sqrt(abs((singsum - (2.0*doublesum)) / singsum)) print your Q: print Q # end of code covariance.py -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Equivalent for dd fold
On Jul 15, 1:48 pm, Emile van Sebille em...@fenx.com wrote: On 7/15/2009 10:23 AM MRAB said... On Jul 15, 12:47 pm, Michiel Overtoom mot...@xs4all.nl wrote: seldan24 wrote: what can I use as the equivalent for the Unix 'fold' command? def fold(s,len): while s: print s[:len] s=s[len:] snip You might still need to tweak the above code as regards how line endings are handled. You might also want to tweak it if the strings are _really_ long to simply slice out the substrings as opposed to reassigning the balance to a newly created s on each iteration. Emile Thanks for all of the help. I'm almost there. I have it working now, but the 'fold' piece is very slow. When I use the 'fold' command in shell it is almost instantaneous. I was able to do the EBCDIC-ASCII conversion usng the decode method in the built-in str type. I didn't have to import the codecs module. I just decoded the data to cp037 which works fine. So now, I'm left with a large file, consisting of one extremely long line of ASCII data that needs to be sliced up into 35 character lines. I did the following, which works but takes a very long time: f = open(ascii_file, 'w') while ascii_data: f.write(ascii_data[:len]) ascii_data = ascii_data[len:] f.close() I know that Emile suggested that I can slice out the substrings rather than do the gradual trimming of the string variable as is being done by moving around the length. So, I'm going to give that a try... I'm a bit confused by what that means, am guessing that slice can break up a string based on characters; will research. Thanks for the help thus far. I'll post again when all is working fine. -- http://mail.python.org/mailman/listinfo/python-list
Re: ImportError: No module named _functools
In article 45228cf4-0b37-4c52-bf6f-d7bd124b0...@l32g2000vbp.googlegroups.com, Tony Lay tony...@gmail.com wrote: Traceback (most recent call last): File /usr/local/bin/meld, line 35, in module import gettext File /usr/local/lib/python2.6/gettext.py, line 49, in module import locale, copy, os, re, struct, sys File /usr/local/lib/python2.6/locale.py, line 15, in module import functools File /usr/local/lib/python2.6/functools.py, line 10, in module from _functools import partial, reduce ImportError: No module named _functools Where is _functools.so? -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ If you think it's expensive to hire a professional to do the job, wait until you hire an amateur. --Red Adair -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not enforce four space indentations in version 3.x?
I realize that a small portion of the community likes the tabs. They're sold on the tabs. They like the tabs. But tabs are an archaic holdover from an era when typewriters had physical tabstops on them. However, they are a single logical level of indentation -- I come down fairly solidly on the tabs side of the tabs vs. spaces argument. I can set my editor (vim in this case) to show tabs as as many spaces as I want. I usually have this set to 4, but sometimes 1 or 2. In Vim, using tabs I can just switch up my tab-stop setting (:set ts=2) and the presentation of my code reindents the way I expect. If I wanted to switch from 4-real-spaces to 2-real-spaces, I'd have to concoct a perlish regexp to handle the munging. The same separation of content and presentation that is all the rage with N-tier programmers and web developers, my content is logical levels of indentation indicated by a tab character in the source-code and my presentation is N spaces as presented by my editor. Yes, the dictatorial a tab always equals 8 spaces is a vestigial holdover for which I hold no love. I'll code on other people's projects with spaces if that's the project convention (as Vim lets me switch around fairly easily). But as for my own code, it's tabs all the way. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: This is a mess...
this is the new oop version, its pretty messy currently, and i do understand it is a simple routine, but i'm using it as an exercise to learn oop python... first the (current) traceback: [:~/python]$ python oop_covariance.py b2ar_all_test b2ar_all_test Eigen.Eigen_vect instance at 0x7fa26c404ab8 Eigen.Eigen_vect instance at 0x7fa26c404ab8 Traceback (most recent call last): File oop_covariance.py, line 24, in module cov = set1.covariance(set2, Eigen_vect.dot) File /home/nleioatts/python/Eigen.py, line 66, in covariance print self.vectors[i][i] AttributeError: Eigen_vect instance has no attribute '__getitem__' and a quick explaination: the file structures aare a 2d list of lists of numbers corresponding to eginvectors and a list of numbers corresponding to eigenvalues #33##Here is the main body #!/usr/bin/env python import sys import Eigen from Eigen import * if len(sys.argv) != 3: print print The corrent usage is 'python covariance.py file1 file2' print where the _U.asc and _s.asc will be appended when needed print exit(1) file1 = sys.argv[1] file2 = sys.argv[2] set1 = Eigen_set(file1+_U.asc, file1+_s.asc) set2 = Eigen_set(file2+_U.asc, file2+_s.asc) cov = set1.covariance(set2, Eigen_vect.dot) print cov ###and here are the classes: #!/usr/bin/env python import sys import math from math import sqrt class Eigen_vect: def __init__(self, e_val, e_vect): self.e_val = e_val self.e_vect = e_vect def length(self): return len(self.e_vect) def dot(self, other): d = 0.0 if other.length() != self.length(): raise ValueError, Eigen Vectors not same Length for k in range(self.length()): # print HI NICK, self.e_vect[k], other.e_vect[k] d += float(self.e_vect[k]) * float(other.e_vect[k]) return d class Eigen_set: def __init__(self, vec_filename, val_filename): self.vec_filename = vec_filename self.val_filename = val_filename # open two files # loop through them, skipping lines that begin with # # for each row, extract eigen vector and eigen values fileholder = open(self.vec_filename) text = fileholder.readlines() fields = text[2].split() #print len of fields, len(fields) self.vectors = [] for line in text[2: len(fields)]: fields = line.split() #print len of fields, len(fields) for i in range(len(fields)): fields[i] = float(fields[i]) e_vect = fields fileholder = open(self.val_filename) text = fileholder.readlines() e_val = [float(line) for line in text[2: self.length()]] self.vectors.append(Eigen_vect(e_val, e_vect)) #print this is self.vectors #print self.vectors(e_val) def length(self): return len(self.vectors) def covariance(self, other, dot): newdot = 0.0 # do a length check to make sure we're consistent if other.length() != self.length(): raise ValueError, Eigen Vectors not same Length #double loop over all my vectors and all of other's vectors doublesum = 0.0 for i in range(self.length()): sum = 0.0 v1 = self.vectors[i] for j in range(self.length()): newdot += v1.dot(self.vectors[j]) # root = self.e_val[i] * other.e_val[j] print self.vectors[i] print self.vectors[j] print self.vectors[i][i] #This is line 66, I'm trying to figure out how to call e_val from the Eigen_set class root = self.vectors[i][i] * other.vectors[i][j] sum += newdot * newdot * root doublesum += sum # singsum = 0.0 for k in range(self.length()): singsum += self.e_val[k] * self.e_val[k] + other.e_val[k] * other.e_val[k] Q = 1 - sqrt(abs((singsum - (2.0*doublesum)) / singsum)) print your Q: print Q and any additional help is great. thanks in advance, like the title says this is really a mess -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing python list from C to python
On Jul 16, 11:13 pm, hartley hartle...@gmail.com wrote: /* the first telling */ (...) /* the second telling */ (...) /* the third telling */ - If you had loosened up on the sarcasm That wasn't sarcasm, it was an attempt at humourous watering-down the expression of exasperation at continued ignoring of advice and wonder that I was continuing to bother ... HTH, It didn't. -- http://mail.python.org/mailman/listinfo/python-list
Re: Memory leak involving traceback objects
In article e6e9b9ea-1f8c-4695-90da-72e85c8a6...@v20g2000yqm.googlegroups.com, Rotem vmal...@gmail.com wrote: I'm debugging a nasty memory leak in a framework written in Python (v2.6.2). After much digging around I found that the entire object group that is leaking is held by a frame object which is subsequently held by a traceback object. Traversing the get_referrers() of each traceback frame leads eventually to a root traceback frame which has no referrers (gc.get_referrers returns an empty list). However, this traceback object seems not to be picked by the garbage collector, and is still there even after many iterations and calls to gc.collect(). The code location to which the traceback frame points doesn't do anything special - it just catches an exception, without saving the exception itself and/or traceback anywhere. What *does* it do? Does it re-raise? This sounds like you're still in block scope of an exception. -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ If you think it's expensive to hire a professional to do the job, wait until you hire an amateur. --Red Adair -- http://mail.python.org/mailman/listinfo/python-list
IFL 2009: Third Call for Papers
Call for Papers IFL 2009Seton Hall UniversitySOUTH ORANGE, NJ, USAhttp://tltc.shu.edu/blogs/projects/IFL2009/* NEW *Registration is now opened! Register at: http://tltc.shu.edu/blogs/projects/IFL2009/registration.htmlInvited Speaker: Benjamin C. Pierce University of Pennsylvania Talk Title: How To Build Your Own Bidirectional Programming LanguageRegistration Fee: Students: US$325.00 Non-students: US$375.00*The 21st International Symposium on Implementation and Application of Functional Languages, IFL 2009, will be held for the first time in the USA. The hosting institution is Seton Hall University in South Orange, NJ, USA and the symposium dates are September 23-25, 2009. It is our goal to make IFL a regular event held in the USA and in Europe. The goal of the IFL symposia is to bring together researchers actively engaged in the implementation and application of functional and function-based programming languages. IFL 2009 will be a venue for researchers to present and discuss new ideas and concepts, work in progress, and publication-ripe results related to the implementation and application of functional languages and function-based programming.Following the IFL tradition, IFL 2009 will use a post-symposium review process to produce a formal proceedings which will be published by Springer in the Lecture Notes in Computer Science series. All participants in IFL 2009 are invited to submit either a draft paper or an extended abstract describing work to be presented at the symposium. These submissions will be screened by the program committee chair to make sure they are within the scope of IFL and will appear in the draft proceedings distributed at the symposium. Submissions appearing in the draft proceedings are not peer-reviewed publications. After the symposium, authors will be given the opportunity to incorporate the feedback from discussions at the symposium and will be invited to submit a revised full arcticle for the formal review process. These revised submissions will be reviewed by the program committee using prevailing academic standards to select the best articles that will appear in the formal proceedings.TOPICSIFL welcomes submissions describing practical and theoretical work as well as submissions describing applications and tools. If you are not sure if your work is appropriate for IFL 2009, please contact the PC chair at ifl2...@shu.edu. Topics of interest include, but are not limited to:language concepts type checking contractscompilation techniques staged compilationruntime function specializationruntime code generation partial evaluation (abstract) interpretation generic programming techniques automatic program generation array processing concurrent/parallel programming concurrent/parallel program execution functional programming and embedded systems functional programming and web applications functional programming and security novel memory management techniques runtime profiling and performance measurements debugging and tracing virtual/abstract machine architectures validation and verification of functional programs tools and programming techniques FP in EducationPAPER SUBMISSIONSProspective authors are encouraged to submit papers or extended abstracts to be published in the draft proceedings and to present them at the symposium. All contributions must be written in English, conform to the Springer-Verlag LNCS series format and not exceed 16 pages. The draft proceedings will appear as a technical report of the Department of Mathematics and Computer Science of Seton Hall University.IMPORTANT DATESRegistration deadline August 15, 2009Presentation submission deadline August 15, 2009IFL 2009 Symposium September 23-25, 2009Submission for review process deadline November 1, 2009Notification Accept/Reject December 22, 2009Camera ready version February 1, 2010PROGRAM COMMITTEEPeter Achten University of Nijmegen, The NetherlandsJost Berthold Philipps-Universität Marburg, GermanyAndrew Butterfield University of Dublin, IrelandRobby Findler Northwestern University, USAKathleen Fisher ATT Research, USACormac Flanagan University of California at Santa Cruz, USAMatthew Flatt University of Utah, USAMatthew Fluet Rochester Institute of Technology, USADaniel Friedman Indiana University, USAAndy Gill University of Kansas, USAClemens Grelck University of Amsterdam/Hertfordshire, The Netherlands/UKJurriaan Hage Utrecht University, The NetherlandsRalf Hinze Oxford University, UKPaul Hudak Yale University, USAJohn Hughes Chalmers University of Technology, SwedenPatricia Johann University of Strathclyde, UKYukiyoshi Kameyama University of Tsukuba, JapanMarco T. Morazán (Chair) Seton Hall University, USARex Page University of Oklahoma, USAFernando Rubio Universidad Complutense de Madrid, SpainSven-Bodo Scholz University of Hertfordshire, UKManuel Serrano INRIA Sophia-Antipolis, FranceChung-chieh Shan Rutgers University, USADavid Walker Princeton University, USAViktória Zsók Eötvös Loránd
Re: Python Equivalent for dd fold
On Jul 16, 3:12 pm, seldan24 selda...@gmail.com wrote: On Jul 15, 1:48 pm, Emile van Sebille em...@fenx.com wrote: On 7/15/2009 10:23 AM MRAB said... On Jul 15, 12:47 pm, Michiel Overtoom mot...@xs4all.nl wrote: seldan24 wrote: what can I use as the equivalent for the Unix 'fold' command? def fold(s,len): while s: print s[:len] s=s[len:] snip You might still need to tweak the above code as regards how line endings are handled. You might also want to tweak it if the strings are _really_ long to simply slice out the substrings as opposed to reassigning the balance to a newly created s on each iteration. Emile Thanks for all of the help. I'm almost there. I have it working now, but the 'fold' piece is very slow. When I use the 'fold' command in shell it is almost instantaneous. I was able to do the EBCDIC-ASCII conversion usng the decode method in the built-in str type. I didn't have to import the codecs module. I just decoded the data to cp037 which works fine. So now, I'm left with a large file, consisting of one extremely long line of ASCII data that needs to be sliced up into 35 character lines. I did the following, which works but takes a very long time: f = open(ascii_file, 'w') while ascii_data: f.write(ascii_data[:len]) ascii_data = ascii_data[len:] f.close() I know that Emile suggested that I can slice out the substrings rather than do the gradual trimming of the string variable as is being done by moving around the length. So, I'm going to give that a try... I'm a bit confused by what that means, am guessing that slice can break up a string based on characters; will research. Thanks for the help thus far. I'll post again when all is working fine. Assuming your rather large text file is 1 meg long, you have 1 million characters in there. 100/35 = ~29k lines. The size remaining string decreases linearly, so the average size is (100 + 0) / 2 or 500k. All said and done, you're allocating and copying a 500K string -- not once, but 29 thousand times. That's where your slowdown resides. -- http://mail.python.org/mailman/listinfo/python-list
Re: list of all possible values
Certainly possible with list comprehensions. a = abc [(x, y) for x in a for y in a] [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')] But I like bearophile's version better. Andreas, Thanks, but I think you were missing my point. I should have explained better. The advantage that bearophile's version is generic with respect to the number of elements in each combination. To go from 2 element pairs (e.g. ('a', 'c')) to 5 element pairs (e.g. ('a', 'c', 'b', 'b', 'e')) requires only a change in a parameter passed to itertools. I don't see how you would do that with list comprehensions. You're example works nicely with 2 element pairs, but it seems to me like you'd need to recode it if you wanted to change it to 5 element pairs. Am I wrong about that? Can you think of a way to write a function that, using list comprehensions, takes a list of values and the size of each combination, and returns the len(list)**(combination size) possible combinations using those values? Thanks again, David -- http://mail.python.org/mailman/listinfo/python-list
Re: missing 'xor' Boolean operator
On 7/16/2009 7:04 AM Unknown said... On 2009-07-16, Emile van Sebille em...@fenx.com wrote: daysInAdvance = int(inputVar) or 25 I don't get it. That doesn't work right when inputVar == 0. Aah, but you didn't get to define right. :) For that particular example 0 is not a valid response. Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Equivalent for dd fold
On Jul 15, 1:14 pm, seldan24 selda...@gmail.com wrote: On Jul 15, 12:47 pm, Michiel Overtoom mot...@xs4all.nl wrote: seldan24 wrote: what can I use as the equivalent for the Unix 'fold' command? def fold(s,len): while s: print s[:len] s=s[len:] s=A very long string indeed. Really that long? Indeed. fold(s,10) Output: A very lon g string i ndeed. Rea lly that l ong? Indee d. Greetings, -- The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing. - Vinod Valloppillilhttp://www.catb.org/~esr/halloween/halloween4.html Wow, I feel like a dork. I should have done more research prior to posting. Anyway, thanks for the advice. The trouble with Python is that things make 'too much' sense. Loving this language. You might also find the textwrap module useful: http://docs.python.org/library/textwrap.html -- http://mail.python.org/mailman/listinfo/python-list
RE: list of all possible values
Certainly possible with list comprehensions. a = abc [(x, y) for x in a for y in a] [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')] But I like bearophile's version better. Andreas, Thanks, but I think you were missing my point. I should have explained better. The advantage that bearophile's version is generic with respect to the number of elements in each combination. To go from 2 element pairs (e.g. ('a', 'c')) to 5 element pairs (e.g. ('a', 'c', 'b', 'b', 'e')) requires only a change in a parameter passed to itertools. I don't see how you would do that with list comprehensions. You're example works nicely with 2 element pairs, but it seems to me like you'd need to recode it if you wanted to change it to 5 element pairs. Am I wrong about that? Can you think of a way to write a function that, using list comprehensions, takes a list of values and the size of each combination, and returns the len(list)**(combination size) possible combinations using those values? Thanks again, David David, I think my post got caught in the nebulous email eddys and seems to have taken 16 hours to arrive on the list. It was meant to be a reply to your first post, not your second. Having said that, I think I missed the point of that post too ;o) Maybe someone smarter than me can come up with a way to dynamically nest the fors in a list comprehension, but I certainly can't do it. Sorry for the confusion. Cheers, Drea -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Equivalent for dd fold
seldan24 wrote: On Jul 15, 1:48 pm, Emile van Sebille em...@fenx.com wrote: On 7/15/2009 10:23 AM MRAB said... On Jul 15, 12:47 pm, Michiel Overtoom mot...@xs4all.nl wrote: seldan24 wrote: what can I use as the equivalent for the Unix 'fold' command? def fold(s,len): while s: print s[:len] s=s[len:] snip You might still need to tweak the above code as regards how line endings are handled. You might also want to tweak it if the strings are _really_ long to simply slice out the substrings as opposed to reassigning the balance to a newly created s on each iteration. Emile Thanks for all of the help. I'm almost there. I have it working now, but the 'fold' piece is very slow. When I use the 'fold' command in shell it is almost instantaneous. I was able to do the EBCDIC-ASCII conversion usng the decode method in the built-in str type. I didn't have to import the codecs module. I just decoded the data to cp037 which works fine. So now, I'm left with a large file, consisting of one extremely long line of ASCII data that needs to be sliced up into 35 character lines. I did the following, which works but takes a very long time: f = open(ascii_file, 'w') while ascii_data: f.write(ascii_data[:len]) ascii_data = ascii_data[len:] f.close() The 'write' method doesn't append any line ending, so that code gives the same output as f.write(ascii_data). I know that Emile suggested that I can slice out the substrings rather than do the gradual trimming of the string variable as is being done by moving around the length. So, I'm going to give that a try... I'm a bit confused by what that means, am guessing that slice can break up a string based on characters; will research. Thanks for the help thus far. I'll post again when all is working fine. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Equivalent for dd fold
Michiel Overtoom wrote: seldan24 wrote: I know that Emile suggested that I can slice out the substrings rather than do the gradual trimming of the string variable as is being done by moving around the length. An excellent idea. def fold(s,chunklength): offset=0 while offsetlen(s): print s[offset:offset+chunklength] offset+=chunklength More Pythonic: for offset in range(0, len(s), chunklength): print s[offset : offset + chunklength] s=A very long string indeed. Really that long? Indeed. fold(s,10) -- http://mail.python.org/mailman/listinfo/python-list
Re: Persistent variable in subprocess using multiprocessing?
mheavner miheav...@gmail.com (m) wrote: m 'The process' refers to the subprocess. I could do as you say, load m the data structure each time, but the problem is that takes a m considerable amount of time compared to the the actual computation m with the data it contains. I'm using these processes within a loop as m follows: m # Don't recreate processes or Queues m pop1 = Queue() m pop2 = Queue() m pop_out = Queue() m p1 = CudaProcess(0, args=(costf,pop1,pop_out)) m p2 = CudaProcess(1, args=(costf,pop2,pop_out)) m # Main loop m for i in range(maxiter): m print 'ITERATION: '+str(i) m if log != None: m l = open(log,'a') m l.write('Iteration: '+str(i)+'\n') m l.close() m # Split population in two m pop1.putmany(pop[0:len(pop)/2]) m pop2.putmany(pop[len(pop)/2:len(pop)]) m # Start two processes m if not p1.isAlive(): m p1.start() m print 'started %s'%str(p1.getPid()) m else: m p1.run() That won't work. p1.run() will execute the run method in the Master process, not in the subprocess. And if it would your could would have a race condition: between the p1.isAlive() (which must be is_alive btw), and the p1.run() the process can have stopped. The proper way to do is to put the work in a Queue and let the processes get work out of the Queue. The datastructure will remain in the process then. m if not p2.isAlive(): m p2.start() m print 'started %s'%str(p2.getPid()) m else: m p2.run() m . m . m . m So I'd like to load that data into memory once and keep there as long m as the process is alive (ideally when the subprocess is created, m storing some sort of pointer to it), rather than loading it each time m run is called for a process within the loop. Could be my CudaProcess m class - I'll check out what Diez suggested and post back. -- Piet van Oostrum p...@cs.uu.nl URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Persistent variable in subprocess using multiprocessing?
I realize that the Queue would be the best way of doing this, however that involves transferring the huge amount of data for each call - my hope was to transfer it once and have it remain in memory for the subprocess across run() calls. On Jul 16, 1:18 pm, Piet van Oostrum p...@cs.uu.nl wrote: mheavner miheav...@gmail.com (m) wrote: m 'The process' refers to the subprocess. I could do as you say, load m the data structure each time, but the problem is that takes a m considerable amount of time compared to the the actual computation m with the data it contains. I'm using these processes within a loop as m follows: m # Don't recreate processes or Queues m pop1 = Queue() m pop2 = Queue() m pop_out = Queue() m p1 = CudaProcess(0, args=(costf,pop1,pop_out)) m p2 = CudaProcess(1, args=(costf,pop2,pop_out)) m # Main loop m for i in range(maxiter): m print 'ITERATION: '+str(i) m if log != None: m l = open(log,'a') m l.write('Iteration: '+str(i)+'\n') m l.close() m # Split population in two m pop1.putmany(pop[0:len(pop)/2]) m pop2.putmany(pop[len(pop)/2:len(pop)]) m # Start two processes m if not p1.isAlive(): m p1.start() m print 'started %s'%str(p1.getPid()) m else: m p1.run() That won't work. p1.run() will execute the run method in the Master process, not in the subprocess. And if it would your could would have a race condition: between the p1.isAlive() (which must be is_alive btw), and the p1.run() the process can have stopped. The proper way to do is to put the work in a Queue and let the processes get work out of the Queue. The datastructure will remain in the process then. m if not p2.isAlive(): m p2.start() m print 'started %s'%str(p2.getPid()) m else: m p2.run() m . m . m . m So I'd like to load that data into memory once and keep there as long m as the process is alive (ideally when the subprocess is created, m storing some sort of pointer to it), rather than loading it each time m run is called for a process within the loop. Could be my CudaProcess m class - I'll check out what Diez suggested and post back. -- Piet van Oostrum p...@cs.uu.nl URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not enforce four space indentations in version 3.x?
On Jul 16, 10:18 am, Tim Chase python.l...@tim.thechases.com wrote: I realize that a small portion of the community likes the tabs. They're sold on the tabs. They like the tabs. But tabs are an archaic holdover from an era when typewriters had physical tabstops on them. However, they are a single logical level of indentation -- I come down fairly solidly on the tabs side of the tabs vs. spaces argument. My bet is that the problem is this: some people like to format their code in ways that don't work well when you're using tabs. For example, they might want to call a function like this (note spaces): some_func(foo=1, bar=2, baz=3) instead of: some_func( foo=1, bar=2, baz=3) The first one requires 10 spaces in front of bar and baz. If you're using tabs, that means one or two tabs plus some space characters. So, people who do that would probably never use tabs. The 2nd example is fine for tabs or spaces. I'm sure there are a bunch of similar examples for things besides function calls. Don't you ever find cases where you'd like to add in an extra space or two to make things line up nicely? I can set my editor (vim in this case) to show tabs as as many spaces as I want. I usually have this set to 4, but sometimes 1 or 2. Just curious: why would you want to do that? In my experience, once my eyes got used to 4-space indents, everything else looks either too little or too much. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: missing 'xor' Boolean operator
Emile van Sebille wrote: On 7/16/2009 7:04 AM Unknown said... On 2009-07-16, Emile van Sebille em...@fenx.com wrote: daysInAdvance = int(inputVar) or 25 I don't get it. That doesn't work right when inputVar == 0. Aah, but you didn't get to define right. :) For that particular example 0 is not a valid response. Emile When I was talking about such error prone form of boolean operations, I didn't expect to be right so quickly :p Steven explained the truth notion with the Something/Nothing. 0 is Something, 0 would be Nothing. I'm not sure it makes sens anyway. I mean, I could easily argue that the number 0 is something. In the end I wonder if I shouldn't just acknowledge the python mechanism without trying to find any intuitive/natural/obvious logic in it, knowing that sometimes the Truth lies far away from the Evidence. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: Ann: Google releases Python-based open-source NX server
On Jul 16, 3:51 pm, J Kenneth King ja...@agentultra.com wrote: It's pretty cool, but not PEP8! Probably because they just bought the source off of another smaller proprietary project. Makes me sad seeing Google, proud supporter of all things Python, release non-PEP8 code. Personally, I don't follow PEP8 either. Note: PEP-8 gives 'coding conventions for the Python code **comprising the standard library in the main Python distribution**' (my emphasis). My coding conventions are similar to, but not exactly the same as, PEP-8. It would be ridiculous IMO (and PEP-8 acknowledges this) for such a permissive language as Python to put a 'coding style' straitjacket around itself. YMMV, of course. J^n -- http://mail.python.org/mailman/listinfo/python-list
Re: Ann: Google releases Python-based open-source NX server
On 7/16/2009 10:59 AM jkn said... Personally, I don't follow PEP8 either. Note: PEP-8 gives 'coding conventions for the Python code **comprising the standard library in the main Python distribution**' (my emphasis). My coding conventions are similar to, but not exactly the same as, PEP-8. Mine too, and my objection to PEP-8 is that the coding style doesn't allow for copy-n-paste into the interpreter, and I like to be able to test that way. Perhaps if I configured my editor not to strip trailing whitespace from lines it would work, but then I don't like trailing whitespace. Of course, I _like_ leading whitespace. :) Emile -- http://mail.python.org/mailman/listinfo/python-list
Re: Ann: Google releases Python-based open-source NX server
On 2009-07-16 09:51, J Kenneth King wrote: jknjkn...@nicorp.f9.co.uk writes: Google quietly releases open-source NX server ...written in Python, apparently http://www.computerworld.com/s/article/9135504/ Google_quietly_releases_open_source_NX_server?taxonomyId=88 Neatx can be downloaded from Google's code repository: http://code.google.com/p/neatx/ Regards J^n It's pretty cool, but not PEP8! Probably because they just bought the source off of another smaller proprietary project. No, it' just that Google does not use PEP8 for its internal style standard. -- Robert Kern I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth. -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not enforce four space indentations in version 3.x?
However, they are a single logical level of indentation -- I come down fairly solidly on the tabs side of the tabs vs. spaces argument. My bet is that the problem is this: some people like to format their code in ways that don't work well when you're using tabs. For example, they might want to call a function like this (note spaces): some_func(foo=1, bar=2, baz=3) instead of: some_func( foo=1, bar=2, baz=3) For continued indenting statements such as this, I tend to use the coding convention used at my first job out of college (Computer Sciences Corp...for better or worse) which just indents two levels: def some_func(foo=1, tabtabbar=2, tabtabbaz=3): tabdo_something(foo) tabdo_other_stuff(bar) examples for things besides function calls. Don't you ever find cases where you'd like to add in an extra space or two to make things line up nicely? I have occasionally (okay, very rarely) use the mixed tab+space method of indentation for continued lines if I want them lined up nicely: tabtabif (foo == bar and tabtabbaz frob and tabtabfred != barney): tabtabtabdo_something() tabtabtabdo_more() This scheme insures that the visual alignment for the continued-line matches up, even if the tab-stop is changed. The positioning of the indented block (the do_* bit) floats inconveniently with relation to the continued text, with pessimal cases being indistinguishable from the continued lines (which is why I generally opt not to use this unless it has great benefits in code clarity). By regularly indenting continued lines for containing blocks (if, while, etc) by two tabs, the continuation stands out from the contained code regardless of my tab stops. I can set my editor (vim in this case) to show tabs as as many spaces as I want. I usually have this set to 4, but sometimes 1 or 2. Just curious: why would you want to do that? In my experience, once my eyes got used to 4-space indents, everything else looks either too little or too much. :) It totally depends on the project -- I like the condensed nature of 2sp/tab for code sharing on mailing lists (and tend to copy out of vim with tabs expanded to 2 spaces for pasting into emails) and for my own visual preference. If it's code that I'd expect anybody else to view, I tend to use 4sp/tab to keep my lines below 80 chars per line with the tabs taken into consideration. I guess I change up my indent enough that sometimes 2 seems just right or too small, and sometimes 4 seems just right or too large. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Why not enforce four space indentations in version 3.x?
On Jul 16, 6:32 am, Inky 788 inky...@gmail.com wrote: On Jul 10, 7:35 pm, Ben Finney ben+pyt...@benfinney.id.au wrote: walterbyrd walterb...@iname.com writes: I believe Guido himself has said that all indentions should be four spaces - no tabs. Yes. That's a “should” and not a “must”, even though PEP 8 says it with a simple imperative:: Use 4 spaces per indentation level. That actually sounds pretty weird. Don't do {foo}. Really, I mean *really* don't do {foo}. Oh, also, the interpreter allows you to do {foo}. But don't do it! I mean it!. Very ... perlish, if you ask me. Not Perlish at all. (Perl would never want you not to use something.) Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Why aren't OrderedDicts comparable with etc?
Mark wrote: On 16 July, 10:21, Piet van Oostrum p...@cs.uu.nl wrote: But why should the order be as if the OrderedDict was a list of tuples. A dict can be considered as a mapping and then you might want to treat either the key or the value as contravariant (the key I guess). So there is ambiguity. Why would the view as a list of tuples for the ordering be the `natural' view? Maybe you may expect some kind of monotonicity such that d1d2 implies d1[x]d2[x], but that doesn't work for d1 = {1:10, 2:20} and d2 = {1:15, 2:5}. So maybe there is only a partial ordering? OK, that seems to me to be a convincing argument against supporting ordering. To put the above in a slightly different way. OrderedDicts are a recently added niche class that Raymond added to what is mostly his collections module because there are enough few use cases. There was pydev discussion which included the idea, I believe, that they should fundamentally be dicts, not lists. Regardless, the justifying use cases did not include a need to compare OrderedDicts. The small fraction of the few use cases for OrderedDicts that do require comparision can be met by extracting the needed sequences and comparing *them* in the appropriate manner. The 'appropriate manner' is not likely to always be the same. This point may have come up in the discussion, but I would let you check for sure if curious. 'Consistency' is a Python design principle, but it is balanced with others, so that it is not sufficient reason to add nearly useless features. There is a cost to every addition. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeEncodeError: 'ascii' codec can't encode character u'\xb7' in position 13: ordinal not in range(128)
Hi, Thanks all for the replies. I am working on a cluster of 15 nodes and I have now installed python 3.1 on all of them. I tried installing python2.6 but there was some make error. So, I do not want to give more time in installing 2.4 and rather use 3.1 but for that I need to convert my 2.4 code to 3.1. I used 2to3 tool, and it did make many changes in the 2.4 code, but still there are some indentation errors that I am unable to resolve being new to python. I have attached my python code, can anyone please fix the indentation error in the code. I am using vi editor. --Thanks a lot, Akhil http://www.nabble.com/file/p24522412/temp.py temp.py alex23 wrote: On Jul 16, 9:00 pm, akhil1988 akhilan...@gmail.com wrote: I have switched to python 3.1 , but now I am getting some syntax errors in the code: Python 3.x was a major release that endeavoured to clean up a number of lingering issues with the language, the upshot being that it isn't entirely backwards compatible with past versions. Unicode became the default string type, which is what is causing the error here: the u- prefix is no longer required (or even allowed). However, Py3.x _does_ come with a handy tool for automatically converting Python 2.x code to 3.x, called 2to3. One of the things it should do is convert Py2.x unicode values into their correct representation in 3.x. With any luck, it should be able to convert the code you're using entirely. Let us know how it goes. -- http://mail.python.org/mailman/listinfo/python-list -- View this message in context: http://www.nabble.com/UnicodeEncodeError%3A-%27ascii%27-codec-can%27t-encode-character-u%27%5Cxb7%27-in-position-13%3A-ordinal-not-in-range%28128%29-tp24509879p24522412.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
URLError errno and strerror not set
python 2.5.2 errno, strerror and message do not appear to be set in the following two cases (at least). Is this to be expected? (as an aside, arg[0] is set) # case 1 print exception, exception.errno, exception.strerror, exception.message == '' urlopen error (111, 'Connection refused') None None True # case 2 print exception, exception.errno, exception.strerror, exception.message == '' urlopen error timed out None None True Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Persistent variable in subprocess using multiprocessing?
mheavner miheav...@gmail.com (m) wrote: m I realize that the Queue would be the best way of doing this, however m that involves transferring the huge amount of data for each call - my m hope was to transfer it once and have it remain in memory for the m subprocess across run() calls. Which huge amount of data? The datastructure you talked about can remain in the process. You only have to transfer the input for your calculation in the queue but you have to do that anyway. And there is only one run call per process. When run has terminated the process exits, so you would have a loop in the run(0 method getting work from the queue. -- Piet van Oostrum p...@cs.uu.nl URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing python list from C to python
In article 0afc5c4d-1af5-4d0e-9442-26b51b12e...@m11g2000yqh.googlegroups.com, hartley hartle...@gmail.com wrote: If you had loosened up on the sarcasm I would probably have read what you wrote more thoroughly instead of just skimming through it. Thanks for the help, but you should seriously consider doing something with your patronizing attitude. http://www.mikeash.com/getting_answers.html http://www.catb.org/~esr/faqs/smart-questions.html -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ If you think it's expensive to hire a professional to do the job, wait until you hire an amateur. --Red Adair -- http://mail.python.org/mailman/listinfo/python-list
Re: Ann: Google releases Python-based open-source NX server
Robert Kern robert.k...@gmail.com writes: On 2009-07-16 09:51, J Kenneth King wrote: jknjkn...@nicorp.f9.co.uk writes: Google quietly releases open-source NX server ...written in Python, apparently http://www.computerworld.com/s/article/9135504/ Google_quietly_releases_open_source_NX_server?taxonomyId=88 Neatx can be downloaded from Google's code repository: http://code.google.com/p/neatx/ Regards J^n It's pretty cool, but not PEP8! Probably because they just bought the source off of another smaller proprietary project. No, it' just that Google does not use PEP8 for its internal style standard. Yeah probably. I'm just a little OCD sometimes. -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeEncodeError: 'ascii' codec can't encode character u'\xb7' in position 13: ordinal not in range(128)
ok! I got the indentation errors fixed. Bu I get another error: Traceback (most recent call last): File ./temp.py, line 484, in module main() File ./temp.py, line 476, in main line.decode('utf-8').strip() AttributeError: 'str' object has no attribute 'decode' I am using Python3.1 Thanks Akhil akhil1988 wrote: Hi, Thanks all for the replies. I am working on a cluster of 15 nodes and I have now installed python 3.1 on all of them. I tried installing python2.6 but there was some make error. So, I do not want to give more time in installing 2.4 and rather use 3.1 but for that I need to convert my 2.4 code to 3.1. I used 2to3 tool, and it did make many changes in the 2.4 code, but still there are some indentation errors that I am unable to resolve being new to python. I have attached my python code, can anyone please fix the indentation error in the code. I am using vi editor. --Thanks a lot, Akhil http://www.nabble.com/file/p24522412/temp.py temp.py alex23 wrote: On Jul 16, 9:00 pm, akhil1988 akhilan...@gmail.com wrote: I have switched to python 3.1 , but now I am getting some syntax errors in the code: Python 3.x was a major release that endeavoured to clean up a number of lingering issues with the language, the upshot being that it isn't entirely backwards compatible with past versions. Unicode became the default string type, which is what is causing the error here: the u- prefix is no longer required (or even allowed). However, Py3.x _does_ come with a handy tool for automatically converting Python 2.x code to 3.x, called 2to3. One of the things it should do is convert Py2.x unicode values into their correct representation in 3.x. With any luck, it should be able to convert the code you're using entirely. Let us know how it goes. -- http://mail.python.org/mailman/listinfo/python-list -- View this message in context: http://www.nabble.com/UnicodeEncodeError%3A-%27ascii%27-codec-can%27t-encode-character-u%27%5Cxb7%27-in-position-13%3A-ordinal-not-in-range%28128%29-tp24509879p24523113.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: ImportError: No module named _functools
On Jul 16, 10:14 am, a...@pythoncraft.com (Aahz) wrote: In article 45228cf4-0b37-4c52-bf6f-d7bd124b0...@l32g2000vbp.googlegroups.com, Tony Lay tony...@gmail.com wrote: Traceback (most recent call last): File /usr/local/bin/meld, line 35, in module import gettext File /usr/local/lib/python2.6/gettext.py, line 49, in module import locale, copy, os, re, struct, sys File /usr/local/lib/python2.6/locale.py, line 15, in module import functools File /usr/local/lib/python2.6/functools.py, line 10, in module from _functools import partial, reduce ImportError: No module named _functools Where is _functools.so? -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ If you think it's expensive to hire a professional to do the job, wait until you hire an amateur. --Red Adair /usr/local/lib/python2.6/lib-dynload/ It's in the path... export PYTHONHOME=/usr/local/lib/python2.6 export PYTHONPATH=/usr/local/lib/python2.6:/usr/local/lib/python2.6/ site-packages:/usr/local/lib/python2.6/lib-dynload:/usr/local/etc/ pango -- http://mail.python.org/mailman/listinfo/python-list
Re: missing 'xor' Boolean operator
Quoting Jean-Michel Pichavant jeanmic...@sequans.com: Emile van Sebille wrote: On 7/16/2009 7:04 AM Unknown said... On 2009-07-16, Emile van Sebille em...@fenx.com wrote: daysInAdvance = int(inputVar) or 25 I don't get it. That doesn't work right when inputVar == 0. Aah, but you didn't get to define right. :) For that particular example 0 is not a valid response. When I was talking about such error prone form of boolean operations, I didn't expect to be right so quickly :p What do you mean by being right so quickly, and error prone in this context? I would also ask Unknown why he believes that int(intputVar) or 25 doesn't work right when inputVar == 0. The only false value that int() may return is zero, so the or 25 clause is there only for that case. I can't see then how you think that is an error. I'm not sure it makes sens anyway. I mean, I could easily argue that the number 0 is something. In the end I wonder if I shouldn't just acknowledge the python mechanism Then look it another way. The Empty/Nothing is just standard practice, there is nothing in python that forces you to be false if you are empty, or true otherwise. Instead, answer this: why do you need a /boolean/ value? Is there any case where you need to be certain that the object's type is 'bool'? If you think the answer is yes, you may want to get more familiar with the duck typing concept. (That doesn't mean that there are no legitimate cases where duck typing is inappropriate, but that there are many cases where people, specially if they come from statically typed languages, may believe that it is inappropriate when it isn't). In the python world, one should care more about how an object /behaves/ than from what clase it came. If something quacks like a duck, then assume that it is a duck, at least for the quacking part. Most python objects carry a truth value. Sometimes it feels natural (None is false, boolean True and False are true and false, empty containers are expected to be false, 0 and '' are false). Sometimes, it is everything but natural, but that's a problem with the object's implementation (datetime.time comes to mind). So, you shouldn't care if you have a bool instance - it should be enough that it behaves like a bool (though, if you need a bool, you can always construct one). The True or False expression could return Giraffes, as long as Giraffes behave like the bool True in boolean context. If you care about the class of the result, you can ask for its truth value, and if you don't care about it, you can just ignore it, and use it as you would use a bool. And then, if you can return any object as long as it behaves properly, what would be better to return? A new bool? Why not new Giraffe, if they will have the same behaviour? Guido chose to return the a value that will say more about the result of the operation than just a boolean. It acts as a boolean - if you don't need anything else, treat it as such -, but it will be, whenever is possible, one of the objects in the sequence, in case you need more info. without trying to find any intuitive/natural/obvious logic in it, knowing that sometimes the Truth lies far away from the Evidence. Don't do that. Many of python's decisions are very well thought. You may disagree with them, as I do with some, but they are rarely taken lightly. And this is one that I find very agreeable and in line with the rest of python's philosophy. -- Luis Zarrabeitia Facultad de Matemática y Computación, UH http://profesores.matcom.uh.cu/~kyrie -- Participe en Universidad 2010, del 8 al 12 de febrero de 2010 La Habana, Cuba http://www.universidad2010.cu -- http://mail.python.org/mailman/listinfo/python-list
Re: ImportError: No module named _functools
On Jul 16, 10:14 am, a...@pythoncraft.com (Aahz) wrote: In article 45228cf4-0b37-4c52-bf6f-d7bd124b0...@l32g2000vbp.googlegroups.com, Tony Lay tony...@gmail.com wrote: Traceback (most recent call last): File /usr/local/bin/meld, line 35, in module import gettext File /usr/local/lib/python2.6/gettext.py, line 49, in module import locale, copy, os, re, struct, sys File /usr/local/lib/python2.6/locale.py, line 15, in module import functools File /usr/local/lib/python2.6/functools.py, line 10, in module from _functools import partial, reduce ImportError: No module named _functools Where is _functools.so? -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ If you think it's expensive to hire a professional to do the job, wait until you hire an amateur. --Red Adair /usr/local/lib/python2.6/lib-dynload/ It's in the path... export PYTHONHOME=/usr/local/lib/python2.6 export PYTHONPATH=/usr/local/lib/python2.6:/usr/local/lib/python2.6/ site-packages:/usr/local/lib/python2.6/lib-dynload:/usr/local/etc/ pango -- http://mail.python.org/mailman/listinfo/python-list
Re: This is a mess...
Nick nleio...@gmail.com (N) wrote: N this is the new oop version, its pretty messy currently, and i do N understand it is a simple routine, but i'm using it as an exercise to N learn oop python... N first the (current) traceback: N [:~/python]$ python oop_covariance.py b2ar_all_test b2ar_all_test N Eigen.Eigen_vect instance at 0x7fa26c404ab8 N Eigen.Eigen_vect instance at 0x7fa26c404ab8 N Traceback (most recent call last): N File oop_covariance.py, line 24, in module N cov = set1.covariance(set2, Eigen_vect.dot) N File /home/nleioatts/python/Eigen.py, line 66, in covariance N print self.vectors[i][i] N AttributeError: Eigen_vect instance has no attribute '__getitem__' self.vectors is a list of Eigen_vect objects. So self.vectors[i] is an Eigen_vect object. Now you do a subscript on this Eigen_vect object but you have not defined what that means. Presumably you want it to do the subscript on the self.e_vect in the Eigen_vect instance. Therefore you have to define the __getitem__ method in the Eigen_vect class. class Eigen_vect: def __init__(self, e_val, e_vect): self.e_val = e_val self.e_vect = e_vect def length(self): return len(self.e_vect) def __getitem__(self, indx): return self.e_vect[indx] I hope I did not make a mistake, I didn't check it because I don't want to make test input files. -- Piet van Oostrum p...@cs.uu.nl URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: p...@vanoostrum.org -- http://mail.python.org/mailman/listinfo/python-list
Re: list of all possible values
On Jul 16, 11:49 am, Andreas Tawn andreas.t...@ubisoft.com wrote: Certainly possible with list comprehensions. a = abc [(x, y) for x in a for y in a] [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')] But I like bearophile's version better. Andreas, Thanks, but I think you were missing my point. I should have explained better. The advantage that bearophile's version is generic with respect to the number of elements in each combination. To go from 2 element pairs (e.g. ('a', 'c')) to 5 element pairs (e.g. ('a', 'c', 'b', 'b', 'e')) requires only a change in a parameter passed to itertools. I don't see how you would do that with list comprehensions. You're example works nicely with 2 element pairs, but it seems to me like you'd need to recode it if you wanted to change it to 5 element pairs. Am I wrong about that? Can you think of a way to write a function that, using list comprehensions, takes a list of values and the size of each combination, and returns the len(list)**(combination size) possible combinations using those values? Thanks again, David David, I think my post got caught in the nebulous email eddys and seems to have taken 16 hours to arrive on the list. It was meant to be a reply to your first post, not your second. Having said that, I think I missed the point of that post too ;o) Maybe someone smarter than me can come up with a way to dynamically nest the fors in a list comprehension, but I certainly can't do it. Well, I don't use list comprehension, but you can certainly make dynamic for loops. Not that this is a replacement for itertools (I wrote it before itertools had the ability to do all this). def ooloop6(a, n, perm=True, repl=True): if (not repl) and (nlen(a)): return r0 = range(n) r1 = r0[1:] if perm and repl: # ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) e = ''.join([p = [''.join((,v,)) ,f,]]) exec e return p if (not perm) and repl:# ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) i = ' and '.join(['(c%s=c%s)' % (j,j-1) for j in r1]) e = ''.join([p = [''.join((,v,)) ,f, if ,i,]]) exec e return p if perm and (not repl):# ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) i = ' and '.join([' and '.join(['(c%s!=c%s)' % (j,k) for k in range(j)]) for j in r1]) e = ''.join([p = [''.join((,v,)) ,f, if ,i,]]) exec e return p if (not perm) and (not repl): # ok v = ','.join(['c%s' % i for i in r0]) f = ' '.join(['for c%s in a' % i for i in r0]) i = ' and '.join(['(c%sc%s)' % (j,j-1) for j in r1]) e = ''.join([p = [''.join((,v,)) ,f, if ,i,]]) exec e return p print '0123456789 taken 2 at a time' p = ooloop6('0123456789',2,True,True) print print 'Permutations withReplacement: %6d' % (len(p)) print p p = ooloop6('0123456789',2,True,False) print print 'Permutations without Replacement: %6d' % (len(p)) print p p = ooloop6('0123456789',2,False,True) print print 'Combinations withReplacement: %6d' % (len(p)) print p p = ooloop6('0123456789',2,False,False) print print 'Combinations without Replacement: %6d' % (len(p)) print p print print '0123456789 taken 3 at a time' p = ooloop6('0123456789',3,True,True) print print 'Permutations withReplacement: %6d' % (len(p)) print p p = ooloop6('0123456789',3,True,False) print print 'Permutations without Replacement: %6d' % (len(p)) print p p = ooloop6('0123456789',3,False,True) print print 'Combinations withReplacement: %6d' % (len(p)) print p p = ooloop6('0123456789',3,False,False) print print 'Combinations without Replacement: %6d' % (len(p)) print p 0123456789 taken 2 at a time Permutations withReplacement:100 ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99'] Permutations without Replacement: 90 ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '45', '46',
Re: missing 'xor' Boolean operator
On Thu, 16 Jul 2009 11:06:54 +0200, Jean-Michel Pichavant wrote: So if I resume: - not 'foo' = False - 'foo' or 'foo' = 'foo' I may be missing something, but honestly, Guido must have smoked some heavy stuff to write such logic, has he ? Several languages (e.g. Lisp, Bourne shell) behave the same way, i.e. or returns the first element which is considered true while and returns the last element provided that all preceding elements are considered true. [snip] Ok then, why or does not return True, if the first element is considered True ? If the first element is true, returning the first element is returning true. Why returning the element itself. Any reason for that ? Why not? Where is the benefit in collapsing all true values to True? You can convert values to True/False with bool(), but the conversion cannot be reversed. It only makes a difference if you are interested in the representation rather than the value. Do you normally test for equality with is or ==? -- http://mail.python.org/mailman/listinfo/python-list