[ANN] Game Microwar 2.0 beta 2
MicroWar 2.0 beta 2 --- MicroWar is Space Invaders style arcade game, in the cruel world of micro-compter industry. You're a Macintosh faced to invading Wintel hordes year after year, kill more PC. Bonuses let you improve your Mac performances or restore life... PC Hunt is now open ! Usages and Licence The game is powered by Python language with SDL and PyGame module. Distributed under BSD Licence : http://opensource.org/licenses/bsd-license.php Compatibility The bundled application is only available for Mac now. The source code, is therefore cross-platform and can run on Macintosh, Windows and Linux : see source documentation for details I was looking for someone to help me released a package for WIndows, i can't make py2exe working... Download the game : http://microwar.sourceforge.net/ Bug report : http://sourceforge.net/projects/microwar/support FAQ : http://microwar.sourceforge.net/faq.html All logos used are tradmarks from the corresponding compagny. Use is illustrative. -- Pierre-Alain Dorangehttp://microwar.sourceforge.net/ Ce message est sous licence Creative Commons by-nc-sa-2.0 http://creativecommons.org/licenses/by-nc-sa/2.0/fr/ -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
[ANN] python-daemon 1.4.8
Howdy all, I'm pleased to announce the release of version 1.4.8 of ‘python-daemon’. What is ‘python-daemon’ === The ‘python-daemon’ library is the reference implementation of PEP 3143 URL:http://www.python.org/dev/peps/pep-3143/, “Standard daemon process library”. The source distribution is available via the PyPI page for this version, URL:http://pypi.python.org/pypi/python-daemon/1.4.8/. The latest version is always available via the library's PyPI page URL:http://pypi.python.org/pypi/python-daemon/. What's new in this version == This is a bug-fix version, addressing the problems with a daemon starting child processes. The library no longer defaults to fiddling with the ‘SIGCLD’ signal, and instead leaves that to the customisation by the library user as appropriate. An update to PEP 3143 to document this change in the API is in progress. Thanks to those who raised this issue and helped troubleshoot it (see URL:http://thread.gmane.org/gmane.comp.python.general/629633) and to Joel Martin for finally pinning down where the problem was. -- \ “An expert is a man who has made all the mistakes which can be | `\ made in a very narrow field.” —Niels Bohr | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
Python-URL! - weekly Python news and links (Sep 17)
QOTW: Python the language doesn't try to satisfy all tastes in language design equally. - Guido van Rossum Is it really necesary to explicitely close open files? http://groups.google.com/group/comp.lang.python/t/d794d426a5bef2c1/ Tips for using Unicode text (specially with non-Latin alphabets): http://groups.google.com/group/comp.lang.python/t/89d3ca6ccc8fb876/ How are class attributes exactly inherited, and how they relate to instance attributes: http://groups.google.com/group/comp.lang.python/t/1e146e21b24548f7/ Automatic attribute assignment during class inheritance: http://groups.google.com/group/comp.lang.python/t/f5aeb582a5ab9463/ Composition: delegating all method calls to the contained object may be tedious to write -- alternatives? http://groups.google.com/group/comp.lang.python/t/199ca4f8ac2208/ Calling all bases implementation of overriden methods in cases of multiple inheritance: http://groups.google.com/group/comp.lang.python/t/92895f3c26e61f0d/ Sometimes, a scope for local variables smaller than a function is desired: http://groups.google.com/group/comp.lang.python/t/96ed59e58035b8ef/ More ways to define an empty function that you ever imagined: http://groups.google.com/group/comp.lang.python/t/c9f494b6745c7d74/ There is real advantage in putting the main program body inside a function: http://groups.google.com/group/comp.lang.python/t/e72fd6f765f97117/ Using several Python interpreters in a multithreaded C++ program: http://groups.google.com/group/comp.lang.python/t/f3fc7455efd33b6c/ Best way to store global application parameters: http://groups.google.com/group/comp.lang.python/t/9954a9e505c071e7/ A portable way to open a document using its associated application: http://groups.google.com/group/comp.lang.python/t/445ffc93b0e6a460/ Getting your first job as a Python programmer: http://groups.google.com/group/comp.lang.python/t/c9f494b6745c7d74/ Idea: a namespace object (nested attribute container): http://groups.google.com/group/comp.lang.python/t/dc58821b6681675a/ Idea: multithreading might be easier if most objects were immutable: http://groups.google.com/group/comp.lang.python/t/29c62cbee7a6b598/ Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish the efforts of Python enthusiasts: http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the Planet site: http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes podcasts ... to help people learn Python ... Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.orggroup=gmane.comp.python.develsort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting
Re: Zipped and pickle
Briefly: s = cPickle.dumps(obj) z = zipfile.Zipfile(filename.zip,w,zipfile.ZIP_DEFLATED) z.writestr(arcname.pkl,s) Thank you very much. I have not been aware that pickle can also do the job without a file! Here's the complete scenario for writing and reading the data... APPENDIX: import pickle import zipfile def test1(): print(test1...) # create data data = {} data[first name ] = Thomas data[second name] = Lehmann data[hobbies] = [programming python] print (data) # pickle data pickleString = pickle.dumps(data) # save string to zip under a name file = zipfile.ZipFile(ZippedPickle.zip, w, zipfile.ZIP_DEFLATED) file.writestr(some data, pickleString) file.close() def test2(): print(test2...) file = zipfile.ZipFile(ZippedPickle.zip, r, zipfile.ZIP_DEFLATED) # reading zipped string store under a name pickleString = file.read(some data) # unpickle string to original data data = pickle.loads(pickleString) print (data) file.close() if __name__ == __main__: test1() test2() -- http://mail.python.org/mailman/listinfo/python-list
regex search with a space as the fist character
Hello, print re.compile('u ').search( u box2, 1) _sre.SRE_Match object at 0x7ff1d918 print re.compile(' u ').search( u box2, 1) None Why ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Shebang line problems and python
Blaine skrev: I'm not sure if there is a Ctrl+Z in here... but, here's the output: bla...@attila ~/tmp $ hexdump shebang-test 000 2123 752f 7273 622f 6e69 702f 7479 6f68 010 0a6e 6d69 6f70 7472 7320 7379 730a 7379 020 732e 6474 756f 2e74 7277 7469 2865 4822 030 6c65 6f6c 202c 6f77 6c72 2e64 6e5c 2922 040 000a 041 You can perhaps use hexdump -c shebang-test to get characters instead of hexadecimals. / johan -- http://mail.python.org/mailman/listinfo/python-list
Re: Shebang line problems and python
On Sep 16, 9:25 pm, Blaine brlafreni...@gmail.com wrote: Hello, Scripts that have #!/usr/bin/python at the top do not parse correctly. Bash treats scripts with that shebang as if they are bash scripts. E.g.: bla...@attila ~/apps/rs-mu $ /usr/sbin/env-update /usr/sbin/env-update: line 6: import: command not found /usr/sbin/env-update: line 8: syntax error near unexpected token `(' /usr/sbin/env-update: line 8: `def usage(status):' Scripts with #!/usr/bin/env python at the top work fine. In fact, `python` and `env python` both bring me to a python interpreter. I've tried other types of scripts. #!/bin/bash works, #!/usr/bin/perl works, #!/usr/bin/ruby works, etc. (and so do their #!/usr/bin/env interpreter counterparts.) Because of this, I'm not sure if it is a Python issue or a system issue. Any and all advice appreciated, thanks. P.S. some system info: bla...@attila ~/apps/rs-mu $ uname -a Linux attila 2.6.27-gentoo #5 SMP Sun Oct 19 19:13:17 MST 2008 i686 AMD Athlon(tm) 64 X2 Dual Core Processor 4000+ AuthenticAMD GNU/Linux bla...@attila ~/apps/rs-mu $ python --version Python 2.6.2 bla...@attila ~/apps/rs-mu $ bash --version GNU bash, version 4.0.28(2)-release (i686-pc-linux-gnu) Copyright (C) 2009 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later http://gnu.org/licenses/ gpl.html I think I've discovered the problem. Someone from IRC had directed me here: http://bugs.gentoo.org/show_bug.cgi?id=279915 -- http://mail.python.org/mailman/listinfo/python-list
Re: recommendation for webapp testing?
On Thu, Sep 17, 2009 at 7:51 AM, Schif Schaf schifsc...@gmail.com wrote: After some more searching I found Mechanize (a Python version of Perl's WWW::Mechanize): http://wwwsearch.sourceforge.net/mechanize/ Anyone here tried it? Yes,mechanize has all the features and very simple to use. -- http://mail.python.org/mailman/listinfo/python-list -- Yours, S.Selvam -- http://mail.python.org/mailman/listinfo/python-list
Re: Are min() and max() thread-safe?
On Sep 16, 2009, at 10:39 PM, Steven D'Aprano wrote: On Wed, 16 Sep 2009 22:08:40 -0700, Miles Kaufmann wrote: On Sep 16, 2009, at 9:33 PM, Steven D'Aprano wrote: I have two threads, one running min() and the other running max() over the same list. I'm getting some mysterious results which I'm having trouble debugging. Are min() and max() thread-safe, or am I doing something fundamentally silly by having them walk over the same list simultaneously? min() and max() don't release the GIL, so yes, they are safe, and shouldn't see a list in an inconsistent state (with regard to the Python interpreter, but not necessarily to your application). But a threaded approach is somewhat silly, since the GIL ensures that they *won't* walk over the same list simultaneously (two separate lists, for that matter). Perhaps that's true for list contents which are built-ins like ints, but with custom objects, I can demonstrate that the two threads operate simultaneously at least sometimes. Unless I'm misinterpreting what I'm seeing. Whoops, sorry. Yes, if you use Python functions (or C functions that release the GIL) for the object comparison methods, a custom key function, or the sequence iterator's methods, then the the min()/max() calls could overlap between threads. If you have additional threads that could modify the list, you should synchronize access to it; if any of the earlier-mentioned functions modify the list, you're likely to get mysterious (or at least potentially unexpected) results even in a single-threaded context. On Sep 16, 2009, at 10:41 PM, Niklas Norrthon wrote: For one time sequences like files and generators your code is broken for obvious reasons. s/sequence/iterable/ -Miles -- http://mail.python.org/mailman/listinfo/python-list
Re: Shebang line problems and python
Blaine schrieb: Hello, Scripts that have #!/usr/bin/python at the top do not parse correctly. Bash treats scripts with that shebang as if they are bash scripts. E.g.: bla...@attila ~/apps/rs-mu $ /usr/sbin/env-update /usr/sbin/env-update: line 6: import: command not found /usr/sbin/env-update: line 8: syntax error near unexpected token `(' /usr/sbin/env-update: line 8: `def usage(status):' Scripts with #!/usr/bin/env python at the top work fine. In fact, `python` and `env python` both bring me to a python interpreter. I've tried other types of scripts. #!/bin/bash works, #!/usr/bin/perl works, #!/usr/bin/ruby works, etc. (and so do their #!/usr/bin/env interpreter counterparts.) Because of this, I'm not sure if it is a Python issue or a system issue. Any and all advice appreciated, thanks. Do you have a DOS-file-ending in your script by any chance? Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: regex search with a space as the fist character
Daniel Santos schrieb: Hello, print re.compile('u ').search( u box2, 1) _sre.SRE_Match object at 0x7ff1d918 print re.compile(' u ').search( u box2, 1) None Why ? because you start searching at the offset 1, which means you try to find u in u box2 - and that's not found. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Are min() and max() thread-safe?
Steven D'Aprano ste...@remove.this.cybersource.com.au writes: min() and max() don't release the GIL, so yes, they are safe, and shouldn't see a list in an inconsistent state (with regard to the Python interpreter, but not necessarily to your application). But a threaded approach is somewhat silly, since the GIL ensures that they *won't* walk over the same list simultaneously (two separate lists, for that matter). Perhaps that's true for list contents which are built-ins like ints, but with custom objects, I can demonstrate that the two threads operate simultaneously at least sometimes. Unless I'm misinterpreting what I'm seeing. If min and max call into Python code, which can happen for custom objects, then the interpreter will occasionally release the GIL to give other threads a chance to run. That way min and max will operate interleaved (if not exactly in parallel). Even so, I see no reason for them to break. -- http://mail.python.org/mailman/listinfo/python-list
Re: recommendation for webapp testing?
On Sep 17, 4:21 am, Schif Schaf schifsc...@gmail.com wrote: After some more searching I found Mechanize (a Python version of Perl's WWW::Mechanize): http://wwwsearch.sourceforge.net/mechanize/ Anyone here tried it? Twill uses mechanize internally. -- http://mail.python.org/mailman/listinfo/python-list
Re: Shebang line problems and python
I think I've discovered the problem. Someone from IRC had directed me here: http://bugs.gentoo.org/show_bug.cgi?id=279915 I would suggest testing with the Python binary itself in your shebang line (e.g. #!/usr/bin/python2.6, if it's in /usr/bin) to confirm, but that looks like it :-) Rami Chowdhury Any sufficiently advanced incompetence is indistinguishable from malice. -- Grey's Law 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Wednesday 16 September 2009 23:27:12 Blaine wrote: On Sep 16, 9:25 pm, Blaine brlafreni...@gmail.com wrote: Hello, Scripts that have #!/usr/bin/python at the top do not parse correctly. Bash treats scripts with that shebang as if they are bash scripts. E.g.: bla...@attila ~/apps/rs-mu $ /usr/sbin/env-update /usr/sbin/env-update: line 6: import: command not found /usr/sbin/env-update: line 8: syntax error near unexpected token `(' /usr/sbin/env-update: line 8: `def usage(status):' Scripts with #!/usr/bin/env python at the top work fine. In fact, `python` and `env python` both bring me to a python interpreter. I've tried other types of scripts. #!/bin/bash works, #!/usr/bin/perl works, #!/usr/bin/ruby works, etc. (and so do their #!/usr/bin/env interpreter counterparts.) Because of this, I'm not sure if it is a Python issue or a system issue. Any and all advice appreciated, thanks. P.S. some system info: bla...@attila ~/apps/rs-mu $ uname -a Linux attila 2.6.27-gentoo #5 SMP Sun Oct 19 19:13:17 MST 2008 i686 AMD Athlon(tm) 64 X2 Dual Core Processor 4000+ AuthenticAMD GNU/Linux bla...@attila ~/apps/rs-mu $ python --version Python 2.6.2 bla...@attila ~/apps/rs-mu $ bash --version GNU bash, version 4.0.28(2)-release (i686-pc-linux-gnu) Copyright (C) 2009 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later http://gnu.org/licenses/ gpl.html I think I've discovered the problem. Someone from IRC had directed me here: http://bugs.gentoo.org/show_bug.cgi?id=279915 -- http://mail.python.org/mailman/listinfo/python-list
Re: Are min() and max() thread-safe?
Steven D'Aprano wrote: I have two threads, one running min() and the other running max() over the same list. I'm getting some mysterious results which I'm having trouble debugging. Are min() and max() thread-safe, or am I doing something fundamentally silly by having them walk over the same list simultaneously? My code is as follows. Is there anything obviously wrong with it? You don't seem to be modifying the data while iterating over it, so there's no real race condition issue. All Python guarantees is that you can't break the underlying memory model with threading. You're not guaranteed, for example, that min is atomic. There's a short list of primitives whose atomicity is guaranteed, at http://effbot.org/zone/thread-synchronization.htm In particular, some operations like appending to a list and popping an element from a list are atomic, which is useful. Be aware that CPython performance on multithreaded programs really sucks on multicore CPUs. Not only does the GIL prevent two CPUs from doing useful work at the same time, the locking logic is horribly inefficient for multiprocessors. Adding an additional CPU actually increases run time as the CPUs fight over the lock. So there's little point in doing this. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Compiler.ast helper function literal_eval in python 2.4
En Fri, 04 Sep 2009 18:43:28 -0300, Sean Talts xitr...@gmail.com escribió: I'm trying to parse some python with the compiler module, select a subset of the AST returned, and then evaluate that subset, all in python 2.4. It seems like in python 2.6 the compiler.ast.literal_eval function may be what I'm looking for, but unfortunately for my project we are restricted to using 2.4. I was wondering if there was some way programmers performed this way back when? Better late than never :) This is a backport of 2.6 literal_eval using the compiler package as of 2.4; I had to add UnarySub (else -3 would be invalid) and change some attribute names, but basically it's the same code. Untested except as shown. from compiler import parse from compiler.ast import * def literal_eval(node_or_string): Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None. _safe_names = {'None': None, 'True': True, 'False': False} if isinstance(node_or_string, basestring): node_or_string = parse(node_or_string, mode='eval') if isinstance(node_or_string, Expression): node_or_string = node_or_string.node def _convert(node): if isinstance(node, Const) and isinstance(node.value, (basestring, int, float, long, complex)): return node.value elif isinstance(node, Tuple): return tuple(map(_convert, node.nodes)) elif isinstance(node, List): return list(map(_convert, node.nodes)) elif isinstance(node, Dict): return dict((_convert(k), _convert(v)) for k, v in node.items) elif isinstance(node, Name): if node.name in _safe_names: return _safe_names[node.name] elif isinstance(node, UnarySub): return -_convert(node.expr) raise ValueError('malformed string') return _convert(node_or_string) py print literal_eval((1, [-2.,'3',4j], {-5:None, u'6':True})) (1, [-2.0, '3', 4j], {-5: None, u'6': True}) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: recommendation for webapp testing?
2009/9/17 Schif Schaf schifsc...@gmail.com: What's the difference between WebDriver and Selenium? Selenium runs in a browser, and uses JavaScript to perform all your automated actions. It need a browser running to work. Several are supported, Firefox, Safari, IE and I think others. You are at thier mercy of the browser's JavaScript engine - I've often had trouble with IE's XPath support, for instance - tests will run fine in Firefox and safari, but not work in IE. One big advantage of Selenium is that there an IDE available, a Firefox add-on which will allow you to record actions. This is useful for building regression tests and acceptance tests for bugs. Sadly, it often tempts people into writing their acceptance tests after the fact, too - a grave mistake IMHO. Selenium tests can be written in Python, Ruby, Java, and in the form of HTML tables. This last seems quite popular with QAs for some reason which escapes me entirely. WebDriver runs outside a browser. It can be (and usually is) used to drive a real browser, though there's is a HtmlUnit driver available, which bypasses any real browser and goes direct to the site you are testing. Even this last option, though, does allow the testing of sites which make use of JavaScript - which is just about all of them these days. It makes use of native drivers for each of the browsers it supports, so it runs very much faster than Selenium. Since it presents the test program with its own version of the page's DOM tree, it's also less likely to give browser incompatibilities. WebDriver tests can be written in Java or Python, at the moment. The Selenium people have recognized the superiority of the WebDriver approach, so the nascent Selenium 2 will use WebDriver under the covers. For the moment, though, you have to pick one or the other. Mechanize is a superb library for its intended purpose - I use it all the time. It's lack of support for pages with JavaScript functionality, though, means it's not very useful at a testing tool for modern web sites. -- Cheers, Simon B. -- http://mail.python.org/mailman/listinfo/python-list
[ANN] python-daemon 1.4.8
Howdy all, I'm pleased to announce the release of version 1.4.8 of ‘python-daemon’. What is ‘python-daemon’ === The ‘python-daemon’ library is the reference implementation of PEP 3143 URL:http://www.python.org/dev/peps/pep-3143/, “Standard daemon process library”. The source distribution is available via the PyPI page for this version, URL:http://pypi.python.org/pypi/python-daemon/1.4.8/. The latest version is always available via the library's PyPI page URL:http://pypi.python.org/pypi/python-daemon/. What's new in this version == This is a bug-fix version, addressing the problems with a daemon starting child processes. The library no longer defaults to fiddling with the ‘SIGCLD’ signal, and instead leaves that to the customisation by the library user as appropriate. An update to PEP 3143 to document this change in the API is in progress. Thanks to those who raised this issue and helped troubleshoot it (see URL:http://thread.gmane.org/gmane.comp.python.general/629633) and to Joel Martin for finally pinning down where the problem was. -- \ “An expert is a man who has made all the mistakes which can be | `\ made in a very narrow field.” —Niels Bohr | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of the Unicode standard
Hendrik van Rooyen hend...@microcorp.co.za wrote: The opposite thing is of course a continual source of trouble - we all have words for stuff we have never seen, like dragon, ghost, goblin, leprechaun, the current King of France, God, Allah, The Holy Trinity, Lucifer, Satan, Griffin - and because we have words for these things, we can, and unfortunately do, think about them, in a fuzzy fashion, to our own detriment. People even go around killing other people, based on such fuzzy thinking about stuff that can not be shown to exist. Okay class, this weekend's assignment is to read Wittgenstein's Philosophical Investigations and then return here on Monday to discuss :) (For someone who is not a linguist, Hendrik, you have a really solid grasp on the fundamentals of the field...) -- http://mail.python.org/mailman/listinfo/python-list
SQLite or files?
Hello, I'm a novice in Python and got one question related to the information storage for my application. I'm currently working on rewriting my own the program that stores everyday information sitting in the system tray. It was written in Delphi some time ago and proved to be durable and fast enough. All the info was stored in the simple RTF files. However now I'd like to rewrite this program in Python (using PyQt) as I want to make it cross-platform and add/remove some features. Now I'm thinking about where to store my information. Would it be better to use files as I used to do or use the database, SQLite in particular? What will be faster and more flexible in the long run? This application will be in the memory most of the time so I'm also concerned about memory usage. If anyone has any experience of comparison these two approaches please help. Thanks, Vlad -- http://mail.python.org/mailman/listinfo/python-list
Re: Are min() and max() thread-safe?
On Sep 16, 11:33 pm, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: I have two threads, one running min() and the other running max() over the same list. I'm getting some mysterious results which I'm having trouble debugging. Are min() and max() thread-safe, or am I doing something fundamentally silly by having them walk over the same list simultaneously? If you are calculating both min and max of a sequence, here is an algorithm that can cut your comparisons by 25% - for objects with rich/ time-consuming comparisons, that can really add up. import sys if sys.version[0] == 2: range = xrange def minmax(seq): if not seq: return None, None min_ = seq[0] max_ = seq[0] seqlen = len(seq) start = seqlen % 2 for i in range(start,seqlen,2): a,b = seq[i],seq[i+1] if a b: a,b = b,a if a min_: min_ = a if b max_: max_ = b return min_,max_ With this test code, I verified that the comparison count drops from 2*len to 1.5*len: if __name__ == __main__: import sys if sys.version[0] == 2: range = xrange import random def minmax_bf(seq): # brute force, just call min and max on sequence return min(seq),max(seq) testseq = [random.random() for i in range(100)] print minmax_bf(testseq) print minmax(testseq) class ComparisonCounter(object): tally = 0 def __init__(self,obj): self.obj = obj def __cmp__(self,other): ComparisonCounter.tally += 1 return cmp(self.obj,other.obj) def __getattr__(self,attr): return getattr(self.obj, attr) def __str__(self): return str(self.obj) def __repr__(self): return repr(self.obj) testseq = [ComparisonCounter(random.random()) for i in range (10001)] print minmax_bf(testseq) print ComparisonCounter.tally ComparisonCounter.tally = 0 print minmax(testseq) print ComparisonCounter.tally Plus, now that you are finding both min and max in a single pass through the sequence, you can wrap this in a lock to make sure of the atomicity of your results. (Just for grins, I also tried sorting the list and returning elements 0 and -1 for min and max - I got numbers of comparisons in the range of 12X to 15X the length of the sequence.) -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: weird str error
daved170 wrote: On Sep 15, 6:29 pm, Peter Otten __pete...@web.de wrote: daved170 wrote: Hi everybody, I'm using SPE 0.8.3.c as my python editor. I'm using thestr() function and i got a very odd error. I'm trying to do this: printstr(HI) When i'm writing this line in the shell it prints: HI When it's in my code (it's the only line) i'm getting the following error: file c:\Python25\lib\local.py line 242, instr return format(%.12g,val) file c:\Python25\lib\local.py line 145, in format formatted = percent % value TypeError, float argument required any idea? It's worked for the entire day and unfortunately when i started my testing it raised this erroe/ local.py or locale.py? If the latter you are probably doing a star import: from locale import * This will replace the builtinstr() with locale.str() which indeed requires a float: str(HI) 'HI' from locale import * str(HI) Traceback (most recent call last): File stdin, line 1, in module File /usr/lib/python2.5/locale.py, line 244, instr return format(%.12g, val) File /usr/lib/python2.5/locale.py, line 147, in format formatted = percent % value TypeError: float argument required As a general rule use the standard import import locale and then invoke the module's functions with an explicit prefix: locale.setlocale(...) It's a bit more to type, but it will save you a lot of trouble. Peter PS: Whenstr() is the builtinstr(HI) converts a string into a string which does not make much sense.- Hide quoted text - - Show quoted text - Hi Peter, Thanks for your answer. I'll clearify myself. I'm using QString cause I have a GUI app. I want to convert it to python string. It works well for several month and suddenly two days ago it didn't. I'm not using localE at all (i'm not importing it). After your answer I tried it but it still didn't work. You mean you don't have any star imports in the module causing error? Any other ideas? Run your script from the command line (not your editor). Then give the complete traceback. Grep through the libraries you use for 'from locale' and 'import locale' to identify the one that uses the locale module. You can identify modules used by your script by running python -v script.py Aside: if you use a version control system and check in frequently it gets easier to identify a modification that introduced an error. Highly recommended. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Are min() and max() thread-safe?
On Thursday 17 September 2009 06:33:05 Steven D'Aprano wrote: I have two threads, one running min() and the other running max() over the same list. I'm getting some mysterious results which I'm having trouble debugging. Are min() and max() thread-safe, or am I doing something fundamentally silly by having them walk over the same list simultaneously? My code is as follows. Is there anything obviously wrong with it? Apart from the plethora of indirection, nothing I can see. But there is something rotten. Going more basic, look at this: h...@linuxbox:~/Junk cat jjj.py import thread as th import time a = range(1000) def worker(func,thing): start_time = time.time() print start time is:,start_time res = func(thing) print res end_time = time.time() print End at:,end_time,That took:,end_time-start_time, 'seconds' t1 = th.start_new_thread(worker,(min,a)) t2 = th.start_new_thread(worker,(max,a)) while True: time.sleep(1) h...@linuxbox:~/Junk python -i jjj.py start time is: 1253176132.64 0 End at: 1253176133.34 That took: 0.700681209564 seconds start time is: 1253176133.34 999 End at: 1253176134.18 That took: 0.84756612 seconds Traceback (most recent call last): File jjj.py, line 18, in module time.sleep(1) KeyboardInterrupt No simultaneity. So when I increase the range to a hundred million to try to force some concurrency, I get: h...@linuxbox:~/Junk python -i jjj.py Killed h...@linuxbox:~/Junk The behaviour is that it just thrashes for some minutes and then it looks like the os kills it. SuSe Linux, dual core Intel with a gig of memory: Python 2.5.1 (r251:54863, Dec 6 2008, 10:49:39) [GCC 4.2.1 (SUSE Linux)] on linux2 I enclose the file. - Hendrik jjj.py Description: application/python -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a pure Python chart drawing module
Vlastimil Brom vlastimil.b...@gmail.com writes: As for BLT, there is Pmw.Blt, the original is written in Tcl. doesn't work (dumps core) on debian linux bug #525860: python-pmw triggers segmentation fault in blt not that blt itself is really OK bug #524149: blt: zooming in a graph produces segmentation fault -- Io ti saluto diventa equivalente ad io saluto te -- gobbacci, in ISC -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a pure Python chart drawing module
John Nagle na...@animats.com writes: gerlos wrote: John Nagle ha scritto: I'm looking for something that can draw simple bar and pie charts in Python. I'm trying to find a Python package, not a wrapper for some C library, as this has to run on both Windows and Linux and version clashes are a problem. Did you look at matplotlib? In their examples page there are some charts like the ones you asked for. I guess it could work for you, and it seems to work flawlessy in MS Windows as in gnu/linux. That's a wrapper for Antigrain (http://www.antigrain.com/;), which is a C++ library. come on, you can configure matplotlib to use one of too many different backends from http://matplotlib.sourceforge.net/users/customizing.html CONFIGURATION BEGINS HERE # the default backend; one of GTK GTKAgg GTKCairo CocoaAgg FltkAgg # MacOSX QtAgg Qt4Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG Template # You can also deploy your own backend outside of matplotlib by # referring to the module name (which must be in the PYTHONPATH) as # 'module://my_backend' backend : GTKAgg -- Yes you who must leave everything that you cannot control. It begins with your family, but soon it comes around to your soul. Well I've been where you're hanging, I think I can see how you're pinned: When you're not feeling holy, your loneliness says that you've sinned. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python C/API Problem
En Sat, 12 Sep 2009 07:37:18 -0300, Gianfranco Murador miten...@gmail.com escribió: Ok, I solved the previous error changing the second argument , but i have another question. Does PyNode_Compile function store the object code in the file passed as argument? And it will be execute by python? I mean, it works if i type 'python prova.pyc'? No; the filename you pass in is just to set the co_filename attribute of code objects, and such things. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: VT100 in Python
On Mon, 14 Sep 2009 04:29:57 -0500, Nick Craig-Wood wrote: At a basic level parsing VT100 is quite easy, so you can get rid of the VT100 control. They start with ESC, have other characters in the middle then end with a letter (upper or lowercase), so a regexp will make short work of them. Something like r\x1B[^A-Za-z]*[A-Za-z] While this pattern is common, unfortunately there are some exceptions. Also, vt100 has become a generic term for terminal emulation. There is no guarantee that the OP actually wants to parse vt100 escapes and nothing else. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.execv Overhead
On Wed, 16 Sep 2009 08:12:50 -0700, mark.mcdow...@gmail.com wrote: I have a script that automates running a program X times by preparing the required files and passing the external program right variables. What I am unsure about though is the overhead of: program = externalScript variables = [-i, var1] pid = os.fork() if not pid: os.execv(program, [program] + variables) os.wait() Whether there would be a more efficient way of making such a call. I would expect the overhead to be dominated by the underlying fork() and execve() system calls, rather than anything within Python. OTOH, using subprocess.call() wouldn't be any slower, and is more portable. -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLite or files?
info was stored in the simple RTF files. However now I'd like to rewrite this program in Python (using PyQt) as I want to make it cross-platform and add/remove some features. Now I'm thinking about where to store my information. Would it be better to use files as I used to do or use the database, SQLite in particular? What will be faster and more flexible in the long run? This application will be in the memory most of the time so I'm also concerned about memory usage. Not knowing what you do with the files, nor what sort of data they contain makes it a bit difficult to make suggestions in light of the context. However: - sqlite will let you perform arbitrary queries against your data, so if you want to aggregate or perform complex conditional tests, it's just SQL. - I don't know if you're currently keeping the RTF in memory the whole time, or if you repeatedly reload (whether in one go, or streaming it) and reparse the file. This sounds memory and/or processor intensive. Using sqlite, the processing is done at the C-module level, the data is kept on disk and only brought into memory as-requested, being released when you're done with it. - concurrently sharing a sqlite database should have minimal issues. Sharing RTF files concurrently means locking/contention issues. May not be an issue for you. - sqlite comes built-in with Python2.5+ while RTF processing is not batteries-included from what I can tell[1] So in the general case, I see sqlite being a notable win over RTF. Depending on your data, if it's just key/value pairs of strings, you might look into the anydbm module[2] which has an even simpler interface. -tkc [1] http://pyrtf.sf.net [2] http://docs.python.org/library/anydbm.html -- http://mail.python.org/mailman/listinfo/python-list
xlrd+excel determine decimal separator
Hi experts, i want to ask you if somebody knows how can I determine, with a help of xlrd, what kind of decimal separator (. or ,) does the user have. Thx in advance. Rg, Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Are min() and max() thread-safe?
On Sep 17, 2:18 am, Hendrik van Rooyen hend...@microcorp.co.za wrote: On Thursday 17 September 2009 06:33:05 Steven D'Aprano wrote: I have two threads, one running min() and the other running max() over the same list. I'm getting some mysterious results which I'm having trouble debugging. Are min() and max() thread-safe, or am I doing something fundamentally silly by having them walk over the same list simultaneously? My code is as follows. Is there anything obviously wrong with it? Apart from the plethora of indirection, nothing I can see. But there is something rotten. Going more basic, look at this: h...@linuxbox:~/Junk cat jjj.py import thread as th import time a = range(1000) def worker(func,thing): start_time = time.time() print start time is:,start_time res = func(thing) print res end_time = time.time() print End at:,end_time,That took:,end_time-start_time, 'seconds' t1 = th.start_new_thread(worker,(min,a)) t2 = th.start_new_thread(worker,(max,a)) while True: time.sleep(1) h...@linuxbox:~/Junk python -i jjj.py start time is: 1253176132.64 0 End at: 1253176133.34 That took: 0.700681209564 seconds start time is: 1253176133.34 999 End at: 1253176134.18 That took: 0.84756612 seconds Traceback (most recent call last): File jjj.py, line 18, in module time.sleep(1) KeyboardInterrupt No simultaneity. When running min or max on a list of ints, there is probably no occasion for the function to release the GIL. If a thread doesn't release the GIL no other Python threads can run. This behavior may be rotten, but it's totally expected. Try adding key=lambda x:x to the function call (which adds an occasion where the GIL might be released); you will see that it will switch threads. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Redirect output on script
I would like to redirect the output of the command below to another file type test.txt test.bak I'm trying to do this as part of a python script running on Windows XP. I'm using os.system('type filepath.txt filepath.bak') but nothing is happening. I was wondering if somebody could enlighten me. Thanks, Glenn Pringle -- http://mail.python.org/mailman/listinfo/python-list
Re: PyQt QCompleter model
On Sep 17, 2:40 am, David Boddie da...@boddie.org.uk wrote: On Thursday 17 September 2009 01:14, nusch wrote: The following code: strings=[asdad, baasd, casd, caxd] completer = QCompleter(strings) model = completer.model() print model.rowCount() model.stringList().append(test) This may not work as you expect. Although it may actually modify the list, the model won't know about the change. print model.rowCount() prints 4 before and after appending test to stringList. What should I do to let the model know about new data? I can save reference to model.stringList() append keyword and after pass this reference as an argument to setStringList then last model.rowCount() increases, but it is not efficient when operating with e.g 2 words in such list. Ideally, you would call setStringList(), but I can see why that isn't a good solution for you. Is there better way to do this? Or is there any other method with simply allow to add word to Qcompleter without using .stringList() Use the model API to append new rows and set new data. Something like this should get you started: rows = model.rowCount() if model.insertRow(rows): index = model.index(rows) model.setData(index, QVariant(test)) David Thanks :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Are min() and max() thread-safe?
On Sep 16, 9:33 pm, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: def minmax(seq): result = [None, None] t1 = MMThread(seq, min, result, 0) t2 = MMThread(seq, max, result, 1) t1.start() t2.start() # Block until all threads are done. while any([t1.isAlive(), t2.isAlive()]): time.sleep(0) Why not use t1.join(); t2.join() here? Is there any benefit to do it this way instead? Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Load TTF from pycairo under Windows
Hi All, I have a program that works under Ubuntu. It loads a TTF font into pycairo, using libfreetype. The code snippet I used was taken from here: http://cairographics.org/freetypepython/ Now I need to use the same program from Microsoft Windows. But Windows does not have libfreetype.so, nor its DLL version. How should I do this? Thanks, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLite or files?
I like shelve for saving small amounts of data, user preferences, recent files etc. http://docs.python.org/library/shelve.html For Qt use QtCore.QCoreApplication.setOrganizationName, QtCore.QCoreApplication.setApplicationName than setValue, value from QtCore.QSettings. -- http://mail.python.org/mailman/listinfo/python-list
Re: Debugging with gdb: pystack macro for gdb to show python stack trace
Timothy Madden wrote: Hello [...] Can I get the python stack trace working under gdb ? [...] Ok I found some other gdb macros on linked from the wiki page and I had to change them to get the stack trace work. I had to change the symbol PyEval_EvalFrame to PyEval_EvalFrameEx and then I could see the stack trace. The resulting gdb macro was: define pbt set $i = 0 set $j = 0 while $i 1000 select $i if $eip = PyEval_EvalFrameEx if $eip PyEval_EvalCodeEx echo c frame # p $i echo py frame # p $j set $j = $j+1 x/s ((PyStringObject*)f-f_code-co_filename)-ob_sval x/s ((PyStringObject*)f-f_code-co_name)-ob_sval echo line # p f-f_lineno end end set $i = $i+1 end end document pbt show python backtrace end Thank you, Timothy Madden -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirect output on script
glenn.prin...@gmail.com wrote: I would like to redirect the output of the command below to another file type test.txt test.bak I'm trying to do this as part of a python script running on Windows XP. I'm using os.system('type filepath.txt filepath.bak') but nothing is happening. Try: os.system('type filepath.txt filepath.bak') or just: os.system('type filepath.txt filepath.bak') I was wondering if somebody could enlighten me. -- http://mail.python.org/mailman/listinfo/python-list
Re: Collection console output
MRAB wrote: Esben von Buchwald wrote: Hello Are there any simple ways to collect the data, python prints to the console when running an app? I'm doing som apps for S60 mobile phones and can't see the console, when the UI is running, but i'd like to collect the output, to look for eventual exceptions etc. Cant it be redirected to a log file, just like when runing a script in unix, where you say $ ./script.pl logfile.txt ? Does the S60 support a command line like *nix and Windows? An alternative from within the script is: import sys sys.stdout = open(log_path, w) You might also want to capture stderr: import sys log_file = open(log_path, w) sys.stdout = log_file sys.stderr = log_file Thanks a lot - it works fine :) I've made this class which works perfectly class Consolefile: def __init__(self): self.file=None self.status='init' def start(self): self.filename=%s\\%s_console.log%(cfg.logdir,FILEID) print self.filename self.oldstderr=sys.stderr self.oldstdout=sys.stdout self.file=open(self.filename,'w') print self.file, '#Logging STDERR and STDOUT to this file' sys.stderr=self.file sys.stdout=self.file self.status='started' def stop(self): print self.file, '#Console logging stopped' sys.stderr=self.oldstderr sys.stdout=self.oldstdout self.file.close() self.status='stopped' -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirect output on script
Hi! import os os.system('cmd /c type L:\\source.fic L:\\destination.txt') @-salutations -- Michel Claveau -- http://mail.python.org/mailman/listinfo/python-list
Re: Are min() and max() thread-safe?
On Thursday 17 September 2009 12:57:18 Carl Banks wrote: On Sep 17, 2:18 am, Hendrik van Rooyen hend...@microcorp.co.za wrote: When running min or max on a list of ints, there is probably no occasion for the function to release the GIL. If a thread doesn't release the GIL no other Python threads can run. This behavior may be rotten, but it's totally expected. The lack of concurrency was not what I was complaining about, but the second case that just quietly freaked out when I made the list of ints large. I have subsequently seen that it is red herring in this context though, as it is some memory problem - the crash comes during the list creation, and has nothing to do with the min/max processing. One can demo it by simply trying to create a big list at the interactive prompt, and after a while you get the Killed message. a = range(1) does it for me on my machine. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: xlrd+excel determine decimal separator
On Sep 17, 8:40 pm, peter bori...@gmail.com wrote: i want to ask you if somebody knows how can I determine, with a help of xlrd, what kind of decimal separator (. or ,) does the user have. It's nothing to do with xlrd. It reads files and gives you the numbers as Python floats. Note that a user of locale A (uses '.') can save an Excel file and send it to a user of locale B (uses ',') and the receiver will see ',' -- as you might expect, locale-specific info is not kept in the file. If you want to find out the current user's decimal separator (and other useful info), use the locale module. Here's what I get after I change my regional settings on Windows XP to French/France: Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. import locale locale.setlocale(locale.LC_ALL, '') 'French_France.1252' locale.localeconv() {'mon_decimal_point': ',', 'int_frac_digits': 2, 'p_sep_by_space': 1, 'frac_digits': 2, 'thousands_sep': '\xa0', 'n_sign_posn': 1, 'decimal_point': ',', 'int_curr_symbol': 'EUR', 'n_cs_precedes': 0, 'p_sign_posn': 1, 'mon_thousands_sep': '\xa0', 'negative_sign': '-', 'currency_symbol': '\x80', 'n_sep_by_space': 1, 'mon_grouping': [3, 0], 'p_cs_precedes': 0, 'positive_sign': '', 'grouping': [3, 0]} Note: there are two different decimal separators. After switching it back to normal and re-starting Python: import locale locale.setlocale(locale.LC_ALL, '') 'English_Australia.1252' locale.localeconv() {'mon_decimal_point': '.', 'int_frac_digits': 2, 'p_sep_by_space': 0, 'frac_digits': 2, 'thousands_sep': ',', 'n_sign_posn': 3, 'decimal_point': '.', 'int_curr_symbol': 'AUD', 'n_cs_precedes': 1, 'p_sign_posn': 3, 'mon_thousands_sep': ',', 'negative_sign': '-', 'currency_symbol': '$', 'n_sep_by_space': 0, 'mon_grouping': [3, 0], 'p_cs_precedes': 1, 'positive_sign': '', 'grouping': [3, 0]} HTH, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and 3d
On 14 Sep, 00:05, Carl Banks pavlovevide...@gmail.com wrote: Dice3DS works fine with PyOpenGL 3.x. PyOpenGL is a bad idea anyway, due to the overhead of Python function calls and ctypes. Doing 3D in pure Python at least requires NumPy arrays as vertex arrays and/or extensive use of display lists. But there are better alternatives. My current approach is use Cython + NumPy, and accumulate calls to OpenGL in a C function. I prefer to keep calls to OpenGL in C (not Cython), because this way I don't have to define the OpenGL API to Cython. Cython merely becomes a glue layer between Python and C. With NumPy support in Cython, this is a nice way of storing contiguous vertex array. NumPy even allows Fortran ordering, which is used by OpenGL. Another nice way of using OpenGL from Python is the Fortran bindings (f90gl or F03GL). One can accumulate calls to OpenGL in a Fortran 95 subroutine, and make it callable from Python with f2py. -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of the Unicode standard
2009/9/15 Hendrik van Rooyen hend...@microcorp.co.za: On Monday 14 September 2009 14:06:36 Christopher Culver wrote: This is the old Sapir-Whorf hypothesis, which fell out of favour among linguists half a century ago already. 1) Language does not constrain human thought, and 2) any two human languages are both capable of expressing the same things, though one may already have a convenient lexeme for the topic at hand while the other uses circumlocution. 1) Is an assumption, not a proven fact. falling out of favour is merely fashion amongst people who are dabbling in fuzzy areas where the hard discipline of the scientific method is inapplicable, because it is kind of hard to prove or disprove that my thinking and yours differ because my first language is different to yours. - we end up talking about our beliefs, after telling war stories. There are good reasons for it falling out of favour, though. At the time of the Sapir-Whorf hypothesis, anthropologists were arguing that members of a certain remote tribe did not experience grief on the death of a child because their language did not have a word for grief. They showed all the *signs* of grief -- weeping and wailing and so on -- and sometimes used metaphors (I feel as if my inside is being crushed). But because of the conviction at the time that if your language does not have a word for something, and you have never seen that object, then you __cannot__ think about it the anthropologists were convinced that this just looked and sounded like grief and wasn't actually grief. By the way, at the moment I am thinking of a sort of purple blob-shaped monster with tentacles and fangs, that my language doesn't have a word for and that I have never seen. On your theory, how come I am thinking about it? -- Tim Rowe -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of the Unicode standard
On 2009-09-15, r rt8...@gmail.com wrote: Are you telling us people using a language that does not have a word for window somehow cannot comprehend what a window is, are you mad man? Words are simply text attributes attached to objects. the text attribute doesn't change the object in any way. just think of is __repr__ Err, no, it's a bit more complicated than that. Words map to material objects, to concepts, abstracta, sets, relations, states of affairs, to mental states, to different senses of the same object. What object is the word bachelor attached to? And why is it that suddenly the label - that's all it is, after all - stops being applicable after a person gets married. To use the classic example: The Morning Star is the Evening Star. The object is the same - Venus. But the sense in which the words are used are different: you wouldn't say that's the Evening Star! in the morning. If words are just dumb strings attached to objects, then someone saying The Morning Star is the Evening Star is saying no more than a = a. Your review of the Unicode standard is utterly naïve. There fact is that even if everyone we could wave a magic wand and ensure that everyone on the planet spoke the same language - English, for the sake of argument - that would not negate the need for using other character sets. A historian wants to typeset a book on ancient Greek civilization, where Greek characters are used interchangably with English characters. Here, having a uniform character set for all characters that one might feasibly want to use from all known civilizations from throughout history that it is practical to represent is superbly useful. Other areas of life use their own symbols, many of which are present in the Unicode specification including mathematical symbols, logic symbols, musical notes, IPA phonetic symbols, currency symbols, chess and playing card symbols, dingbats and much more. For basic typesetting, the Unicode standard also contains a variety of spaces, dashes and other typographical components which are not represented in Latin-1. The fact is that every language with characters in the Unicode standard generally have a large body of literature behind them - not necessarily literature like Shakespeare, but things which tell the story of a culture. How would you digitise those for search and study? Without the characters to represent those languages, you could say that it would be ideal to just translate them into the global language. Great. Do you trust the translators to do the job once and forever? Take any ancient text which still has relevance today for religion or culture or philosophy, and you'll find that anyone who *really* wants to understand it goes back to the original text in the original language. I'd really love to have some excellent language-to-language compilers that could, say, turn Ruby into Python into Java into C and vice versa. And do so reliably. Where are they? Show me perfect machine translation and then we can maybe stop bothering about other languages. [1] http://en.wikipedia.org/wiki/Unicode_Mathematical_Operators -- Tom Morris http://tommorris.org/ -- http://mail.python.org/mailman/listinfo/python-list
Python-URL! - weekly Python news and links (Sep 17)
QOTW: Python the language doesn't try to satisfy all tastes in language design equally. - Guido van Rossum Is it really necesary to explicitely close open files? http://groups.google.com/group/comp.lang.python/t/d794d426a5bef2c1/ Tips for using Unicode text (specially with non-Latin alphabets): http://groups.google.com/group/comp.lang.python/t/89d3ca6ccc8fb876/ How are class attributes exactly inherited, and how they relate to instance attributes: http://groups.google.com/group/comp.lang.python/t/1e146e21b24548f7/ Automatic attribute assignment during class inheritance: http://groups.google.com/group/comp.lang.python/t/f5aeb582a5ab9463/ Composition: delegating all method calls to the contained object may be tedious to write -- alternatives? http://groups.google.com/group/comp.lang.python/t/199ca4f8ac2208/ Calling all bases implementation of overriden methods in cases of multiple inheritance: http://groups.google.com/group/comp.lang.python/t/92895f3c26e61f0d/ Sometimes, a scope for local variables smaller than a function is desired: http://groups.google.com/group/comp.lang.python/t/96ed59e58035b8ef/ More ways to define an empty function that you ever imagined: http://groups.google.com/group/comp.lang.python/t/c9f494b6745c7d74/ There is real advantage in putting the main program body inside a function: http://groups.google.com/group/comp.lang.python/t/e72fd6f765f97117/ Using several Python interpreters in a multithreaded C++ program: http://groups.google.com/group/comp.lang.python/t/f3fc7455efd33b6c/ Best way to store global application parameters: http://groups.google.com/group/comp.lang.python/t/9954a9e505c071e7/ A portable way to open a document using its associated application: http://groups.google.com/group/comp.lang.python/t/445ffc93b0e6a460/ Getting your first job as a Python programmer: http://groups.google.com/group/comp.lang.python/t/c9f494b6745c7d74/ Idea: a namespace object (nested attribute container): http://groups.google.com/group/comp.lang.python/t/dc58821b6681675a/ Idea: multithreading might be easier if most objects were immutable: http://groups.google.com/group/comp.lang.python/t/29c62cbee7a6b598/ Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish the efforts of Python enthusiasts: http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the Planet site: http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes podcasts ... to help people learn Python ... Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.orggroup=gmane.comp.python.develsort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting
Re: SQLite or files?
ici iltch...@gmail.com writes: I like shelve for saving small amounts of data, user preferences, recent files etc. http://docs.python.org/library/shelve.html I like it too, but I hear the great powers that be are going to deprecate it. For Qt use QtCore.QCoreApplication.setOrganizationName, QtCore.QCoreApplication.setApplicationName than setValue, value from QtCore.QSettings. -- http://mail.python.org/mailman/listinfo/python-list
Re: [ANN] python-daemon 1.4.8
Ben Finney ben+pyt...@benfinney.id.au writes: The ‘python-daemon’ library is the reference implementation of PEP 3143 URL:http://www.python.org/dev/peps/pep-3143/, “Standard daemon process library”. The source distribution is available via the PyPI page for this version, URL:http://pypi.python.org/pypi/python-daemon/1.4.8/. The latest version is always available via the library's PyPI page URL:http://pypi.python.org/pypi/python-daemon/. Thank you to those who have asked for more information about this library and how to contribute. The source code is available using the Bazaar distributed VCS URL:http://bazaar-vcs.org/ from the public repository at URL:http://bzr.debian.org/bzr/python-daemon/python-daemon.devel/, or browseable via a web interface URL:http://bzr.debian.org/loggerhead/python-daemon/python-daemon.devel/. Patches made via Bazaar against the public repository are most useful, but regular ‘patch(1)’ compatible patches are fine too. There isn't a better “project home page” than the PyPI page. Currently bug reports are best sent to me directly via email, or here on this forum. I suppose I really should put together a ‘HACKING’ document for all this information for potential hackers on the library :-) -- \ “If [a technology company] has confidence in their future | `\ ability to innovate, the importance they place on protecting | _o__) their past innovations really should decline.” —Gary Barnett | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Application-global switches?
On Sep 4, 9:29 pm, kj no.em...@please.post wrote: The only solution I can come up with is to define a dummy module, say _config.py, which contains only upper-case variables representing these global switches, and is imported by all the other modules in the application with the line from _config import *. During the early stages of the run, the script inspects the command-line flags, and if it finds a --continuing flag, it sets the variable _config.CONTINUATION_MODE to True. (The last point implies that these variables are not strictly speaking read-only, since they most be set at the beginning of the run. But after this initial setting, they should remain read-only.) Be very very careful about from _config import *. If you import a module that, in turn, imports _config this way, before you set the initial values, that module will already have made its own copies of all the variables and thus will not see the correct values. -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing Variables WITHOUT Dynamic URLs
Right. Bad example on my part. How about if I want to pass a cookie from page to page? Or some data called up from a database query? V On Wed, Sep 16, 2009 at 7:30 PM, Rami Chowdhury rami.chowdh...@gmail.comwrote: I like to pass at least browser information from page to page to make pages display properly. What kind of web framework are you using? Most allow you to access the HTTP headers sent with a request -- in this case, what you'd be after is the 'User-Agent' header. On Wed, 16 Sep 2009 16:21:41 -0700, Victor Subervi victorsube...@gmail.com wrote: Hi; Search engines don't like dynamic links. I like to pass at least browser information from page to page to make pages display properly. Spiders couldn't care less about asthetics, so that wouldn't matter to them. But passing something like *.com?browser=IE5 trips the spider up. Is there a way to pass this variable without that and without using a form for every page (which is not practical)? TIA, Victor -- Rami Chowdhury Never attribute to malice that which can be attributed to stupidity -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing Variables WITHOUT Dynamic URLs
Victor Subervi wrote: Right. Bad example on my part. How about if I want to pass a cookie from page to page? Or some data called up from a database query? Cookies are also passed in the header. Results from a database query are best left on the server rather than passing them back and forth between server and client. You should look into the concept called session variables. HTH, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
module metadata variables
Hi, many Python-modules contain metadata-variables, like __author__ etc. But most documentation-tools only support some of these variables, and some tools even define their own metadata-variables. So far, I found: - pydoc (- pydoc.py): __author__ __credits__ __date__ __version__ (additionally converting '$Revision: ...$' to '...') - epydoc (- http://epydoc.sourceforge.net/manual-fields.html): __author__ __authors__ __contact__ __copyright__ __date__ __deprecated__ __license__ __version__ - some modules also use: __revision__ So, my question is: Is there any generic definition of these variables? Otherwise it may be good to define a standard set of such metadata variables. And I think pydoc should be extended to at least support __copyright__ and __license__. I'll send a patch for this, except there is any reason against it. regards, Roland -- http://mail.python.org/mailman/listinfo/python-list
Re: unpacking vars from list of tuples
if you have numpy installed: ln[12]: import numpy as np In [13]: k = np.array([('a', 'bob', 'c'), ('p', 'joe', 'd'), ('x', 'mary', 'z')]) In [14]: k Out[14]: array([['a', 'bob', 'c'], ['p', 'joe', 'd'], ['x', 'mary', 'z']], dtype='|S4') In [15]: k[:,1] Out[15]: array(['bob', 'joe', 'mary'], dtype='|S4') -- http://mail.python.org/mailman/listinfo/python-list
Re: Looking for a pure Python chart drawing module
by your definitions, Python is just a wrapper around a C library. If none of the solutions work for you, roll your own. On Thu, Sep 17, 2009 at 11:38 AM, Giacomo Boffi giacomo.bo...@polimi.it wrote: John Nagle na...@animats.com writes: gerlos wrote: John Nagle ha scritto: I'm looking for something that can draw simple bar and pie charts in Python. I'm trying to find a Python package, not a wrapper for some C library, as this has to run on both Windows and Linux and version clashes are a problem. Did you look at matplotlib? In their examples page there are some charts like the ones you asked for. I guess it could work for you, and it seems to work flawlessy in MS Windows as in gnu/linux. That's a wrapper for Antigrain (http://www.antigrain.com/;), which is a C++ library. come on, you can configure matplotlib to use one of too many different backends from http://matplotlib.sourceforge.net/users/customizing.html CONFIGURATION BEGINS HERE # the default backend; one of GTK GTKAgg GTKCairo CocoaAgg FltkAgg # MacOSX QtAgg Qt4Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG Template # You can also deploy your own backend outside of matplotlib by # referring to the module name (which must be in the PYTHONPATH) as # 'module://my_backend' backend : GTKAgg -- Yes you who must leave everything that you cannot control. It begins with your family, but soon it comes around to your soul. Well I've been where you're hanging, I think I can see how you're pinned: When you're not feeling holy, your loneliness says that you've sinned. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing Variables WITHOUT Dynamic URLs
Session variables, yes. That is what I need. Thanks, V On Thu, Sep 17, 2009 at 11:46 AM, Carsten Haese carsten.ha...@gmail.comwrote: Victor Subervi wrote: Right. Bad example on my part. How about if I want to pass a cookie from page to page? Or some data called up from a database query? Cookies are also passed in the header. Results from a database query are best left on the server rather than passing them back and forth between server and client. You should look into the concept called session variables. HTH, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Are min() and max() thread-safe?
On Sep 17, 7:02 am, Carl Banks pavlovevide...@gmail.com wrote: On Sep 16, 9:33 pm, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: def minmax(seq): result = [None, None] t1 = MMThread(seq, min, result, 0) t2 = MMThread(seq, max, result, 1) t1.start() t2.start() # Block until all threads are done. while any([t1.isAlive(), t2.isAlive()]): time.sleep(0) Why not use t1.join(); t2.join() here? Is there any benefit to do it this way instead? Carl Banks The benefit is that SIGINT (Control-C) will be handled. Not sure why sleep(0) is used, though, rather than something less busy like sleep (0.5). -- http://mail.python.org/mailman/listinfo/python-list
WHIFF += Open Flash Charts
WHIFF (WSGI HTTP Integrated Filesystem Frames) 0.5 released. [ WHIFF += Open Flash Charts ] The new WHIFF 0.5 release linked from http://whiff.sourceforge.net includes built in support for Open Flash Charts -- see documentation at http://aaron.oirt.rutgers.edu/myapp/docs/W1100_1600.openFlashCharts Its pretty cool, if I do say so myself :). It also includes number of enhancements and bugfixes including a fairly important performance bugfix. What is Open Flash Charts? Open Flash Charts (http://teethgrinder.co.uk/open-flash-chart-2/ ) is an LPGL Flash implementation for a large number of attractive and dynamic graphical charts. These charts may be used to present numeric data on web pages in an attractive, accessible and forceful manner. Available chart types include line, bar, scatter, candle stick, and radar charts. What is WHIFF? WHIFF is a collection of support services for Python WSGI applications which allows applications to be composed by dropping dynamic pages into container directories. This mode of development will be familiar to developers who have created PHP applications, vanilla CGI scripts, Apache/modpy Publisher applications, JSP pages, or static web content. It is distributed under a BSD style open source license. The WHIFF implementation significantly generalizes the drop in paradigm to support WSGI middleware components and application fragments as well as stand-alone pages. WHIFF provides other services in addition to supporting drop in components, such as managed application resources. I created WHIFF to address complexity issues I encounter when creating and fixing sophisticated Web applications which include complex database interactions and dynamic features such as AJAX (Asynchronous Javascript And XML). Project home page: http://whiff.sourceforge.net . Documentation index: http://aaron.oirt.rutgers.edu/myapp/docs/W.intro . I hope you like it! -- Aaron Watters === an apple every 8 hours will keep 3 doctors away -- kliban -- http://mail.python.org/mailman/listinfo/python-list
explicit call to __init__(self) in subclass needed?
I create a class like this in Python-2.6 class Y(str): ... def __init__(self, s): ... pass ... y = Y('giraffe') y 'giraffe' How does the base class (str) get initialized with the value passed to Y.__init__() ? Is this behavior specific to the str type, or do base classes not need to be explicitly initialized? Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: socket.MSG_WAITALL flag broken on Windows XP in Python 2.5.4?
Wes McKinney wrote: I am running what is apparently a custom Python 2.5.4 (part of the Enthought Python Distribution) which should be identical to the one on python.org, but is not. I contacted Enthought about the issue-- it can be worked around in the Pyro configuration for the time being. Thanks a lot for the debugging help, Wes Alternatively you could 'fix' your python installation by editing the socket.py in your stdlib, so that it deletes the MSG_WAITALL symbol after importing it from the builtin _socket module. --irmen -- http://mail.python.org/mailman/listinfo/python-list
Re: str.split() with empty separator
On Tue, 15 Sep 2009 14:31:26 +0200, Ulrich Eckhardt wrote: Hi! 'abc'.split('') gives me a ValueError: empty separator. However, ''.join(['a', 'b', 'c']) gives me 'abc'. Why this asymmetry? The docs say If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ['1', '', '2']). Now suppose sep = ''. That means split() should return an infinitely long list of empty strings! Because if sep = '' then the string 'hello' starts with an empty string followed by sep followed by an empty string followed by sep followed by an empty string followed by sep... that's all before we get to the 'h'. I was under the impression that the two would be complementary. Uli -- http://mail.python.org/mailman/listinfo/python-list
Re: unpacking vars from list of tuples
Cool - Now that would be some seriously dense, efficient code! Will have to play with numpy sometime. R. On 17-Sep-09, at 12:25 PM, Chris Colbert wrote: if you have numpy installed: ln[12]: import numpy as np In [13]: k = np.array([('a', 'bob', 'c'), ('p', 'joe', 'd'), ('x', 'mary', 'z')]) In [14]: k Out[14]: array([['a', 'bob', 'c'], ['p', 'joe', 'd'], ['x', 'mary', 'z']], dtype='|S4') In [15]: k[:,1] Out[15]: array(['bob', 'joe', 'mary'], dtype='|S4') -- http://mail.python.org/mailman/listinfo/python-list
elif alternative
Can anybody show me a better looking alternative for this elif structure ? http://code.google.com/p/appwsgi/source/browse/appwsgi/wsgi/appointment.wsgi -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirect output on script
On Thu, Sep 17, 2009 at 3:58 AM, glenn.prin...@gmail.com glenn.prin...@gmail.com wrote: I would like to redirect the output of the command below to another file type test.txt test.bak I'm trying to do this as part of a python script running on Windows XP. I'm using os.system('type filepath.txt filepath.bak') but nothing is happening. I was wondering if somebody could enlighten me. Using the handy-dandy subprocess module: bak = file('filepath.bak', 'w') subprocess.call(['type', 'filepath.txt'], stdout=bak) Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: elif alternative
On Thu, Sep 17, 2009 at 12:38 PM, gert gert.cuyk...@gmail.com wrote: Can anybody show me a better looking alternative for this elif structure ? Use a dictionary with functions as values. For example: #untested obviously def admin_remove(db, v, gid): db.execute(DELETE FROM appointments WHERE aid=?,(v['aid'],)) def guest_remove(db, v, gid): db.execute(DELETE FROM appointments WHERE aid=? AND uid=?,(v['aid'],s.UID)) cmd_gid2func = {('remove', 'admin') : admin_remove, ('remove', 'guest') : guest_remove} func = cmd_gid2func[(v['cmd'], s.GID)] func(db, v, s.GID) Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: elif alternative
gert wrote: Can anybody show me a better looking alternative for this elif structure ? http://code.google.com/p/appwsgi/source/browse/appwsgi/wsgi/appointment.wsgi Where you have cascaded ifs based on a single value, one alternative is to use a dict where the test value is the key and functions are the values: def do_overview(): db.execute(SELECT calendar,appointment FROM appointments WHERE calendar = ? AND calendar ?,(v['from'],v['to'])) def do_find(): db.execute(SELECT users.name, appointments.* FROM users, appointments WHERE users.uid = appointments.uid AND appointments.calendar = ? AND appointments.appointment LIKE ? GROUP BY appointments.aid,(v['calendar'],%+v['appointment']+%)) ... actions = {'overview': do_overview, 'find': find, ...} actions[v['cmd']]() Your code does have an 'if' which breaks the pattern, but you might be able to work around it. -- http://mail.python.org/mailman/listinfo/python-list
Re: elif alternative
On Sep 17, 9:48 pm, Chris Rebert c...@rebertia.com wrote: On Thu, Sep 17, 2009 at 12:38 PM, gert gert.cuyk...@gmail.com wrote: Can anybody show me a better looking alternative for this elif structure ? Use a dictionary with functions as values. For example: #untested obviously def admin_remove(db, v, gid): db.execute(DELETE FROM appointments WHERE aid=?,(v['aid'],)) def guest_remove(db, v, gid): db.execute(DELETE FROM appointments WHERE aid=? AND uid=?,(v['aid'],s.UID)) cmd_gid2func = {('remove', 'admin') : admin_remove, ('remove', 'guest') : guest_remove} func = cmd_gid2func[(v['cmd'], s.GID)] func(db, v, s.GID) Actually I was hopping the answer would be no :) Need to change allot of lines again thanks to you -- http://mail.python.org/mailman/listinfo/python-list
Re: explicit call to __init__(self) in subclass needed?
Andrew MacKeith wrote: I create a class like this in Python-2.6 class Y(str): ... def __init__(self, s): ... pass ... y = Y('giraffe') y 'giraffe' How does the base class (str) get initialized with the value passed to Y.__init__() ? Is this behavior specific to the str type, or do base classes not need to be explicitly initialized? Andrew All the immutable base types (I *think*), use __new__ for object creation, not __init__. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: elif alternative
On Sep 17, 2:38 pm, gert gert.cuyk...@gmail.com wrote: Can anybody show me a better looking alternative for this elif structure ? http://code.google.com/p/appwsgi/source/browse/appwsgi/wsgi/appointme... For starters assign v['cmd'] to a variable instead of looking it up every time! cmd = v['cmd'] if cmd == ... elif cmd == ... ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Shebang line problems and python
On Sep 16, 9:25 pm, Blaine brlafreni...@gmail.com wrote: Hello, Scripts that have #!/usr/bin/python at the top do not parse correctly. Bash treats scripts with that shebang as if they are bash scripts. E.g.: bla...@attila ~/apps/rs-mu $ /usr/sbin/env-update /usr/sbin/env-update: line 6: import: command not found /usr/sbin/env-update: line 8: syntax error near unexpected token `(' /usr/sbin/env-update: line 8: `def usage(status):' Scripts with #!/usr/bin/env python at the top work fine. In fact, `python` and `env python` both bring me to a python interpreter. I've tried other types of scripts. #!/bin/bash works, #!/usr/bin/perl works, #!/usr/bin/ruby works, etc. (and so do their #!/usr/bin/env interpreter counterparts.) Because of this, I'm not sure if it is a Python issue or a system issue. Any and all advice appreciated, thanks. P.S. some system info: bla...@attila ~/apps/rs-mu $ uname -a Linux attila 2.6.27-gentoo #5 SMP Sun Oct 19 19:13:17 MST 2008 i686 AMD Athlon(tm) 64 X2 Dual Core Processor 4000+ AuthenticAMD GNU/Linux bla...@attila ~/apps/rs-mu $ python --version Python 2.6.2 bla...@attila ~/apps/rs-mu $ bash --version GNU bash, version 4.0.28(2)-release (i686-pc-linux-gnu) Copyright (C) 2009 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later http://gnu.org/licenses/ gpl.html Okay, in case anyone is curious, here is how I fixed the problem: downgraded app-admin/eselect-python-20090801 to app-admin/eselect- python-20090606 `rm /usr/bin/python/` `ln -s -T /usr/bin/python2.6 /usr/bin/python` `emerge python` -- http://mail.python.org/mailman/listinfo/python-list
OpenAnything
In Dive Into Python, Mark Pilgrim offers the function openAnything that can open for reading anything (i.e. local files or URLs). I was wondering if there was already in the standard Python library an official version of this, that could not only open (for reading) regular files and URLs, but also other data sources such as compressed files. TIA! kynn -- http://mail.python.org/mailman/listinfo/python-list
Re: OpenAnything
Read this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/445ffc93b0e6a460 and you will likely get the idea. -- http://mail.python.org/mailman/listinfo/python-list
Re: elif alternative
On Sep 17, 9:48 pm, Chris Rebert c...@rebertia.com wrote: On Thu, Sep 17, 2009 at 12:38 PM, gert gert.cuyk...@gmail.com wrote: Can anybody show me a better looking alternative for this elif structure ? Use a dictionary with functions as values. For example: #untested obviously def admin_remove(db, v, gid): db.execute(DELETE FROM appointments WHERE aid=?,(v['aid'],)) def guest_remove(db, v, gid): db.execute(DELETE FROM appointments WHERE aid=? AND uid=?,(v['aid'],s.UID)) cmd_gid2func = {('remove', 'admin') : admin_remove, ('remove', 'guest') : guest_remove} func = cmd_gid2func[(v['cmd'], s.GID)] func(db, v, s.GID) What about s.UID ? -- http://mail.python.org/mailman/listinfo/python-list
Re: OpenAnything
On 17 Sep, 23:24, kj no.em...@please.post wrote: In Dive Into Python, Mark Pilgrim offers the function openAnything that can open for reading anything (i.e. local files or URLs). I was wondering if there was already in the standard Python library an official version of this, that could not only open (for reading) regular files and URLs, but also other data sources such as compressed files. Not in the standard library, but available from the package index: http://pypi.python.org/pypi/desktop The desktop.open function just wraps other mechanisms for opening/ launching files or URLs. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: elif alternative
On Sep 18, 12:09 am, gert gert.cuyk...@gmail.com wrote: On Sep 17, 9:48 pm, Chris Rebert c...@rebertia.com wrote: On Thu, Sep 17, 2009 at 12:38 PM, gert gert.cuyk...@gmail.com wrote: Can anybody show me a better looking alternative for this elif structure ? Use a dictionary with functions as values. For example: #untested obviously def admin_remove(db, v, gid): db.execute(DELETE FROM appointments WHERE aid=?,(v['aid'],)) def guest_remove(db, v, gid): db.execute(DELETE FROM appointments WHERE aid=? AND uid=?,(v['aid'],s.UID)) cmd_gid2func = {('remove', 'admin') : admin_remove, ('remove', 'guest') : guest_remove} func = cmd_gid2func[(v['cmd'], s.GID)] func(db, v, s.GID) What about s.UID ? Never mind :) func(db, v, s.GID, s.UID) -- http://mail.python.org/mailman/listinfo/python-list
Re: elif alternative
On Thu, Sep 17, 2009 at 3:09 PM, gert gert.cuyk...@gmail.com wrote: On Sep 17, 9:48 pm, Chris Rebert c...@rebertia.com wrote: On Thu, Sep 17, 2009 at 12:38 PM, gert gert.cuyk...@gmail.com wrote: Can anybody show me a better looking alternative for this elif structure ? Use a dictionary with functions as values. For example: #untested obviously def admin_remove(db, v, gid): db.execute(DELETE FROM appointments WHERE aid=?,(v['aid'],)) def guest_remove(db, v, gid): db.execute(DELETE FROM appointments WHERE aid=? AND uid=?,(v['aid'],s.UID)) cmd_gid2func = {('remove', 'admin') : admin_remove, ('remove', 'guest') : guest_remove} func = cmd_gid2func[(v['cmd'], s.GID)] func(db, v, s.GID) What about s.UID ? I only covered a couple cases since this was just to give you an example of the approach. You'll need to adjust the parameters the functions take and the elements in the key tuples of the dictionary to account for your full body of code. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: elif alternative
On Sep 18, 12:12 am, gert gert.cuyk...@gmail.com wrote: On Sep 18, 12:09 am, gert gert.cuyk...@gmail.com wrote: On Sep 17, 9:48 pm, Chris Rebert c...@rebertia.com wrote: On Thu, Sep 17, 2009 at 12:38 PM, gert gert.cuyk...@gmail.com wrote: Can anybody show me a better looking alternative for this elif structure ? Use a dictionary with functions as values. For example: #untested obviously def admin_remove(db, v, gid): db.execute(DELETE FROM appointments WHERE aid=?,(v['aid'],)) def guest_remove(db, v, gid): db.execute(DELETE FROM appointments WHERE aid=? AND uid=?,(v['aid'],s.UID)) cmd_gid2func = {('remove', 'admin') : admin_remove, ('remove', 'guest') : guest_remove} func = cmd_gid2func[(v['cmd'], s.GID)] func(db, v, s.GID) What about s.UID ? Never mind :) func(db, v, s.GID, s.UID) [(v['cmd'], s.GID)] Can s.GID be None ? -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLite or files?
TerryP bigboss1...@gmail.com wrote: Yeah, I'm sure that is the same kind of thinking that caused 16-bit MS- DOS applications to remain a part of Windows NT so long. So what part of the standard library do you recommend using instead? Or was there no time for advice between snarkiness? -- http://mail.python.org/mailman/listinfo/python-list
Re: class initialization problem
On Sep 17, 11:14 pm, alex23 wuwe...@gmail.com wrote: On Sep 18, 1:27 pm, rantingrick rantingr...@gmail.com wrote: ok i have a class and in it's constructor i want to create a copy of it as an attribute, i have tried super, __new__, and noting seems to work, please help! class A(base): def __init__(self): super(A, self).__init__() self.nested = ? think of a nested list [ [] ] but with object A as the toplevel list and having an instance of A in the attribute nested Sorry, do you want an a copy of the instance or of the class? If you mean the class, self.nested = self.__class__ If you mean the instance, self.nested = self No i want an *actual* separate instance inside the current instance bound to an attribute nested. But the problem is how to do this in the constructor without causing infinite recursion. I thought about creating an object copy function which would initialize the object and *then* return it to the constructor but that seemed kind of kludgy. There must be some syntax for doing this? -- http://mail.python.org/mailman/listinfo/python-list
Re: class initialization problem
On Sep 17, 8:27 pm, rantingrick rantingr...@gmail.com wrote: ok i have a class and in it's constructor i want to create a copy of it as an attribute, i have tried super, __new__, and noting seems to work, please help! class A(base): def __init__(self): super(A, self).__init__() self.nested = ? think of a nested list [ [] ] but with object A as the toplevel list and having an instance of A in the attribute nested Well, to answer the question you asked (i have a class and in it's constructor i want to create a copy of it as an attribute): import copy self.nested = copy.copy(self) However, your post contains some conflicting information, copy often means different things to different people, it is ambiguous, and what you ask for seems to to be well-conceived. I think we will be able to help you more if you give more details about what you expect and how you intend to use this nested object. Please try to observe the distiction between classes and instances (you almost certainly wanted a copy of the instance, not of the class). Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: SQLite or files?
In article mailman.30.1253183180.2807.python-l...@python.org, Tim Chase python.l...@tim.thechases.com wrote: - I don't know if you're currently keeping the RTF in memory the whole time, or if you repeatedly reload (whether in one go, or streaming it) and reparse the file. This sounds memory and/or processor intensive. Using sqlite, the processing is done at the C-module level, the data is kept on disk and only brought into memory as-requested, being released when you're done with it. You can also make a SQLite database be in-memory, giving you the performance benefits of skipping the disk. -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ I won't accept a model of the universe in which free will, omniscient gods, and atheism are simultaneously true. --M -- http://mail.python.org/mailman/listinfo/python-list
Re: class initialization problem
On Sep 17, 11:54 pm, Carl Banks pavlovevide...@gmail.com wrote: On Sep 17, 8:27 pm, rantingrick rantingr...@gmail.com wrote: ok i have a class and in it's constructor i want to create a copy of it as an attribute, i have tried super, __new__, and noting seems to work, please help! class A(base): def __init__(self): super(A, self).__init__() self.nested = ? think of a nested list [ [] ] but with object A as the toplevel list and having an instance of A in the attribute nested Well, to answer the question you asked (i have a class and in it's constructor i want to create a copy of it as an attribute): import copy self.nested = copy.copy(self) However, your post contains some conflicting information, copy often means different things to different people, it is ambiguous, and what you ask for seems to to be well-conceived. I think we will be able to help you more if you give more details about what you expect and how you intend to use this nested object. Please try to observe the distiction between classes and instances (you almost certainly wanted a copy of the instance, not of the class). Carl Banks ok here is some code. this will cause an infinite recursion. class A(): def __init__(self, *args): self.nestedA = A(*args) #NO GOOD! there must be a way to create an instance of an object within the same objects constructor? TIA -- http://mail.python.org/mailman/listinfo/python-list
Re: An assessment of the Unicode standard
On Sep 18, 2:39 pm, Dennis Lee Bieber wlfr...@ix.netcom.com wrote: Granted, a proper version would use a class where the two Venus objects have a different description... I think I'd be more inclined to model Venus and treat the others as views :) -- http://mail.python.org/mailman/listinfo/python-list
Re: class initialization problem
On Sep 18, 3:08 pm, rantingrick rantingr...@gmail.com wrote: ok here is some code. this will cause an infinite recursion. class A(): def __init__(self, *args): self.nestedA = A(*args) #NO GOOD! there must be a way to create an instance of an object within the same objects constructor? But if _every_ instance of A has a 'nested' instance of A, won't it _always_ end up smacking up against the recursive depth limit? It's beginning to sound like you need to separate the creation out to a factory function. And to rethink your design, maybe. -- http://mail.python.org/mailman/listinfo/python-list
Re: class initialization problem
rantingrick wrote: ok here is some code. this will cause an infinite recursion. class A(): def __init__(self, *args): self.nestedA = A(*args) #NO GOOD! there must be a way to create an instance of an object within the same objects constructor? This is an inherent problem with what you want to do, not a problem with Python. You have said you want each instance of A to have a nested instance. But then the nested instance is an instance of A too, so it should have a nested instance, and that doubly-nested instance should have its own nested instance, and so on to infinity. Perhaps you want to cut off the recursion at the first step, so that the nested instance itself does not have a nested instance. If so, add another parameter to __init__ that flags whether you are creating a top-level instance. -- --OKB (not okblacke) Brendan Barnwell Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail. --author unknown -- http://mail.python.org/mailman/listinfo/python-list
Re: class initialization problem
!SOLVED! Thanks for the help guys! copy.copy did it! Why does me makes life so hard on me? ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: class initialization problem
On Sep 18, 12:24 am, OKB (not okblacke) brennospamb...@nobrenspambarn.net wrote: Perhaps you want to cut off the recursion at the first step, so that the nested instance itself does not have a nested instance. If so, add another parameter to __init__ that flags whether you are creating a top-level instance. yes, i also figured that out just a few minutes ago. class A(): def __init__(self, nested=True) if nested: self.var = A(nested=False) I think i have been staring at code too long and my noodle just shutdown for the evening :) Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: class initialization problem
On Sep 18, 3:08 pm, rantingrick rantingr...@gmail.com wrote: ok here is some code. this will cause an infinite recursion. class A(): def __init__(self, *args): self.nestedA = A(*args) #NO GOOD! How about: class A(object): def __init__(self, first=True, *args): if first: self.nestedA = A(first=False, *args) That's about the only way I can see you easily avoiding the recursiveness. -- http://mail.python.org/mailman/listinfo/python-list
Re: class initialization problem
On Sep 18, 3:31 pm, alex23 wuwe...@gmail.com wrote: On Sep 18, 3:08 pm, rantingrick rantingr...@gmail.com wrote: ok here is some code. this will cause an infinite recursion. class A(): def __init__(self, *args): self.nestedA = A(*args) #NO GOOD! How about: class A(object): def __init__(self, first=True, *args): if first: self.nestedA = A(first=False, *args) That's about the only way I can see you easily avoiding the recursiveness. Only, y'know, with the right indentation: class A(object): def __init__(self, first=True, *args): if first: self.nestedA = A(first=False, *args) -- http://mail.python.org/mailman/listinfo/python-list
Re: class initialization problem
On Sep 17, 10:08 pm, rantingrick rantingr...@gmail.com wrote: On Sep 17, 11:54 pm, Carl Banks pavlovevide...@gmail.com wrote: On Sep 17, 8:27 pm, rantingrick rantingr...@gmail.com wrote: ok i have a class and in it's constructor i want to create a copy of it as an attribute, i have tried super, __new__, and noting seems to work, please help! class A(base): def __init__(self): super(A, self).__init__() self.nested = ? think of a nested list [ [] ] but with object A as the toplevel list and having an instance of A in the attribute nested Well, to answer the question you asked (i have a class and in it's constructor i want to create a copy of it as an attribute): import copy self.nested = copy.copy(self) However, your post contains some conflicting information, copy often means different things to different people, it is ambiguous, and what you ask for seems to to be well-conceived. I think we will be able to help you more if you give more details about what you expect and how you intend to use this nested object. Please try to observe the distiction between classes and instances (you almost certainly wanted a copy of the instance, not of the class). Carl Banks ok here is some code. this will cause an infinite recursion. class A(): def __init__(self, *args): self.nestedA = A(*args) #NO GOOD! there must be a way to create an instance of an object within the same objects constructor? Here's something to ponder: If you have two objects, one of which has an attribute that contains certain nested object, one which doesn't, should those objects be instances of the same class? You may come to a different conclusion, but it seems to me they ought to be different classes. They have a significant difference in their behavior. class Inner(base): def __init__(self,*args): super(self,Inner).__init__(*args) class Outer(Inner): def __init__(self,*args): super(self,Outer).__init__(*args) self.nested = Inner(*args) If you insist on them being the same class, you could use copy.copy() as I did earlier, although it won't always work for every class. Or just pass a parameter to the class indicating whether it should create a nested copy of itself, defaulting to True. When creating the nested class it should be set to False. (Note: because keyword-only arguments aren't in Python 2.5 I capture _create_nested in kwargs. You may find it more convenient to use a keyword argument.) class A(base): def __init__(self,*args,**kwargs): _create_nested = kwargs.pop('_create_nested',True) super(A,self).__init__(*args,**kwargs) if _create_nested: self.nested = A(_create_nested=False,*args) Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
[issue6300] encode and decode should accept 'errors' as a keyword argument
Jeff Bradberry jeff.bradbe...@gmail.com added the comment: As it turns out, someone had previously made this adjustment to str() and unicode(). My updated patch adds this behavior to unicode.decode and unicode.encode, adds a couple of tests to test_unicode.py, and updates the documentation to show that these functions (and str.format, which had failed to be noted as taking them) now take keyword arguments. -- Added file: http://bugs.python.org/file14906/python27.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6300 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6912] Add 'with' block support to Tools/Scripts/pindent.py
Georg Brandl ge...@python.org added the comment: Added in r74865. -- nosy: +georg.brandl resolution: - fixed status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6912 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6915] os.listdir inconsistenly releases the GIL on win32
Changes by Georg Brandl ge...@python.org: -- assignee: - loewis nosy: +loewis ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6915 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6300] encode and decode should accept 'errors' as a keyword argument
Marc-Andre Lemburg m...@egenix.com added the comment: The patch looks fine, the idea is good as well. I'm just a little worried about the performance impact this might have (not much though). Could you run a quick comparison of before applying the patch compared to after the patch is applied, using positional arguments in both cases ? Thanks. -- nosy: +lemburg ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6300 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6508] expose setresuid
Martin v. Löwis mar...@v.loewis.de added the comment: Please do try this out on your system. Installing autoconf locally is really not difficult: download 2.61, then do ./configure --prefix=$HOME/ac261 make make install This will give you $HOME/ac261/bin/auto{conf|header}; automake is not needed for Python. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6508 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6508] expose setresuid
Martin v. Löwis mar...@v.loewis.de added the comment: Your patch looks right, although I have a few style issues: - the if chaining looks complicated: we don't usually have an else when the if returns - make sure you use tabs consistently with the rest of the file - it may be better to use uid_t where appropriate, see issue6873 -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6508 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6919] Link CRT Statically
Amaury Forgeot d'Arc amaur...@gmail.com added the comment: It will seem to work for simple scripts, but many extension modules won't behave properly because: - some API functions (PyFile_AsFile, many PyRun_*functions, PyMarshal_*+FromFile) pass FILE* structures, which differ between instances of the CRT. - file descriptors, environment variables, locale settings, the errno variable, are not shared. - when a thread exits, it would have to free thread-local storage for each CRT. Python uses Ansi C, and has to use the same system as the extension modules it wants to support. Linking statically with the CRT may be a solution in specific cases, but not for the general python distribution. -- nosy: +amaury.forgeotdarc ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6919 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6877] enable compilation of readline module on Mac OS X 10.5 and 10.6
Mark Dickinson dicki...@gmail.com added the comment: Do the remove_history_item and replace_history_item functions also need the off-by-one adjustment? -- nosy: +marketdickinson ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6877 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1613573] xmlrpclib ServerProxy uses old httplib interface
anatoly techtonik techto...@gmail.com added the comment: This bug may be fixed. Unfortunately I do not possess original setup anymore. The primary issue is still issue648658 and that affects bzr + launchpad integration, XML-RPC access to bugzilla and probably more. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue1613573 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1613573] xmlrpclib ServerProxy uses old httplib interface
anatoly techtonik techto...@gmail.com added the comment: And I want to add that I am glad that is finally fixed, so I really appreciate the work people done in this direction in their free time. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue1613573 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6877] enable compilation of readline module on Mac OS X 10.5 and 10.6
Ronald Oussoren ronaldousso...@mac.com added the comment: Mark: yes those functions need to be changed as well. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6877 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com