title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Recommendations for Python development on a Mac?
601,236
<p>I bought a low-end MacBook about a month ago and am finally getting around to configuring it for Python. I've done most of my Python work in Windows up until now, and am finding the choices for OS X a little daunting. It looks like there are at least five options to use for Python development:</p> <ul> <li>"Stock" Apple Python</li> <li>MacPython</li> <li>Fink</li> <li>MacPorts</li> <li>roll-your-own-from-source</li> </ul> <p>I'm still primarily developing for 2.5, so the stock Python is fine from a functionality standpoint. What I want to know is: why should I choose one over the other?</p> <p><strong>Update:</strong> To clarify, I am looking for a discussion of the various options, not links to the documentation. I've marked this as a Community Wiki question, as I don't feel there is a "correct" answer. Thanks to everyone who has already commented for their insight.</p>
8
2009-03-02T04:04:06Z
601,287
<p>I recommend python (any python?) plus the ipython shell. My most recent experience with MacPython was MacPython 2.5, and I found IDLE frustrating to use as an editor. It's not very featureful, and its' very slow to scroll large quantities of output.</p>
0
2009-03-02T04:37:03Z
[ "python", "osx" ]
Recommendations for Python development on a Mac?
601,236
<p>I bought a low-end MacBook about a month ago and am finally getting around to configuring it for Python. I've done most of my Python work in Windows up until now, and am finding the choices for OS X a little daunting. It looks like there are at least five options to use for Python development:</p> <ul> <li>"Stock" Apple Python</li> <li>MacPython</li> <li>Fink</li> <li>MacPorts</li> <li>roll-your-own-from-source</li> </ul> <p>I'm still primarily developing for 2.5, so the stock Python is fine from a functionality standpoint. What I want to know is: why should I choose one over the other?</p> <p><strong>Update:</strong> To clarify, I am looking for a discussion of the various options, not links to the documentation. I've marked this as a Community Wiki question, as I don't feel there is a "correct" answer. Thanks to everyone who has already commented for their insight.</p>
8
2009-03-02T04:04:06Z
601,844
<p>Depends what you are using python for. If you are using MacOS funitionality and things like PyObjC you are probably best of with MacPython or the python provided by Apple. </p> <p>I use Python on my Mac mostly for development of server side applications which later will run on FreeBSD &amp; Linux boxes. For that I have used fink python for a few years and ever since MacPorts python. With mac ports it is simple to add required c modules (like database driver etc). It's also easy to keep two python Versions (2.5 &amp; 2.6 in my case) around.</p> <p>I used "compile your own" python to test pre-3.0 python but generally I find managing dependencies to c modules painfull if done by hand.</p> <p>Thanks to easy_install installing pure python modules is fast and easy for all the options mentioned above.</p> <p>I was never very much an IDE person. For development I use command line subversion installed by MacPorts, <a href="http://macromates.com/" rel="nofollow">Textmate</a> and occasionaly <a href="http://www.expandrive.com/mac" rel="nofollow">Expandrive</a> do directly access files on servers. I personally are very dependent on <a href="http://blogs.23.nu/c0re/2007/08/antville-15779/" rel="nofollow">Bicyclerepairman for Textmade</a> to handle my refactoring needs.</p> <p>Others seem to be very happy with <a href="http://pydev.sourceforge.net/" rel="nofollow">Eclipse &amp; Pydev</a>.</p>
3
2009-03-02T10:10:18Z
[ "python", "osx" ]
Recommendations for Python development on a Mac?
601,236
<p>I bought a low-end MacBook about a month ago and am finally getting around to configuring it for Python. I've done most of my Python work in Windows up until now, and am finding the choices for OS X a little daunting. It looks like there are at least five options to use for Python development:</p> <ul> <li>"Stock" Apple Python</li> <li>MacPython</li> <li>Fink</li> <li>MacPorts</li> <li>roll-your-own-from-source</li> </ul> <p>I'm still primarily developing for 2.5, so the stock Python is fine from a functionality standpoint. What I want to know is: why should I choose one over the other?</p> <p><strong>Update:</strong> To clarify, I am looking for a discussion of the various options, not links to the documentation. I've marked this as a Community Wiki question, as I don't feel there is a "correct" answer. Thanks to everyone who has already commented for their insight.</p>
8
2009-03-02T04:04:06Z
602,013
<p>I would highly recommend using <a href="http://www.macports.org/" rel="nofollow">MacPorts</a> with <a href="http://porticus.alittledrop.com/" rel="nofollow">Porticus</a> for managing your Python installation. It takes a while to build everything, but the advantage is that whatever you build yourself will be built against the same libraries, so you won't have to futz around with statically linked shared objects, etc. if you want your Python stuff to work with Apache, PostgreSQL, etc.</p> <p>If you choose to go this way, remember to install the <code>python_select</code> port and use it to make your system use the Python installed from MacPorts.</p> <p>As an added bonus, MacPorts has packages for most main-stream Python eggs, so if you should be able to have MacPorts keep you up-to-date with the latest versions of all that stuff :)</p>
4
2009-03-02T11:38:41Z
[ "python", "osx" ]
Recommendations for Python development on a Mac?
601,236
<p>I bought a low-end MacBook about a month ago and am finally getting around to configuring it for Python. I've done most of my Python work in Windows up until now, and am finding the choices for OS X a little daunting. It looks like there are at least five options to use for Python development:</p> <ul> <li>"Stock" Apple Python</li> <li>MacPython</li> <li>Fink</li> <li>MacPorts</li> <li>roll-your-own-from-source</li> </ul> <p>I'm still primarily developing for 2.5, so the stock Python is fine from a functionality standpoint. What I want to know is: why should I choose one over the other?</p> <p><strong>Update:</strong> To clarify, I am looking for a discussion of the various options, not links to the documentation. I've marked this as a Community Wiki question, as I don't feel there is a "correct" answer. Thanks to everyone who has already commented for their insight.</p>
8
2009-03-02T04:04:06Z
602,025
<p>In my windows environment I use Eclipse and PyDev, which works quite well together, even if it's a bit sparse. Apparently the exact same environment is available for the Mac as well, so I suggest downloading <a href="http://www.eclipse.org" rel="nofollow">Eclipse</a> and using the internal update software function to update PyDev with the URL <a href="http://pydev.sourceforge.net/updates/" rel="nofollow">http://pydev.sourceforge.net/updates/</a>. To look further into PyDev, look <a href="http://pydev.sourceforge.net" rel="nofollow">here</a>.</p>
1
2009-03-02T11:44:02Z
[ "python", "osx" ]
Recommendations for Python development on a Mac?
601,236
<p>I bought a low-end MacBook about a month ago and am finally getting around to configuring it for Python. I've done most of my Python work in Windows up until now, and am finding the choices for OS X a little daunting. It looks like there are at least five options to use for Python development:</p> <ul> <li>"Stock" Apple Python</li> <li>MacPython</li> <li>Fink</li> <li>MacPorts</li> <li>roll-your-own-from-source</li> </ul> <p>I'm still primarily developing for 2.5, so the stock Python is fine from a functionality standpoint. What I want to know is: why should I choose one over the other?</p> <p><strong>Update:</strong> To clarify, I am looking for a discussion of the various options, not links to the documentation. I've marked this as a Community Wiki question, as I don't feel there is a "correct" answer. Thanks to everyone who has already commented for their insight.</p>
8
2009-03-02T04:04:06Z
604,338
<p>Apple's supplied python is quite old – my tiger install has 2.3.5. This may not be a problem for you, but you would be missing out on a lot. Also, there is a risk that Apple will update it. I'm not sure if moving from 2.3.5 to (say) 2.4 would cause code to break, but I guess it's possible. This happened to perl people recently: <a href="http://developers.slashdot.org/article.pl?sid=09/02/18/1435227&amp;from=rss" rel="nofollow">http://developers.slashdot.org/article.pl?sid=09/02/18/1435227</a></p> <p>Macpython is a framework build (as is Apple's, I believe). To be honest, I'm not sure exactly what that means, but it's a prerequisite for some modules, in particular wxPython. If you get python from macports or fink, you will not be able to run wxPython (unless you run it through X11).</p>
1
2009-03-02T22:32:54Z
[ "python", "osx" ]
Recommendations for Python development on a Mac?
601,236
<p>I bought a low-end MacBook about a month ago and am finally getting around to configuring it for Python. I've done most of my Python work in Windows up until now, and am finding the choices for OS X a little daunting. It looks like there are at least five options to use for Python development:</p> <ul> <li>"Stock" Apple Python</li> <li>MacPython</li> <li>Fink</li> <li>MacPorts</li> <li>roll-your-own-from-source</li> </ul> <p>I'm still primarily developing for 2.5, so the stock Python is fine from a functionality standpoint. What I want to know is: why should I choose one over the other?</p> <p><strong>Update:</strong> To clarify, I am looking for a discussion of the various options, not links to the documentation. I've marked this as a Community Wiki question, as I don't feel there is a "correct" answer. Thanks to everyone who has already commented for their insight.</p>
8
2009-03-02T04:04:06Z
613,677
<p>Based on the number of bugs and omissions people have been encountering in Leopard python (<em>just here on SO</em>!), I couldn't recommend that version. e.g., see:</p> <ul> <li><a href="http://stackoverflow.com/questions/613111/different-results-for-hmac-in-python-and-perl">http://stackoverflow.com/questions/613111/different-results-for-hmac-in-python-and-perl</a></li> <li><a href="http://stackoverflow.com/questions/584575/problems-on-select-module-on-python-2-5">http://stackoverflow.com/questions/584575/problems-on-select-module-on-python-2-5</a></li> </ul> <p>I would choose <strong>MacPorts</strong>. </p> <p>It does not eliminate your existing python supplied by Apple since it installs by default in <code>/opt/local/bin</code> (plays nice with it) and plus it is easy to download and install additional python modules (even binary modules that you need to compile!). I use <a href="http://porticus.alittledrop.com/" rel="nofollow">Porticus</a> GUI to maintain my MacPorts installed list of packages, including python. </p>
2
2009-03-05T05:37:09Z
[ "python", "osx" ]
Recommendations for Python development on a Mac?
601,236
<p>I bought a low-end MacBook about a month ago and am finally getting around to configuring it for Python. I've done most of my Python work in Windows up until now, and am finding the choices for OS X a little daunting. It looks like there are at least five options to use for Python development:</p> <ul> <li>"Stock" Apple Python</li> <li>MacPython</li> <li>Fink</li> <li>MacPorts</li> <li>roll-your-own-from-source</li> </ul> <p>I'm still primarily developing for 2.5, so the stock Python is fine from a functionality standpoint. What I want to know is: why should I choose one over the other?</p> <p><strong>Update:</strong> To clarify, I am looking for a discussion of the various options, not links to the documentation. I've marked this as a Community Wiki question, as I don't feel there is a "correct" answer. Thanks to everyone who has already commented for their insight.</p>
8
2009-03-02T04:04:06Z
618,078
<p>How about EPD from Enthought? Yes, it's large but it is a framework build and includes things like wxPython, vtk, numpy, scipy, and ipython built-in.</p>
3
2009-03-06T08:39:57Z
[ "python", "osx" ]
Recommendations for Python development on a Mac?
601,236
<p>I bought a low-end MacBook about a month ago and am finally getting around to configuring it for Python. I've done most of my Python work in Windows up until now, and am finding the choices for OS X a little daunting. It looks like there are at least five options to use for Python development:</p> <ul> <li>"Stock" Apple Python</li> <li>MacPython</li> <li>Fink</li> <li>MacPorts</li> <li>roll-your-own-from-source</li> </ul> <p>I'm still primarily developing for 2.5, so the stock Python is fine from a functionality standpoint. What I want to know is: why should I choose one over the other?</p> <p><strong>Update:</strong> To clarify, I am looking for a discussion of the various options, not links to the documentation. I've marked this as a Community Wiki question, as I don't feel there is a "correct" answer. Thanks to everyone who has already commented for their insight.</p>
8
2009-03-02T04:04:06Z
5,541,640
<p>And guess what was forgotten by every answer here ... <a href="http://code.activestate.com/pypm/psyco/" rel="nofollow"><strong>ActivePython</strong></a>.</p> <p>No compilation required, even for third-party modules such as <a href="http://code.activestate.com/pypm/numpy/" rel="nofollow">numpy</a>, <a href="http://code.activestate.com/pypm/lxml/" rel="nofollow">lxml</a>, <a href="http://code.activestate.com/pypm/pyqt4/" rel="nofollow">pyqt</a> and <a href="http://code.activestate.com/pypm/" rel="nofollow">thousands of others</a>.</p> <p><img src="http://i.stack.imgur.com/r9rF8.png" alt="ActivePython Community Edition logo"></p>
1
2011-04-04T16:45:14Z
[ "python", "osx" ]
Should I use GeoDjango for mapping a floor plan?
601,442
<p>I want to create a floor plan map of an interior space that has clickable regions. My first thought was to investigate GeoDjango since its <em>the</em> mapping app for Django. But considering the dependencies, the learning curve and overall complexity, I'm concerned that I may be trying to swat a fly with a bazooka.</p> <p>Should I use GeoDjango for this, or should I just store integer lists in a database field?</p> <p><strong>EDIT:</strong> The floor plan would be fairly simple; a collection of walls and workstations with the ability to define regions for how much space the workstation occupies, thus allowing offices to be defined as well as open plan layouts.</p>
6
2009-03-02T06:34:21Z
612,487
<p>IMHO using GeoDjango for a floor plan isn't a bad idea. But if your data does not change much and the amount of data (rooms, areas, workstation, ...) isn't very large, then you might not need a database and a full GeoDjango stack.</p> <p>A simpler solution would be using <a href="http://www.openlayers.org" rel="nofollow">OpenLayers</a> directly with an image of the a (maybe scanned) floor plan as background layer. OpenLayers lets you also define region and points (markers) which handle "mouse over" or click events. </p> <p>An example of using OpenLayers for a floor plan is <a href="http://www.laudontech.com/openlayers/openlayersv1.php5" rel="nofollow">Office Plans via Open Layers</a>.</p>
3
2009-03-04T21:23:00Z
[ "python", "django", "mapping", "geodjango" ]
Should I use GeoDjango for mapping a floor plan?
601,442
<p>I want to create a floor plan map of an interior space that has clickable regions. My first thought was to investigate GeoDjango since its <em>the</em> mapping app for Django. But considering the dependencies, the learning curve and overall complexity, I'm concerned that I may be trying to swat a fly with a bazooka.</p> <p>Should I use GeoDjango for this, or should I just store integer lists in a database field?</p> <p><strong>EDIT:</strong> The floor plan would be fairly simple; a collection of walls and workstations with the ability to define regions for how much space the workstation occupies, thus allowing offices to be defined as well as open plan layouts.</p>
6
2009-03-02T06:34:21Z
613,955
<p>I'd say that using GeoDjango for this purpose is definitely overkill. </p> <p>It could be implemented simply with an image map, or Canvas/SVG or Flash for extra pretty-points :)</p>
4
2009-03-05T08:20:04Z
[ "python", "django", "mapping", "geodjango" ]
Should I use GeoDjango for mapping a floor plan?
601,442
<p>I want to create a floor plan map of an interior space that has clickable regions. My first thought was to investigate GeoDjango since its <em>the</em> mapping app for Django. But considering the dependencies, the learning curve and overall complexity, I'm concerned that I may be trying to swat a fly with a bazooka.</p> <p>Should I use GeoDjango for this, or should I just store integer lists in a database field?</p> <p><strong>EDIT:</strong> The floor plan would be fairly simple; a collection of walls and workstations with the ability to define regions for how much space the workstation occupies, thus allowing offices to be defined as well as open plan layouts.</p>
6
2009-03-02T06:34:21Z
614,489
<p>How often will the floor plan change? From your description a simple image with a imagemap would suffice.</p>
1
2009-03-05T12:02:39Z
[ "python", "django", "mapping", "geodjango" ]
Should I use GeoDjango for mapping a floor plan?
601,442
<p>I want to create a floor plan map of an interior space that has clickable regions. My first thought was to investigate GeoDjango since its <em>the</em> mapping app for Django. But considering the dependencies, the learning curve and overall complexity, I'm concerned that I may be trying to swat a fly with a bazooka.</p> <p>Should I use GeoDjango for this, or should I just store integer lists in a database field?</p> <p><strong>EDIT:</strong> The floor plan would be fairly simple; a collection of walls and workstations with the ability to define regions for how much space the workstation occupies, thus allowing offices to be defined as well as open plan layouts.</p>
6
2009-03-02T06:34:21Z
29,847,935
<p>One good motivation for using of GeoDjango may be:</p> <pre><code>the access to the geographical cooridinates backend, </code></pre> <p>and you won't produce just beauty looking images with arbitrary scale, but objects which will be <strong><code>geo-oriented</code></strong>, what is cruciall if you will plane to use the created plan for purpose of <strong><code>indoor navigation</code></strong>. </p> <p>I will consider strongly usage of GeoDjango, and some OpenLayers with support for GeoJSON.</p>
0
2015-04-24T12:47:46Z
[ "python", "django", "mapping", "geodjango" ]
Best way to create a NumPy array from a dictionary?
601,477
<p>I'm just starting with NumPy so I may be missing some core concepts...</p> <p>What's the best way to create a NumPy array from a dictionary whose values are lists?</p> <p>Something like this:</p> <pre><code>d = { 1: [10,20,30] , 2: [50,60], 3: [100,200,300,400,500] } </code></pre> <p>Should turn into something like:</p> <pre><code>data = [ [10,20,30,?,?], [50,60,?,?,?], [100,200,300,400,500] ] </code></pre> <p>I'm going to do some basic statistics on each row, eg:</p> <pre><code>deviations = numpy.std(data, axis=1) </code></pre> <p>Questions:</p> <ul> <li><p>What's the best / most efficient way to create the numpy.array from the dictionary? The dictionary is large; a couple of million keys, each with ~20 items.</p></li> <li><p>The number of values for each 'row' are different. If I understand correctly numpy wants uniform size, so what do I fill in for the missing items to make std() happy?</p></li> </ul> <p>Update: One thing I forgot to mention - while the python techniques are reasonable (eg. looping over a few million items is fast), it's constrained to a single CPU. Numpy operations scale nicely to the hardware and hit all the CPUs, so they're attractive.</p>
8
2009-03-02T06:57:43Z
601,582
<p>You don't need to create numpy arrays to call numpy.std(). You can call numpy.std() in a loop over all the values of your dictionary. The list will be converted to a numpy array on the fly to compute the standard variation.</p> <p>The downside of this method is that the main loop will be in python and not in C. But I guess this should be fast enough: you will still compute std at C speed, and you will save a lot of memory as you won't have to store 0 values where you have variable size arrays. </p> <ul> <li>If you want to further optimize this, you can store your values into a list of numpy arrays, so that you do the python list -> numpy array conversion only once. </li> <li>if you find that this is still too slow, try to use psycho to optimize the python loop.</li> <li>if this is still too slow, try using <a href="http://www.cython.org/" rel="nofollow">Cython</a> together with the numpy module. This <a href="http://wiki.cython.org/tutorials/numpy" rel="nofollow">Tutorial</a> claims impressive speed improvements for image processing. Or simply program the whole std function in Cython (see <a href="http://prabhuramachandran.blogspot.com/2008%5F09%5F01%5Farchive.html" rel="nofollow">this</a> for benchmarks and examples with sum function )</li> <li>An alternative to Cython would be to use <a href="http://www.swig.org/" rel="nofollow">SWIG</a> with <a href="http://projects.scipy.org/scipy/numpy/browser/trunk/doc/swig/numpy.i" rel="nofollow">numpy.i</a>.</li> <li>if you want to use only numpy and have everything computed at C level, try grouping all the records of same size together in different arrays and call numpy.std() on each of them. It should look like the following example.</li> </ul> <p>example with O(N) complexity:</p> <pre><code>import numpy list_size_1 = [] list_size_2 = [] for row in data.itervalues(): if len(row) == 1: list_size_1.append(row) elif len(row) == 2: list_size_2.append(row) list_size_1 = numpy.array(list_size_1) list_size_2 = numpy.array(list_size_2) std_1 = numpy.std(list_size_1, axis = 1) std_2 = numpy.std(list_size_2, axis = 1) </code></pre>
8
2009-03-02T08:02:56Z
[ "python", "numpy" ]
Best way to create a NumPy array from a dictionary?
601,477
<p>I'm just starting with NumPy so I may be missing some core concepts...</p> <p>What's the best way to create a NumPy array from a dictionary whose values are lists?</p> <p>Something like this:</p> <pre><code>d = { 1: [10,20,30] , 2: [50,60], 3: [100,200,300,400,500] } </code></pre> <p>Should turn into something like:</p> <pre><code>data = [ [10,20,30,?,?], [50,60,?,?,?], [100,200,300,400,500] ] </code></pre> <p>I'm going to do some basic statistics on each row, eg:</p> <pre><code>deviations = numpy.std(data, axis=1) </code></pre> <p>Questions:</p> <ul> <li><p>What's the best / most efficient way to create the numpy.array from the dictionary? The dictionary is large; a couple of million keys, each with ~20 items.</p></li> <li><p>The number of values for each 'row' are different. If I understand correctly numpy wants uniform size, so what do I fill in for the missing items to make std() happy?</p></li> </ul> <p>Update: One thing I forgot to mention - while the python techniques are reasonable (eg. looping over a few million items is fast), it's constrained to a single CPU. Numpy operations scale nicely to the hardware and hit all the CPUs, so they're attractive.</p>
8
2009-03-02T06:57:43Z
603,892
<p>While there are already some pretty reasonable ideas present here, I believe following is worth mentioning.</p> <p>Filling missing data with any default value would spoil the statistical characteristics (std, etc). Evidently that's why Mapad proposed the nice trick with grouping same sized records. The problem with it (assuming there isn't any a priori data on records lengths is at hand) is that it involves even more computations than the straightforward solution:</p> <ol> <li>at least <em>O(N*logN)</em> 'len' calls and comparisons for sorting with an effective algorithm</li> <li><em>O(N)</em> checks on the second way through the list to obtain groups(their beginning and end indexes on the 'vertical' axis)</li> </ol> <p>Using Psyco is a good idea (it's strikingly easy to use, so be sure to give it a try).</p> <p>It seems that the optimal way is to take the strategy described by Mapad in bullet #1, but with a modification - not to generate the whole list, but iterate through the dictionary converting each row into numpy.array and performing required computations. Like this:</p> <pre><code>for row in data.itervalues(): np_row = numpy.array(row) this_row_std = numpy.std(np_row) # compute any other statistic descriptors needed and then save to some list </code></pre> <p>In any case a few million loops in python won't take as long as one might expect. Besides this doesn't look like a routine computation, so who cares if it takes extra second/minute if it is run once in a while or even just once.</p> <p><hr /></p> <p>A generalized variant of what was suggested by Mapad:</p> <pre><code>from numpy import array, mean, std def get_statistical_descriptors(a): if ax = len(shape(a))-1 functions = [mean, std] return f(a, axis = ax) for f in functions def process_long_list_stats(data): import numpy groups = {} for key, row in data.iteritems(): size = len(row) try: groups[size].append(key) except KeyError: groups[size] = ([key]) results = [] for gr_keys in groups.itervalues(): gr_rows = numpy.array([data[k] for k in gr_keys]) stats = get_statistical_descriptors(gr_rows) results.extend( zip(gr_keys, zip(*stats)) ) return dict(results) </code></pre>
2
2009-03-02T20:36:03Z
[ "python", "numpy" ]
Best way to create a NumPy array from a dictionary?
601,477
<p>I'm just starting with NumPy so I may be missing some core concepts...</p> <p>What's the best way to create a NumPy array from a dictionary whose values are lists?</p> <p>Something like this:</p> <pre><code>d = { 1: [10,20,30] , 2: [50,60], 3: [100,200,300,400,500] } </code></pre> <p>Should turn into something like:</p> <pre><code>data = [ [10,20,30,?,?], [50,60,?,?,?], [100,200,300,400,500] ] </code></pre> <p>I'm going to do some basic statistics on each row, eg:</p> <pre><code>deviations = numpy.std(data, axis=1) </code></pre> <p>Questions:</p> <ul> <li><p>What's the best / most efficient way to create the numpy.array from the dictionary? The dictionary is large; a couple of million keys, each with ~20 items.</p></li> <li><p>The number of values for each 'row' are different. If I understand correctly numpy wants uniform size, so what do I fill in for the missing items to make std() happy?</p></li> </ul> <p>Update: One thing I forgot to mention - while the python techniques are reasonable (eg. looping over a few million items is fast), it's constrained to a single CPU. Numpy operations scale nicely to the hardware and hit all the CPUs, so they're attractive.</p>
8
2009-03-02T06:57:43Z
11,619,778
<p><strong>numpy dictionary</strong></p> <p>You can use a structured array to preserve the ability to address a numpy object by a key, like a dictionary.</p> <pre><code>import numpy as np dd = {'a':1,'b':2,'c':3} dtype = eval('[' + ','.join(["('%s', float)" % key for key in dd.keys()]) + ']') values = [tuple(dd.values())] numpy_dict = np.array(values, dtype=dtype) numpy_dict['c'] </code></pre> <p>will now output</p> <pre><code>array([ 3.]) </code></pre>
0
2012-07-23T20:11:50Z
[ "python", "numpy" ]
Python Table engine binding for Tokyo Cabinet
601,865
<p>I am looking for python bindings for Table engine of Tokyo cabinet. I tried <a href="http://pypi.python.org/pypi/pytc" rel="nofollow">Pytc</a> but can only find Hash and B-tree engine support. Is there any other bindings available?</p>
12
2009-03-02T10:18:23Z
601,920
<p>The only other one I know of is a fork of pytc but it looks like they have only done some refactoring and documentation work, so probably still only hash and b-tree support:</p> <p><a href="http://github.com/rsms/tc/tree/master" rel="nofollow">tc</a></p> <p>If this doesn't work you are probably out of luck. I think all the tyrant bindings only use the hash engine.</p>
1
2009-03-02T10:49:03Z
[ "python", "tokyo-cabinet" ]
Python Table engine binding for Tokyo Cabinet
601,865
<p>I am looking for python bindings for Table engine of Tokyo cabinet. I tried <a href="http://pypi.python.org/pypi/pytc" rel="nofollow">Pytc</a> but can only find Hash and B-tree engine support. Is there any other bindings available?</p>
12
2009-03-02T10:18:23Z
732,178
<p>I was in contact with the author of tc and he told me the following:</p> <blockquote> <p>Currently, the table (tdb) driver exist in the <a href="http://github.com/rsms/tc/blob/master/src/TDB.c" rel="nofollow">master branch</a> (<a href="http://github.com/rsms/tc/blob/master/lib/tc/test/tdb.py" rel="nofollow">unit tests</a>) and the <a href="http://github.com/rsms/tc/tree/fdb%5Frewrite" rel="nofollow">fdb driver</a> is being developed in a separate branch.</p> </blockquote> <p>I tried the table driver for a small test with success, am planning on trying it on larger tables soon.</p>
4
2009-04-08T22:41:45Z
[ "python", "tokyo-cabinet" ]
Python Table engine binding for Tokyo Cabinet
601,865
<p>I am looking for python bindings for Table engine of Tokyo cabinet. I tried <a href="http://pypi.python.org/pypi/pytc" rel="nofollow">Pytc</a> but can only find Hash and B-tree engine support. Is there any other bindings available?</p>
12
2009-03-02T10:18:23Z
897,843
<p>Here is an implementation of search of table engine using PyTyrant:</p> <p><a href="http://github.com/ericflo/pytyrant/tree/master" rel="nofollow">http://github.com/ericflo/pytyrant/tree/master</a></p>
7
2009-05-22T13:25:52Z
[ "python", "tokyo-cabinet" ]
Python Table engine binding for Tokyo Cabinet
601,865
<p>I am looking for python bindings for Table engine of Tokyo cabinet. I tried <a href="http://pypi.python.org/pypi/pytc" rel="nofollow">Pytc</a> but can only find Hash and B-tree engine support. Is there any other bindings available?</p>
12
2009-03-02T10:18:23Z
1,312,908
<p>I've been monitoring (and sometimes improving) various Python bindings for TC for more than a year, so here's an updated list of best bindings matching your criteria.</p> <ul> <li>For Tokyo Cabinet, including Tyrant: <a href="http://pypi.python.org/pypi/tokyo-python/" rel="nofollow">tokyo-python</a></li> <li>For Tokyo Tyrant (pure-Python): <a href="http://pypi.python.org/pypi/pyrant/" rel="nofollow">pyrant</a></li> </ul> <p>There are many stale and/or incomplete alternatives.</p>
2
2009-08-21T16:18:21Z
[ "python", "tokyo-cabinet" ]
Python Table engine binding for Tokyo Cabinet
601,865
<p>I am looking for python bindings for Table engine of Tokyo cabinet. I tried <a href="http://pypi.python.org/pypi/pytc" rel="nofollow">Pytc</a> but can only find Hash and B-tree engine support. Is there any other bindings available?</p>
12
2009-03-02T10:18:23Z
1,526,460
<p>My branch of pytc called "tc" do have support for tables (TDB) <a href="http://github.com/rsms/tc" rel="nofollow">http://github.com/rsms/tc</a></p> <p>Basic example:</p> <pre><code>&gt;&gt;&gt; import tc &gt;&gt;&gt; db = tc.TDB("slab.tdb", tc.TDBOWRITER | tc.TDBOCREAT) &gt;&gt;&gt; db.put('some key', {'name': 'John Doe', 'age': '45', 'city': u'Internets'}) &gt;&gt;&gt; rec = db.get('some key') &gt;&gt;&gt; print rec['name'] John Doe </code></pre> <p>Performing queries:</p> <pre><code>&gt;&gt;&gt; import tc &gt;&gt;&gt; db = tc.TDB("slab.tdb", tc.TDBOWRITER | tc.TDBOCREAT) &gt;&gt;&gt; db.put('torgny', {'name': 'Torgny Korv', 'age': '31', 'colors': 'red,blue,green'}) &gt;&gt;&gt; db.put('rosa', {'name': 'Rosa Flying', 'age': '29', 'colors': 'pink,blue,green'}) &gt;&gt;&gt; db.put('jdoe', {'name': 'John Doe', 'age': '45', 'colors': 'red,green,orange'}) &gt;&gt;&gt; q = db.query() &gt;&gt;&gt; q.keys() ['torgny', 'rosa', 'jdoe'] &gt;&gt;&gt; q.filter('age', tc.TDBQCNUMGE, '30') &gt;&gt;&gt; q.keys() ['torgny', 'jdoe'] &gt;&gt;&gt; q.filter('colors', tc.TDBQCSTROR, 'blue') &gt;&gt;&gt; q.keys() ['torgny'] &gt;&gt;&gt; # new query: &gt;&gt;&gt; q = db.query() &gt;&gt;&gt; q.order('name') # Ascending order by default &gt;&gt;&gt; q.keys() ['jdoe', 'rosa', 'torgny'] &gt;&gt;&gt; q.order(type=tc.TDBQONUMASC, column='age') &gt;&gt;&gt; q.keys() ['jdoe', 'torgny', 'rosa'] </code></pre> <p>More examples in the TDB unit test: <a href="http://github.com/rsms/tc/blob/master/lib/tc/test/tdb.py" rel="nofollow">http://github.com/rsms/tc/blob/master/lib/tc/test/tdb.py</a></p>
2
2009-10-06T15:46:35Z
[ "python", "tokyo-cabinet" ]
Digital Image cropping in Python
601,874
<p>Got this question from a professor, a physicist.</p> <p>I am a beginner in Python programming. I am not a computer professional I am a physicist. I was trying to write a code in python for my own research which involves a little image processing.</p> <p>All I need to do is to display an image and then select a region of interest using my mouse and finally crop out the selected region. I can do this in Matlab using the ginput() function. </p> <p>I tried using PIL. But I find that after I issue the command Image.show(), the image is displayed but then the program halts there unless I exit from the image window. Is there any way to implement what I was planning. Do I need to download any other module? Please advise. </p>
4
2009-03-02T10:23:37Z
601,922
<p>Image.show() just calls whatever simple picture viewer it can find on the current platform, one that may or may not have a crop-and-save facility.</p> <p>If you are on a Windows box and you just need to make it work on your machine, set the ‘Open with...’ association to make it so running an image loads it into an editor of your choice. On OS X and *nix you'd want to hack the _showxv() method at the bottom of Image.py to change the command used to open the image.</p> <p>If you do actually need to provide a portable solution, you'll need to use a UI framework to power your cropping application. The choices boil down to <a href="http://pythonware.com/library/tkinter/introduction/index.htm" rel="nofollow">Tkinter</a> (ImageTk.py gives you a wrapper for displaying PIL images in Tk), <a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="nofollow">PyQT4</a> (ImageQt in PIL 1.1.6 gives you a wrapper for displaying images in QT4) or <a href="http://wxpython.org/" rel="nofollow">wxPython</a> (a higher-level application authoring toolkit using wxWidgets). It'll be quite a bit of work to get the hang of a full UI kit, but you'll be able to completely customise how your application's interface will work.</p>
2
2009-03-02T10:49:56Z
[ "python", "image-processing" ]
Digital Image cropping in Python
601,874
<p>Got this question from a professor, a physicist.</p> <p>I am a beginner in Python programming. I am not a computer professional I am a physicist. I was trying to write a code in python for my own research which involves a little image processing.</p> <p>All I need to do is to display an image and then select a region of interest using my mouse and finally crop out the selected region. I can do this in Matlab using the ginput() function. </p> <p>I tried using PIL. But I find that after I issue the command Image.show(), the image is displayed but then the program halts there unless I exit from the image window. Is there any way to implement what I was planning. Do I need to download any other module? Please advise. </p>
4
2009-03-02T10:23:37Z
601,942
<p>For what it's worth (coming from another physicist), I would just do this in an image processing program like <a href="http://www.gimp.org" rel="nofollow">the GIMP</a>. The main benefit of doing this task in Python (or any language) would be to save time by automating the process, but unless you - well, the professor - can somehow develop an algorithm to automatically figure out what part of the image to crop, there doesn't seem to be much time to be saved by automation.</p> <p>If I remember correctly, GIMP is actually scriptable, possibly with Python, so it might be possible to write a time-saving GIMP script to do what your professor friend wants.</p>
4
2009-03-02T10:56:21Z
[ "python", "image-processing" ]
Digital Image cropping in Python
601,874
<p>Got this question from a professor, a physicist.</p> <p>I am a beginner in Python programming. I am not a computer professional I am a physicist. I was trying to write a code in python for my own research which involves a little image processing.</p> <p>All I need to do is to display an image and then select a region of interest using my mouse and finally crop out the selected region. I can do this in Matlab using the ginput() function. </p> <p>I tried using PIL. But I find that after I issue the command Image.show(), the image is displayed but then the program halts there unless I exit from the image window. Is there any way to implement what I was planning. Do I need to download any other module? Please advise. </p>
4
2009-03-02T10:23:37Z
602,383
<p>While I agree with David that you should probably just use GIMP or some other image manipulation program, here is a script (as I took it to be an exercise to the reader) using <a href="http://www.pygame.org/">pygame</a> that does what you want. You will need to install pygame as well as the PIL, usage would be:</p> <pre><code>scriptname.py &lt;input_path&gt; &lt;output_path&gt; </code></pre> <p>Actual script:</p> <pre><code>import pygame, sys from PIL import Image pygame.init() def displayImage( screen, px, topleft): screen.blit(px, px.get_rect()) if topleft: pygame.draw.rect( screen, (128,128,128), pygame.Rect(topleft[0], topleft[1], pygame.mouse.get_pos()[0] - topleft[0], pygame.mouse.get_pos()[1] - topleft[1])) pygame.display.flip() def setup(path): px = pygame.image.load(path) screen = pygame.display.set_mode( px.get_rect()[2:] ) screen.blit(px, px.get_rect()) pygame.display.flip() return screen, px def mainLoop(screen, px): topleft = None bottomright = None runProgram = True while runProgram: for event in pygame.event.get(): if event.type == pygame.QUIT: runProgram = False elif event.type == pygame.MOUSEBUTTONUP: if not topleft: topleft = event.pos else: bottomright = event.pos runProgram = False displayImage(screen, px, topleft) return ( topleft + bottomright ) if __name__ == "__main__": screen, px = setup(sys.argv[1]) left, upper, right, lower = mainLoop(screen, px) im = Image.open(sys.argv[1]) im = im.crop(( left, upper, right, lower)) im.save(sys.argv[2]) </code></pre> <p>Hope this helps :)</p>
6
2009-03-02T13:39:00Z
[ "python", "image-processing" ]
Digital Image cropping in Python
601,874
<p>Got this question from a professor, a physicist.</p> <p>I am a beginner in Python programming. I am not a computer professional I am a physicist. I was trying to write a code in python for my own research which involves a little image processing.</p> <p>All I need to do is to display an image and then select a region of interest using my mouse and finally crop out the selected region. I can do this in Matlab using the ginput() function. </p> <p>I tried using PIL. But I find that after I issue the command Image.show(), the image is displayed but then the program halts there unless I exit from the image window. Is there any way to implement what I was planning. Do I need to download any other module? Please advise. </p>
4
2009-03-02T10:23:37Z
6,654,047
<p>Is there a script in python like a library to auto crop images : <a href="http://codeunivers.com/source-codes/python/automatically_crop_image" rel="nofollow">Automatically crop image</a></p>
2
2011-07-11T17:34:31Z
[ "python", "image-processing" ]
Digital Image cropping in Python
601,874
<p>Got this question from a professor, a physicist.</p> <p>I am a beginner in Python programming. I am not a computer professional I am a physicist. I was trying to write a code in python for my own research which involves a little image processing.</p> <p>All I need to do is to display an image and then select a region of interest using my mouse and finally crop out the selected region. I can do this in Matlab using the ginput() function. </p> <p>I tried using PIL. But I find that after I issue the command Image.show(), the image is displayed but then the program halts there unless I exit from the image window. Is there any way to implement what I was planning. Do I need to download any other module? Please advise. </p>
4
2009-03-02T10:23:37Z
6,880,221
<p>What you are looking for is the module: matplotlib, it emulates Matlab. See the ginput() function. That allow you to find the bounding box, then you can use crop from PIL. </p> <p><a href="http://matplotlib.sourceforge.net/api/figure_api.html" rel="nofollow">http://matplotlib.sourceforge.net/api/figure_api.html</a></p>
0
2011-07-30T00:12:17Z
[ "python", "image-processing" ]
How to write meaningful docstrings?
601,900
<p>What, in Your opinion is a meaningful docstring? What do You expect to be described there?</p> <p>For example, consider this Python class's <code>__init__</code>:</p> <pre><code>def __init__(self, name, value, displayName=None, matchingRule="strict"): """ name - field name value - field value displayName - nice display name, if empty will be set to field name matchingRule - I have no idea what this does, set to strict by default """ </code></pre> <p>Do you find this meaningful? Post Your good/bad examples for all to know (and a general answer so it can be accepted).</p>
23
2009-03-02T10:39:52Z
601,909
<p>What should go there:</p> <p>Anything that you can't tell from the method's signature. In this case the only bit useful is: displayName - if empty will be set to field name.</p>
6
2009-03-02T10:44:16Z
[ "python", "comments", "docstring" ]
How to write meaningful docstrings?
601,900
<p>What, in Your opinion is a meaningful docstring? What do You expect to be described there?</p> <p>For example, consider this Python class's <code>__init__</code>:</p> <pre><code>def __init__(self, name, value, displayName=None, matchingRule="strict"): """ name - field name value - field value displayName - nice display name, if empty will be set to field name matchingRule - I have no idea what this does, set to strict by default """ </code></pre> <p>Do you find this meaningful? Post Your good/bad examples for all to know (and a general answer so it can be accepted).</p>
23
2009-03-02T10:39:52Z
601,960
<p>I like to use the documentation to describe in as much detail as possible what the function does, especially the behavior at corner cases (a.k.a. edge cases). Ideally, a programmer using the function should never have to look at the source code - in practice, that means that whenever another programmer does have to look at source code to figure out some detail of how the function works, that detail probably should have been mentioned in the documentation. As Freddy said, anything that doesn't add any detail to the method's signature probably shouldn't be in a documentation string.</p>
1
2009-03-02T11:06:44Z
[ "python", "comments", "docstring" ]
How to write meaningful docstrings?
601,900
<p>What, in Your opinion is a meaningful docstring? What do You expect to be described there?</p> <p>For example, consider this Python class's <code>__init__</code>:</p> <pre><code>def __init__(self, name, value, displayName=None, matchingRule="strict"): """ name - field name value - field value displayName - nice display name, if empty will be set to field name matchingRule - I have no idea what this does, set to strict by default """ </code></pre> <p>Do you find this meaningful? Post Your good/bad examples for all to know (and a general answer so it can be accepted).</p>
23
2009-03-02T10:39:52Z
601,991
<p>I agree with "Anything that you can't tell from the method's signature". It might also mean to explain what a method/function returns.</p> <p>You might also want to use <a href="http://sphinx.pocoo.org/">Sphinx</a> (and reStructuredText syntax) for documentation purposes inside your docstrings. That way you can include this in your documentation easily. For an example check out e.g. <a href="http://svn.repoze.org/repoze.bfg/trunk">repoze.bfg</a> which uses this extensively (<a href="http://svn.repoze.org/repoze.bfg/trunk/repoze/bfg/location.py">example file</a>, <a href="http://svn.repoze.org/repoze.bfg/trunk/docs/">documentation example</a>).</p> <p>Another thing one can put in docstrings is also <a href="http://docs.python.org/library/doctest.html">doctests</a>. This might make sense esp. for module or class docstrings as you can also show that way how to use it and have this testable at the same time.</p>
12
2009-03-02T11:25:15Z
[ "python", "comments", "docstring" ]
How to write meaningful docstrings?
601,900
<p>What, in Your opinion is a meaningful docstring? What do You expect to be described there?</p> <p>For example, consider this Python class's <code>__init__</code>:</p> <pre><code>def __init__(self, name, value, displayName=None, matchingRule="strict"): """ name - field name value - field value displayName - nice display name, if empty will be set to field name matchingRule - I have no idea what this does, set to strict by default """ </code></pre> <p>Do you find this meaningful? Post Your good/bad examples for all to know (and a general answer so it can be accepted).</p>
23
2009-03-02T10:39:52Z
602,160
<p>The most striking things I can think of to include in a docstring are the things that aren't obvious. Usually this includes type information, or capability requirements - eg. "Requires a file-like object". In some cases this will be evident from the signature, not so in other cases.</p> <p>Another useful thing you can put in to your docstrings is a <code>doctest</code>.</p>
2
2009-03-02T12:34:34Z
[ "python", "comments", "docstring" ]
How to write meaningful docstrings?
601,900
<p>What, in Your opinion is a meaningful docstring? What do You expect to be described there?</p> <p>For example, consider this Python class's <code>__init__</code>:</p> <pre><code>def __init__(self, name, value, displayName=None, matchingRule="strict"): """ name - field name value - field value displayName - nice display name, if empty will be set to field name matchingRule - I have no idea what this does, set to strict by default """ </code></pre> <p>Do you find this meaningful? Post Your good/bad examples for all to know (and a general answer so it can be accepted).</p>
23
2009-03-02T10:39:52Z
602,224
<p>From <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a>:</p> <blockquote> <p>Conventions for writing good documentation strings (a.k.a. "docstrings") are immortalized in <a href="http://www.python.org/dev/peps/pep-0257/" rel="nofollow">PEP 257</a>.</p> <ul> <li>Write docstrings for all public modules, functions, classes, and methods. Docstrings are not necessary for non-public methods, but you should have a comment that describes what the method does. This comment should appear after the "def" line.</li> <li><a href="http://www.python.org/dev/peps/pep-0257/" rel="nofollow">PEP 257</a> describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself, and preferably preceded by a blank line.</li> <li>For one liner docstrings, it's okay to keep the closing """ on the same line.</li> </ul> </blockquote>
8
2009-03-02T12:51:32Z
[ "python", "comments", "docstring" ]
How to write meaningful docstrings?
601,900
<p>What, in Your opinion is a meaningful docstring? What do You expect to be described there?</p> <p>For example, consider this Python class's <code>__init__</code>:</p> <pre><code>def __init__(self, name, value, displayName=None, matchingRule="strict"): """ name - field name value - field value displayName - nice display name, if empty will be set to field name matchingRule - I have no idea what this does, set to strict by default """ </code></pre> <p>Do you find this meaningful? Post Your good/bad examples for all to know (and a general answer so it can be accepted).</p>
23
2009-03-02T10:39:52Z
4,690,279
<p>Check out numpy's docstrings for good examples (e.g. <a href="http://github.com/numpy/numpy/blob/master/numpy/core/numeric.py" rel="nofollow">http://github.com/numpy/numpy/blob/master/numpy/core/numeric.py</a>).</p> <p>The docstrings are split into several sections and look like this:</p> <pre><code>Compute the sum of the elements of a list. Parameters ---------- foo: sequence of ints The list of integers to sum up. Returns ------- res: int sum of elements of foo See also -------- cumsum: compute cumulative sum of elemenents </code></pre>
4
2011-01-14T10:56:25Z
[ "python", "comments", "docstring" ]
Solution basis of underdetermined equation set in python
601,941
<p>I have an underdetermined equation set (m equations of n variables, m smaller than n). As such, if it is solvable then the set of solutions are a linear space (if it is a homogenic set) or affine space (non-homogenic).</p> <p>Is there an easy way in Python (possibly with other libraries) to obtain this space - for example, a basis of which?</p> <p>Thanks.</p>
2
2009-03-02T10:56:21Z
601,950
<p>Use <a href="http://docs.scipy.org/doc/scipy/reference/linalg.html" rel="nofollow">linalg</a> package from <a href="http://www.scipy.org" rel="nofollow">SciPy</a></p>
4
2009-03-02T11:01:32Z
[ "python", "linear-equation" ]
Solution basis of underdetermined equation set in python
601,941
<p>I have an underdetermined equation set (m equations of n variables, m smaller than n). As such, if it is solvable then the set of solutions are a linear space (if it is a homogenic set) or affine space (non-homogenic).</p> <p>Is there an easy way in Python (possibly with other libraries) to obtain this space - for example, a basis of which?</p> <p>Thanks.</p>
2
2009-03-02T10:56:21Z
602,113
<p>Like the previous poster said, you'll want linalg from SciPy, but focus on the <a href="http://en.wikipedia.org/wiki/Singular%5Fvalue%5Fdecomposition" rel="nofollow">Singular Value Decomposition</a> solution. The matrix U is the basis for the output vectors.</p>
2
2009-03-02T12:19:30Z
[ "python", "linear-equation" ]
Store last created model's row in memory
602,030
<p>I am working on ajax-game. The abstract: 2+ gamers(browsers) change a variable which is saved to DB through json. All gamers are synchronized by javascript-timer+json - periodically reading that variable from DB. </p> <p>In general, all changes are stored in DB as history, but I want the recent change duplicated in memory. </p> <p>So the problem is: i want one variable to be stored in memory instead of DB.</p>
0
2009-03-02T11:46:17Z
603,121
<p>You can use the cache system:</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/cache/#topics-cache" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/cache/#topics-cache</a></p>
0
2009-03-02T17:11:29Z
[ "python", "django" ]
Store last created model's row in memory
602,030
<p>I am working on ajax-game. The abstract: 2+ gamers(browsers) change a variable which is saved to DB through json. All gamers are synchronized by javascript-timer+json - periodically reading that variable from DB. </p> <p>In general, all changes are stored in DB as history, but I want the recent change duplicated in memory. </p> <p>So the problem is: i want one variable to be stored in memory instead of DB.</p>
0
2009-03-02T11:46:17Z
603,202
<p>Unfortunately I don't believe you can do this unless you only have one instance of Python running, in which case you can use a global variable. With most web implementations you have a threaded server so this would not work. You would have to do a fetch from the database to get the latest copy of the record.</p> <p>If this is a very high-usage situation, you may want to look into <a href="http://www.danga.com/memcached/" rel="nofollow">memcached</a> (or similar) as a way of lowering the performance overhead of hitting the database for each request.</p>
0
2009-03-02T17:30:43Z
[ "python", "django" ]
Store last created model's row in memory
602,030
<p>I am working on ajax-game. The abstract: 2+ gamers(browsers) change a variable which is saved to DB through json. All gamers are synchronized by javascript-timer+json - periodically reading that variable from DB. </p> <p>In general, all changes are stored in DB as history, but I want the recent change duplicated in memory. </p> <p>So the problem is: i want one variable to be stored in memory instead of DB.</p>
0
2009-03-02T11:46:17Z
603,637
<p>You'd either have to use a cache, or fetch the most recent change on each request (since you can't persist objects between requests in-memory).</p> <p>From what you describe, it sounds as if it's being hit fairly frequently, so the cache is probably the way to go.</p>
0
2009-03-02T19:27:43Z
[ "python", "django" ]
Store last created model's row in memory
602,030
<p>I am working on ajax-game. The abstract: 2+ gamers(browsers) change a variable which is saved to DB through json. All gamers are synchronized by javascript-timer+json - periodically reading that variable from DB. </p> <p>In general, all changes are stored in DB as history, but I want the recent change duplicated in memory. </p> <p>So the problem is: i want one variable to be stored in memory instead of DB.</p>
0
2009-03-02T11:46:17Z
723,413
<p>Would something like <a href="http://www.danga.com/memcached/" rel="nofollow"><code>memcached</code></a> be suitable?</p>
0
2009-04-06T21:57:34Z
[ "python", "django" ]
Should I check the types of constructor arguments (and at other places too)?
602,046
<p>Python discourages checking the types. But in many cases this may be useful:</p> <ol> <li><p>Checking constructor arguments. e.g. checking foe Boolean, string, dict etc. If I don't and set the object's members to the arguments it will cause problems later.</p></li> <li><p>Checking functions arguments.</p></li> <li><p>In properties. If someone sets a wrong value or different type, I should respond quickly.</p></li> </ol>
9
2009-03-02T11:55:04Z
602,078
<p>The simple answer is <strong>No</strong>, use Polymorphism, Exceptions etc. </p> <ol> <li><p>In the case of constructor arguments being of the wrong type, an exception will be thrown when executing code that depend s on the parameter being of a particular type. If it is a weird, domain specific thing, raise your own Exception. Surround blocks of code which are likely to fail with try-except and handle errors. So it is better to use Exception handling. (<em>Same goes for function arguments</em>)</p></li> <li><p>In properties, the same argument applies. If you are validating the value received, use an assertion to check its range etc. If the value is of the wrong type, it will fail anyway. Then, handle AssertionError.</p></li> </ol> <p>In Python, you treat programmers as intelligent beings!! Just document your code well (make things obvious), raise Exceptions where appropriate, write polymorphic code etc. Leave the Exception handling(where it is appropriate only)/errors in construction to the client code.</p> <p><strong>Warning</strong><br /> Leaving Exception handling to clients doesn't mean that you should chuck a lot of garbage errors at the unwitting user. If at all possible, handle exceptions that might occur due to bad construction or any other reason in your code itself. Your code should be robust. Where it is impossible for you to handle the error, politely inform the user/client code programmer!</p> <p><strong>Note</strong><br /> In general, bad arguments to a constructor isn't something I worry about too much.</p>
8
2009-03-02T12:04:19Z
[ "python", "typechecking" ]
Should I check the types of constructor arguments (and at other places too)?
602,046
<p>Python discourages checking the types. But in many cases this may be useful:</p> <ol> <li><p>Checking constructor arguments. e.g. checking foe Boolean, string, dict etc. If I don't and set the object's members to the arguments it will cause problems later.</p></li> <li><p>Checking functions arguments.</p></li> <li><p>In properties. If someone sets a wrong value or different type, I should respond quickly.</p></li> </ol>
9
2009-03-02T11:55:04Z
602,087
<p>Check all you like, you just have to be explicit. The following example is a constructor from <a href="http://svn.python.org/view/python/trunk/Lib/csv.py?view=markup" rel="nofollow">a module</a> in the standard library - it checks the <code>extrasaction</code> arg:</p> <pre><code>class DictWriter: def __init__(self, f, fieldnames, restval="", extrasaction="raise", dialect="excel", *args, **kwds): self.fieldnames = fieldnames # list of keys for the dict self.restval = restval # for writing short dicts if extrasaction.lower() not in ("raise", "ignore"): raise ValueError, \ ("extrasaction (%s) must be 'raise' or 'ignore'" % extrasaction) self.extrasaction = extrasaction self.writer = writer(f, dialect, *args, **kwds) </code></pre>
3
2009-03-02T12:06:35Z
[ "python", "typechecking" ]
Should I check the types of constructor arguments (and at other places too)?
602,046
<p>Python discourages checking the types. But in many cases this may be useful:</p> <ol> <li><p>Checking constructor arguments. e.g. checking foe Boolean, string, dict etc. If I don't and set the object's members to the arguments it will cause problems later.</p></li> <li><p>Checking functions arguments.</p></li> <li><p>In properties. If someone sets a wrong value or different type, I should respond quickly.</p></li> </ol>
9
2009-03-02T11:55:04Z
602,097
<p>The answer is almost always "no". The general idea in Python, Ruby, and some other languages us called "<a href="http://en.wikipedia.org/wiki/Duck%5Ftyping">Duck Typing</a>". You shouldn't care what something is, only how it works. In other words, "if all you want is something that quacks, you don't need to check that it's actually a duck."</p> <p>In real life, the problem with putting in all those type checks is the inability to replace inputs with alternate implementations. You may check for dict, but I may want to pass something in which is not a dict, but implements the dict API.</p> <p>Type checking only checks for one of many possible errors in code. For example, it doesn't include range checking (at least not in Python). A modern response to the assertion that there needs to be type checking is that it's more effective to develop unit tests which ensure that not only are the types correct, but also that the functionality is correct.</p> <p>Another viewpoint is that you should treat your API users like consenting adults, and trust them to use the API correctly. Of course there are times when input checking is helpful, but that's less common than you think. One example is input from untrusted sources, like from the public web.</p>
11
2009-03-02T12:12:01Z
[ "python", "typechecking" ]
Should I check the types of constructor arguments (and at other places too)?
602,046
<p>Python discourages checking the types. But in many cases this may be useful:</p> <ol> <li><p>Checking constructor arguments. e.g. checking foe Boolean, string, dict etc. If I don't and set the object's members to the arguments it will cause problems later.</p></li> <li><p>Checking functions arguments.</p></li> <li><p>In properties. If someone sets a wrong value or different type, I should respond quickly.</p></li> </ol>
9
2009-03-02T11:55:04Z
602,391
<p>"If I don't and set the object's members to the arguments it will cause problems later."</p> <p>Please be very clear on the exact list of "problems" which will be caused later.</p> <ul> <li><p>Will it not work at all? That what try/except blocks are for.</p></li> <li><p>Will it behave "oddly"? This is really rare, and is limited to "near-miss" types and operators. The standard example is division. If you expected integers, but got floating-point, then division may not do what you wanted. But that's fixed with the //, vs. / division operators.</p></li> <li><p>Will it be simply wrong, but still appear to complete? This is really rare, and would require a pretty-carefully crafted type that used standard names, but did non-standard things. For example</p> <pre><code>class MyMaliciousList( list ): def append( self, value ): super( MyMaliciousList, self ).remove( value ) </code></pre></li> </ul> <p>Other than that, it's hard to have things "cause problems later". Please update your question with specific examples of "problems".</p>
0
2009-03-02T13:41:16Z
[ "python", "typechecking" ]
Should I check the types of constructor arguments (and at other places too)?
602,046
<p>Python discourages checking the types. But in many cases this may be useful:</p> <ol> <li><p>Checking constructor arguments. e.g. checking foe Boolean, string, dict etc. If I don't and set the object's members to the arguments it will cause problems later.</p></li> <li><p>Checking functions arguments.</p></li> <li><p>In properties. If someone sets a wrong value or different type, I should respond quickly.</p></li> </ol>
9
2009-03-02T11:55:04Z
602,395
<p>It is often a good thing to do. Checking for explicit types is probably not so useful in Python (as others have said), but checking for legal values can be a good idea. The reason it's a good idea is that the software will fail closer to the source of the bug (it follows the Fail Fast Principle). Also, the checks act as documentation to other programmers and yourself. Even better, it is "executable documentation", which is good because it's documentation that can't lie.</p> <p>A quick and dirty but reasonable way to check your arguments is to use assert:</p> <pre><code>def my_sqrt(x): assert x &gt;= 0, "must be greater or equal to zero" # ... </code></pre> <p>Asserting your arguments is a kind of poor man's Design by Contract. (You might like to look up Design by Contract; it is interesting.) </p>
1
2009-03-02T13:42:06Z
[ "python", "typechecking" ]
Should I check the types of constructor arguments (and at other places too)?
602,046
<p>Python discourages checking the types. But in many cases this may be useful:</p> <ol> <li><p>Checking constructor arguments. e.g. checking foe Boolean, string, dict etc. If I don't and set the object's members to the arguments it will cause problems later.</p></li> <li><p>Checking functions arguments.</p></li> <li><p>In properties. If someone sets a wrong value or different type, I should respond quickly.</p></li> </ol>
9
2009-03-02T11:55:04Z
604,568
<p>AFAIU, you want to make sure that some objects behave ("follow an interface") at an earlier time than that of the actual use. In your example, you want to know that objects are appropriate at instance creation time, not when they will actually be used.</p> <p>Keeping in mind that we're talking Python here, I won't suggest <code>assert</code> (what if <code>python -O</code> or an environment variable PYTHONOPTIMIZE is set to 1 when your program runs?) or checking for specific types (because that unnecessarily restricts the types you can use), but I will suggest early testing <em>functionality</em>, something along the lines:</p> <pre><code>def __init__(self, a_number, a_boolean, a_duck, a_sequence): self.a_number= a_number + 0 self.a_boolean= not not a_boolean try: a_duck.quack except AttributeError: raise TypeError, "can't use it if it doesn't quack" else: self.a_duck= a_duck try: iter(a_sequence) except TypeError: raise TypeError, "expected an iterable sequence" else: self.a_sequence= a_sequence </code></pre> <p>I used <code>try… except… else</code> in this suggestion because I want to set the instance members <em>only</em> if the test succeeded, even if the code is changed or augmented. You don't have to do it so, obviously.</p> <p>For function arguments and setting properties, I wouldn't do these tests in advance, I'd just use the provided objects and act on thrown exceptions, unless the suspect objects are going to be used after a lengthy process.</p>
0
2009-03-03T00:02:14Z
[ "python", "typechecking" ]
Should I check the types of constructor arguments (and at other places too)?
602,046
<p>Python discourages checking the types. But in many cases this may be useful:</p> <ol> <li><p>Checking constructor arguments. e.g. checking foe Boolean, string, dict etc. If I don't and set the object's members to the arguments it will cause problems later.</p></li> <li><p>Checking functions arguments.</p></li> <li><p>In properties. If someone sets a wrong value or different type, I should respond quickly.</p></li> </ol>
9
2009-03-02T11:55:04Z
604,615
<p>As dalke says, the answer is almost always "no". In Python, you generally do not care that a a parameter <em>is</em> a certain type but rather that it <em>behaves</em> like a certain type. This is known as "<a href="http://en.wikipedia.org/wiki/Duck%5Ftyping" rel="nofollow">Duck Typing</a>". There are two ways to test whether a parameter <em>behaves</em> like a given type: (1) you can use it as if it behaved as you expect and throw an exception when/if it doesn't or (2) you can define an interface that describes how that type should <em>behave</em> and test conformance with that interface.</p> <p><a href="http://apidoc.zope.org/%2B%2Bapidoc%2B%2B/Book/ifaceschema/interface/show.html" rel="nofollow">zope.interface</a> is my prefered interface system for Python, but there are several others. With any one of them, you define an interface, then declare that a given type conforms to that interface or define an adaptor that turns your type into something that does conform to that interface. You can then assert (or test as you wish) that paramters provide (in the zope.interface terminology) that interface.</p>
0
2009-03-03T00:14:47Z
[ "python", "typechecking" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
602,111
<p>nikow: I can only answer for myself, most of my Python (and PHP or Ruby, all dynamic "scripting" languages) work is done <em>just for me</em> - but I always release it on my personal site if anyone else finds it useful, but I never go through any documentation or QA process because as long as it works for me I'm happy.</p>
0
2009-03-02T12:18:28Z
[ "python", "conventions" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
602,116
<p>PEP8 is a style <strong>guide</strong>, not a style requirement. It even states that you should "know when to be inconsistent".</p> <p>Personally, I don't like some of the guidelines in it. I prefer tabs to spaces (but still abhor the mixing of the two).</p> <p>And, to be brutal, I don't often look at the source code of libraries I'm using unless it's absolutely necessary. I'd much prefer the documentation for said library to be adequate enough that I never have to look at the source (bugs notwithstanding, of course).</p> <p>Seriously, why do you really care what the source code for matplotlib looks like, as long as it does what it is intended to do?</p> <p>I agree with you on the missing docstrings (assuming they're public elements rather than internal ones) but that's not the only way to document a library.</p>
4
2009-03-02T12:21:19Z
[ "python", "conventions" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
602,128
<p>Well, they <strong>are</strong> open source. As such they will also evolve over time, if they are good enough. </p> <p>That's one of the many beauties of open source.</p> <p>Often there is little sense in writing lot of documentation and "good" code if you don't know whether the project will live on. That would just be a waste of time.</p> <p>Edit: Of course writing good code would never hurt the first time around though... But maybe just "getting the job done" is good enough in many cases. I think that otherwise we wouldn't enjoy the vast amount of options when it comes to OSS.</p> <p>I think that if enough people act a specific way there might be some explanation to it. They are not just randomly doing so to offend you.</p>
0
2009-03-02T12:24:54Z
[ "python", "conventions" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
602,137
<p>PEP8 is just that, a convention, not a requirement. It would be really sad if all python programmers <em>had</em> to adhere to a common set of rules, we lose enthusiasm over the slightest of issues.</p> <p>As far as missing docstrings are concerned - yes, they can help when using interactive help - but I generally don't mind as long as there's <em>some</em> documentation. I try not to read the source code of the libraries I use, I tend to start modifying (rewriting) them.</p>
1
2009-03-02T12:26:34Z
[ "python", "conventions" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
602,139
<p>Regarding documentation, it's not just Python. If there is one single factor that is preventing the wider adoption of OSS it is, IMHO, the truly dreadful level of documentation of most OSS projects. This starts at the code level and extends to the user docs. Can I just say to anyone working on OSS:</p> <p>a) Comment your code! There is no such thing as self documenting code!</p> <p>b) Spend at least 25% of the project time budget on end-user documentation.</p> <p>And I do know vaguely what I'm talking about - I have a couple of OSS projects of my own, I've contributed to several others and I use OSS almost exclusively. And yesterday I spent over 4 hours trying to build a major OSS project (no names, no pack drill), and failing because of the crappy, self-contradictory documentation. </p>
21
2009-03-02T12:26:45Z
[ "python", "conventions" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
602,172
<blockquote> <p>Instead the authors each seem to follow their own glorious convention. And sometimes the conventions are not even consistent with the same file of a library</p> </blockquote> <p>Welcome to the wonderful code of the real world!</p> <p>FWIW Python code I have met is no better or worse than that in any other language.</p> <p>(Well, better than the average PHP project, obviously, but that's not really fair.)</p>
7
2009-03-02T12:37:26Z
[ "python", "conventions" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
602,217
<p>This is because Python is not backed up by the corporate world like Java or .Net .</p> <p>If I want my Java library to be promoted by Sun I will follow their guidelines. This is not the case with Python. I write my code, people find it better and it has to evolve on its own.</p> <p>Also most Python developers are from C++, C, Java,.Net etc. And they start writing production code right from the first day. Thanks to easiness of Python. And the vicious cycle continues.</p> <p>Even it took me a month to come to PEP8 and refactor my code.</p>
5
2009-03-02T12:49:15Z
[ "python", "conventions" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
602,220
<p>As for matplotlib, there is project to improve it's "pythoness" - <a href="http://www.scipy.org/PyLab" rel="nofollow">http://www.scipy.org/PyLab</a></p> <p>The thing about scientific libraries, is that they are written by scientist, no by professional software developers. Moveover, those scientist are used to write Fortran. The question is -- would you rather have working code or beautiful code?</p>
4
2009-03-02T12:50:09Z
[ "python", "conventions" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
602,236
<p>Quality of code * number of comments * time = constant</p> <p>Pick two !</p> <p>I never had any problem using matplotlib; can't say I looked at the code much - it is a fine library. Does what it is supposed to do (for free !)</p>
0
2009-03-02T12:55:10Z
[ "python", "conventions" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
602,280
<p>PEP 8 has changed over time. Some modules follow older recommendations. You can see that with PIL, which uses modules like "Image" where the module contains a single main class, instead of the recommended lowercase for module names, and in C extensions which use the "c" prefix, rather than the more modern "_" prefix.</p> <p>Some of the libraries are developed by people who are strongly influenced by traditions in other fields, like Java and C++. These people more often use CamelCase instead of the PEP 8 recommended lowercase_with_underscores.</p> <p>The answers here wouldn't be complete without reference to <a href="http://en.wikipedia.org/wiki/Sturgeon%27s%5Flaw" rel="nofollow">Sturgeon's Law</a>: "Ninety percent of everything is crap."</p>
6
2009-03-02T13:05:08Z
[ "python", "conventions" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
602,406
<blockquote> <p>Ninety percent of [python libraries] are crud, but ninety percent of everything is crud</p> </blockquote> <p>-- Sturgeons law (paraphrased)</p>
5
2009-03-02T13:45:32Z
[ "python", "conventions" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
602,703
<p>I believe that Python suffers from being hoisted too eagerly on people who are not programmers (by schooling or trade) as a solution for "need some programming done? Here, try this easy and mature tool". </p> <p>Similarly to how PHP became such a huge success and with so many libraries with abysmal code quality (even if, granted, the average Python code quality is better then for PHP) - the average PHP user similarly to the average Python user has not much programming experience or skills and very little incentive to improve themselves in this regard - they set out to achieve something, and maybe they thought it is worthy enough to be shared with the community in the form of a library, but most often once the job is done they have no interest to better the code or better themselves (in programming skills, I mean).</p> <p>The solution might be for Python library repositories (such as PyPI) to have stricter rules about accepting contributed packages - handle this with a review process whose purpose is to ensure quality - the same way that major Linux distributions have a review process before adding a package to their repositories.</p>
4
2009-03-02T15:19:13Z
[ "python", "conventions" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
603,218
<p>It sounds like you have come to find that code quality does not meet the expectations you were set up to expect. Perhaps from school, or best practices books or senior developers.</p> <p>After having worked at several companies, I found myself regularly advised to do unit tests, document code, use version/source control (all good advice that I have taken) then finding that the givers of that advice rarely follow the advice themselves. </p> <p>I would say that you do have the right impression that sometimes the code quality is low, but only based on your expectations. Certainly numpy and others are quite useful packages, even if not coded to the standard you were set up to expect. </p> <p>Standards are opinions, and if you are of the opinion that standards are low, then you can try to help make those standards better by contributing, or accept them as they are and be sure to write code that serves as an example to the juniors you will find yourself in charge of one day.</p>
5
2009-03-02T17:32:58Z
[ "python", "conventions" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
603,336
<p>Regarding comparison with other languages, I think that language design plays a big part here. For example, in a strong-typed language like Java, even if the library is missing good documentation, you can still deduce much of the functionality from the method signatures. No <code>*args</code> to contend with.</p>
1
2009-03-02T17:56:35Z
[ "python", "conventions" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
603,872
<p>The first thing you need to realize is that Python did not spring, fully formed, from the head of Guido sometime around version 2.x. It's grown over the course of the past twenty years.</p> <p>In fact, a number of the things you mention (unittest, for example, and PEP-8), didn't even exist when some of the standard libraries were first written.</p> <p>You'll probably notice that the older the library you're looking at, the more likely they are to have divergences from the current "best practices"--often because they predate widespread adoption of those practices. More recent libraries are more likely to conform to current practices. </p> <p>Additionally, sometimes there is often a good reason for <em>not</em> bringing them up to date. Imagine you have several tens of thousands of lines of code written against the current Python libraries. Now, the maintainer of one of those libraries decides to change the libraries to make the class and function names conform to PEP-8. Now everyone who has working code has to revisit huge amounts of it, lest the renaming break things.</p> <p>That's not to say there aren't things that can improve in Python libraries--there are! But there's always a trade-off between perfection and getting things done. That's one reason they say "Practicality beats purity."</p>
7
2009-03-02T20:27:56Z
[ "python", "conventions" ]
Do many Python libraries have relatively low code quality?
602,096
<p><strong>Edit:</strong> Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.</p> <hr> <p>I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.</p> <p><em>Some reasons why I have the impression that quality is lacking:</em></p> <ul> <li><p>The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes <code>*args</code> and <code>**kwargs</code> but does not document which values can be given.</p></li> <li><p>Bad Python coding practices, like adding new attributes outside of <code>__init__</code>. Things like this make the code hard to read (or to maintain).</p></li> <li><p>Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.</p></li> <li><p>The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.</p></li> <li><p>Poor unittest coverage.</p></li> </ul> <p>Don't get me wrong, <em>I absolutely love Python and its ecosystem</em>. And even though I struggled with these libraries <em>they generally get the job done and I am grateful for that</em>. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because <em>Python gives you so much freedom that it is very easy to write bad code</em>.</p>
14
2009-03-02T12:11:56Z
653,944
<p>How about a collection of examples of good software doc ?<br /> Good examples might lead to overall improvement a bit faster than random walk.<br /> The collection could be split into categories such as:<br /> inline doc / help page / tutorial / reference manual, web page / paper, pictures / none.<br /> Each entry should have a few words on <em>why</em> the reviewer finds it good.<br /> (Where: a corner of stackoverflow ?)</p>
1
2009-03-17T12:06:57Z
[ "python", "conventions" ]
Differential AJAX updates for HTML table?
602,322
<p>I have a <a href="http://conquer-on-contact.bthomson.com" rel="nofollow">game</a> on Google App Engine that's based on a 25x20 HTML table (the game board). Every 3 seconds the user can "move," which sends an AJAX request to the server, at which time the server rerenders the entire HTML table and sends it to the user.</p> <p>This was easy to write, but it wastes a lot of bandwidth. Are there any libraries, client (preferably jquery) or server-side (must work with GAE), that help send differential instead of full updates for large tables? Usually only 5-10 tiles change on a given reload, so I feel like I could cut bandwidth use by an order of magnitude by sending just those tiles instead of all 500 every 3 seconds.</p> <p>I'm also open to "you idiot, why are you using HTML tables"-type comments if you can suggest a better alternative. For example are there any CSS/DOM manipulation techniques I should be considering instead of using an HTML table? Should I use a table but give each td coordinates for an id (like "12x08") and then use jquery to replace cells by id?</p> <p>A clarification: the tiles are text, not images.</p>
2
2009-03-02T13:17:57Z
602,381
<p>Without thinking of deltas:</p> <p>You can use JSON quite easily to do this sort of thing. You can roll out your own compressed format, too.</p> <p>I think compressing the data using gzip would help a lot. Most browsers nowadays support it, and it will greatly reduce the size of your responses.</p>
1
2009-03-02T13:38:00Z
[ "jquery", "python", "html", "google-app-engine", "dhtml" ]
Differential AJAX updates for HTML table?
602,322
<p>I have a <a href="http://conquer-on-contact.bthomson.com" rel="nofollow">game</a> on Google App Engine that's based on a 25x20 HTML table (the game board). Every 3 seconds the user can "move," which sends an AJAX request to the server, at which time the server rerenders the entire HTML table and sends it to the user.</p> <p>This was easy to write, but it wastes a lot of bandwidth. Are there any libraries, client (preferably jquery) or server-side (must work with GAE), that help send differential instead of full updates for large tables? Usually only 5-10 tiles change on a given reload, so I feel like I could cut bandwidth use by an order of magnitude by sending just those tiles instead of all 500 every 3 seconds.</p> <p>I'm also open to "you idiot, why are you using HTML tables"-type comments if you can suggest a better alternative. For example are there any CSS/DOM manipulation techniques I should be considering instead of using an HTML table? Should I use a table but give each td coordinates for an id (like "12x08") and then use jquery to replace cells by id?</p> <p>A clarification: the tiles are text, not images.</p>
2
2009-03-02T13:17:57Z
602,396
<p>If you known the state between refreshes on the server side (see comment on question), you an send the data using JSON like so (not sure about exact syntax):</p> <pre><code>[ { x: 3, y: 5, class: "asdf", content: "1234" }, { x: 6, y: 5, class: "asdf", content: "8156" }, { x: 2, y: 2, class: "qwer", content: "1337" } ] </code></pre> <p>Compact that (remove extra whitespace, etc.), gzip it, and send it to your Javascript. Surprisingly, the Javascript code to read this isn't that complicated (simply DOM manipulations).</p>
2
2009-03-02T13:42:54Z
[ "jquery", "python", "html", "google-app-engine", "dhtml" ]
Differential AJAX updates for HTML table?
602,322
<p>I have a <a href="http://conquer-on-contact.bthomson.com" rel="nofollow">game</a> on Google App Engine that's based on a 25x20 HTML table (the game board). Every 3 seconds the user can "move," which sends an AJAX request to the server, at which time the server rerenders the entire HTML table and sends it to the user.</p> <p>This was easy to write, but it wastes a lot of bandwidth. Are there any libraries, client (preferably jquery) or server-side (must work with GAE), that help send differential instead of full updates for large tables? Usually only 5-10 tiles change on a given reload, so I feel like I could cut bandwidth use by an order of magnitude by sending just those tiles instead of all 500 every 3 seconds.</p> <p>I'm also open to "you idiot, why are you using HTML tables"-type comments if you can suggest a better alternative. For example are there any CSS/DOM manipulation techniques I should be considering instead of using an HTML table? Should I use a table but give each td coordinates for an id (like "12x08") and then use jquery to replace cells by id?</p> <p>A clarification: the tiles are text, not images.</p>
2
2009-03-02T13:17:57Z
603,701
<p>You can model your game board as a multidimensional javascript array:</p> <pre><code>[[x0, x1, x2, x3 ... xn], ..... .....] </code></pre> <p>each entry is an array representing a row. Each cell holds the numerical value of the game piece/square.</p> <p>This model can be the "contract" you send to the server via ajax as JSON. The server calculates the same array and sends it back to the UI. You can render that array into a table, divs or whatever you like. Prototype.js and jQuery make creating dhtml super easy.</p> <p>This array format will be much smaller than a whole HTML response laden with markup. It also gives you freedom to render the board in whatever way you like.</p> <p>You can further compress this format and just send the deltas. For example: save the coordinates of tiles changed by the user and send those to the server:</p> <pre><code>[(x1, y2),.....(xn, yn)] </code></pre> <p>Or you can do it the other way around: send the full model array to the server, and have the server calculate the deltas.</p> <p>Check out Sponty, and watch the ajax traffic every few minutes or so, we do something very similar: <a href="http://www.thesponty.com/stackoverflow" rel="nofollow">http://www.thesponty.com/</a> The client sends the full model to the server, and the server sends the diffs.</p>
2
2009-03-02T19:47:12Z
[ "jquery", "python", "html", "google-app-engine", "dhtml" ]
Evil code from the Python standard library
602,445
<p>So, we have had this: <a href="http://lucumr.pocoo.org/2009/3/1/the-1000-speedup-or-the-stdlib-sucks" rel="nofollow">http://lucumr.pocoo.org/2009/3/1/the-1000-speedup-or-the-stdlib-sucks</a>. It demonstrates a rather bad bug that is probably costing the universe a load of cycles even as we speak. It's fixed now, which is great.</p> <p>So what parts of the standard library have you noticed to be evil?</p> <p>I would expect all the responsible people to match up an answer with a bug report (if suitable) and a patch (if superman).</p>
7
2009-03-02T14:03:39Z
602,460
<p>Never attribute to malice that which can be adequately explained by stupidity.</p>
10
2009-03-02T14:12:17Z
[ "python", "std" ]
Evil code from the Python standard library
602,445
<p>So, we have had this: <a href="http://lucumr.pocoo.org/2009/3/1/the-1000-speedup-or-the-stdlib-sucks" rel="nofollow">http://lucumr.pocoo.org/2009/3/1/the-1000-speedup-or-the-stdlib-sucks</a>. It demonstrates a rather bad bug that is probably costing the universe a load of cycles even as we speak. It's fixed now, which is great.</p> <p>So what parts of the standard library have you noticed to be evil?</p> <p>I would expect all the responsible people to match up an answer with a bug report (if suitable) and a patch (if superman).</p>
7
2009-03-02T14:03:39Z
602,474
<p>The <a href="http://docs.python.org/library/rexec.html" rel="nofollow">rexec</a> module has so many security holes in it that it's almost useless.</p>
3
2009-03-02T14:15:54Z
[ "python", "std" ]
Evil code from the Python standard library
602,445
<p>So, we have had this: <a href="http://lucumr.pocoo.org/2009/3/1/the-1000-speedup-or-the-stdlib-sucks" rel="nofollow">http://lucumr.pocoo.org/2009/3/1/the-1000-speedup-or-the-stdlib-sucks</a>. It demonstrates a rather bad bug that is probably costing the universe a load of cycles even as we speak. It's fixed now, which is great.</p> <p>So what parts of the standard library have you noticed to be evil?</p> <p>I would expect all the responsible people to match up an answer with a bug report (if suitable) and a patch (if superman).</p>
7
2009-03-02T14:03:39Z
602,525
<p>(since this is a different module, placing it in a different answer)</p> <p><a href="http://docs.python.org/library/cgitb.html" rel="nofollow">cgitb</a> has some weird threading issues. See <a href="http://bugs.python.org/issue1665206" rel="nofollow">this bug report</a>.</p>
2
2009-03-02T14:27:51Z
[ "python", "std" ]
How can I use C++ class in Python?
602,580
<p>I have implemented a class in C++. I want to use it with Python. <strong>Please suggest step by step method and elaborate each step.</strong> Somthing like this...</p> <pre><code>class Test{ private: int n; public: Test(int k){ n=k; } void setInt(int k){ n = k; } int getInt(){ return n; } }; </code></pre> <p>Now, in Python </p> <pre><code>&gt;&gt;&gt; T1 = Test(12) &gt;&gt;&gt; T1.getInt() 12 &gt;&gt;&gt; T1.setInt(32) &gt;&gt;&gt; T1.getInt() 32 </code></pre> <p>Please suggest.How can I do this ? NOTE: I would like to know manual way to do that. I don't want any third party library dependency.</p>
27
2009-03-02T14:47:11Z
602,592
<p>I would suggest you try SWIG or sip (KDE/PyQt).</p> <p>SWIG link : <a href="http://www.swig.org/">http://www.swig.org/</a><br /> SIP link: <a href="http://freshmeat.net/projects/python-sip/">http://freshmeat.net/projects/python-sip/</a></p> <p>These can be used to wrap C++ classes and provide a Pythonic interface to them. </p>
6
2009-03-02T14:49:39Z
[ "c++", "python", "class" ]
How can I use C++ class in Python?
602,580
<p>I have implemented a class in C++. I want to use it with Python. <strong>Please suggest step by step method and elaborate each step.</strong> Somthing like this...</p> <pre><code>class Test{ private: int n; public: Test(int k){ n=k; } void setInt(int k){ n = k; } int getInt(){ return n; } }; </code></pre> <p>Now, in Python </p> <pre><code>&gt;&gt;&gt; T1 = Test(12) &gt;&gt;&gt; T1.getInt() 12 &gt;&gt;&gt; T1.setInt(32) &gt;&gt;&gt; T1.getInt() 32 </code></pre> <p>Please suggest.How can I do this ? NOTE: I would like to know manual way to do that. I don't want any third party library dependency.</p>
27
2009-03-02T14:47:11Z
602,594
<p>Look into <a href="http://www.boost.org/doc/libs/1%5F38%5F0/libs/python/doc/index.html">Boost.Python</a>. It's a library to write python modules with C++.</p> <p>Also look into <a href="http://www.swig.org/">SWIG</a> which can also handle modules for other scripting languages. I've used it in the past to write modules for my class and use them within python. Works great.</p> <p>You can do it manually by using the <a href="http://docs.python.org/c-api/">Python/C API</a>, writing the interface yourself. It's pretty lowlevel, but you will gain a lot of additional knowledge of how Python works behind the scene (And you will need it when you use SWIG anyway).</p>
21
2009-03-02T14:49:48Z
[ "c++", "python", "class" ]
How can I use C++ class in Python?
602,580
<p>I have implemented a class in C++. I want to use it with Python. <strong>Please suggest step by step method and elaborate each step.</strong> Somthing like this...</p> <pre><code>class Test{ private: int n; public: Test(int k){ n=k; } void setInt(int k){ n = k; } int getInt(){ return n; } }; </code></pre> <p>Now, in Python </p> <pre><code>&gt;&gt;&gt; T1 = Test(12) &gt;&gt;&gt; T1.getInt() 12 &gt;&gt;&gt; T1.setInt(32) &gt;&gt;&gt; T1.getInt() 32 </code></pre> <p>Please suggest.How can I do this ? NOTE: I would like to know manual way to do that. I don't want any third party library dependency.</p>
27
2009-03-02T14:47:11Z
602,666
<p><a href="https://docs.python.org/2/library/ctypes.html" rel="nofollow">ctypes</a> is good. It is really easy to use, and it comes standard with Python. Unfortunately it can only talk to shared libraries (Unix) or DLLs (Windows) that have a C-style interface, which means you can't directly interface to a C++ object. But you could use a handle system where a handle refers to a particular object.</p> <pre><code>&gt;&gt;&gt; getInt(h) 12 </code></pre> <p>I think that is simple, easy to understand, and doesn't require extra libraries.</p>
8
2009-03-02T15:06:33Z
[ "c++", "python", "class" ]
How to show the output of 'l' in python pdb after every command entered
602,599
<p>I would like to have the output of the python pdb 'l' command printed to the screen after every command I enter in an interactive debugging session.</p> <p>Is there a way to setup python pdb to do this?</p>
4
2009-03-02T14:51:11Z
602,733
<p>';;' allow to separate commands</p> <pre> <code> [crchemist@test tmp]$ python t.py > /home/crchemist/tmp/t.py(7)() -> a() (Pdb) p a ;; l function a at 0xb7e96df4 2 b = 49 + 45 3 v = 'fff' 4 return v 5 6 import pdb; pdb.set_trace() 7 -> a() [EOF] (Pdb) s ;; l --Call-- > /home/crchemist/tmp/t.py(1)a() -> def a(): 1 -> def a(): 2 b = 49 + 45 3 v = 'fff' 4 return v 5 6 import pdb; pdb.set_trace() 7 a() [EOF] (Pdb) s ;; l > /home/crchemist/tmp/t.py(2)a() -> b = 49 + 45 1 def a(): 2 -> b = 49 + 45 3 v = 'fff' 4 return v 5 6 import pdb; pdb.set_trace() 7 a() [EOF] (Pdb) </code> </pre>
2
2009-03-02T15:25:19Z
[ "python", "debugging", "pdb" ]
How to show the output of 'l' in python pdb after every command entered
602,599
<p>I would like to have the output of the python pdb 'l' command printed to the screen after every command I enter in an interactive debugging session.</p> <p>Is there a way to setup python pdb to do this?</p>
4
2009-03-02T14:51:11Z
602,750
<p>One way to do this is to alias your favourite commands to run the command and then l.</p> <p>e.g.</p> <pre><code>(Pdb) alias s step ;; l (Pdb) s &gt; /usr/lib/python2.5/distutils/core.py(14)&lt;module&gt;() -&gt; from types import * 9 # This module should be kept compatible with Python 2.1. 10 11 __revision__ = "$Id: core.py 38672 2005-03-20 22:19:47Z fdrake $" 12 13 import sys, os 14 -&gt; from types import * 15 16 from distutils.debug import DEBUG 17 from distutils.errors import * 18 from distutils.util import grok_environment_error 19 </code></pre> <p>In your ~/.pdbrc you can add the aliases so you have them every time:</p> <pre><code>alias s step ;; l </code></pre>
5
2009-03-02T15:29:38Z
[ "python", "debugging", "pdb" ]
How can I access the current executing module or class name in Python?
602,846
<p>I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code:</p> <p><strong>foo.py:</strong></p> <pre><code>def f(): print __name__ </code></pre> <p><strong>bar.py:</strong></p> <pre><code>from foo import f def b(): f() </code></pre> <p>This obviously does not work as <code>__name__</code> is the name of the module that contains the function. What I would like to be access inside the <code>foo</code> module is the name of the current executing module that is using <code>foo</code>. So in the case above it would be <code>bar</code> but if any other module imported <code>foo</code> I would like <code>foo</code> to dynamically have access to the name of that module.</p> <p><strong>Edit:</strong> The <code>inspect</code> module looks quite promising but it is not exactly what I was looking for. What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module. Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.</p> <p><strong>Edit:</strong> Here is how I am trying to use this. I have two different Django applications that both need to log errors to file. Lets say that they are called "AppOne" and "AppTwo". I also have a place to which I would like to log these files: "<code>/home/hare/app_logs</code>". In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file. However what I would like to do is create a directory under <code>app_logs</code> that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.</p> <p>In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.</p>
15
2009-03-02T15:55:53Z
602,859
<p>I don't believe that's possible since that's out of <code>foo</code>'s scope. foo will only be aware of its internal scope since it may be being called by countless other modules and applications.</p>
2
2009-03-02T15:59:54Z
[ "python", "module" ]
How can I access the current executing module or class name in Python?
602,846
<p>I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code:</p> <p><strong>foo.py:</strong></p> <pre><code>def f(): print __name__ </code></pre> <p><strong>bar.py:</strong></p> <pre><code>from foo import f def b(): f() </code></pre> <p>This obviously does not work as <code>__name__</code> is the name of the module that contains the function. What I would like to be access inside the <code>foo</code> module is the name of the current executing module that is using <code>foo</code>. So in the case above it would be <code>bar</code> but if any other module imported <code>foo</code> I would like <code>foo</code> to dynamically have access to the name of that module.</p> <p><strong>Edit:</strong> The <code>inspect</code> module looks quite promising but it is not exactly what I was looking for. What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module. Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.</p> <p><strong>Edit:</strong> Here is how I am trying to use this. I have two different Django applications that both need to log errors to file. Lets say that they are called "AppOne" and "AppTwo". I also have a place to which I would like to log these files: "<code>/home/hare/app_logs</code>". In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file. However what I would like to do is create a directory under <code>app_logs</code> that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.</p> <p>In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.</p>
15
2009-03-02T15:55:53Z
602,881
<p>I think what you want to use is the <a href="http://docs.python.org/library/inspect.html" rel="nofollow">inspect</a> module, to inspect the python runtime stack. Check out this <a href="http://telin.ugent.be/~slippens/drupal/node/148" rel="nofollow">tutorial</a>. I think it provides an almost exact example of what you want to do.</p>
9
2009-03-02T16:04:33Z
[ "python", "module" ]
How can I access the current executing module or class name in Python?
602,846
<p>I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code:</p> <p><strong>foo.py:</strong></p> <pre><code>def f(): print __name__ </code></pre> <p><strong>bar.py:</strong></p> <pre><code>from foo import f def b(): f() </code></pre> <p>This obviously does not work as <code>__name__</code> is the name of the module that contains the function. What I would like to be access inside the <code>foo</code> module is the name of the current executing module that is using <code>foo</code>. So in the case above it would be <code>bar</code> but if any other module imported <code>foo</code> I would like <code>foo</code> to dynamically have access to the name of that module.</p> <p><strong>Edit:</strong> The <code>inspect</code> module looks quite promising but it is not exactly what I was looking for. What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module. Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.</p> <p><strong>Edit:</strong> Here is how I am trying to use this. I have two different Django applications that both need to log errors to file. Lets say that they are called "AppOne" and "AppTwo". I also have a place to which I would like to log these files: "<code>/home/hare/app_logs</code>". In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file. However what I would like to do is create a directory under <code>app_logs</code> that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.</p> <p>In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.</p>
15
2009-03-02T15:55:53Z
602,967
<p>The "currently executing module" clearly is foo, as that's what contains the function currently running - I think a better description as to what you want is the module of foo's immediate caller (which may itself be foo if you're calling a f() from a function in foo called by a function in bar. How far you want to go up depends on what you want this for.</p> <p>In any case, assuming you want the immediate caller, you can obtain this by walking up the call stack. This can be accomplished by calling <a href="http://docs.python.org/library/sys.html#sys.%5Fgetframe"><code>sys._getframe</code></a>, with the aprropriate number of levels to walk.</p> <pre><code>def f(): caller = sys._getframe(1) # Obtain calling frame print "Called from module", caller.f_globals['__name__'] </code></pre> <p><strong>[Edit]</strong>: Actually, using the <a href="http://docs.python.org/library/inspect.htm">inspect</a> module as suggested above is probably a cleaner way of obtaining the stack frame. The equivalent code is:</p> <pre><code>def f(): caller = inspect.currentframe().f_back print "Called from module", caller.f_globals['__name__'] </code></pre> <p>(sys._getframe is documented as being for internal use - the inspect module is a more reliable API)</p>
10
2009-03-02T16:27:58Z
[ "python", "module" ]
How can I access the current executing module or class name in Python?
602,846
<p>I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code:</p> <p><strong>foo.py:</strong></p> <pre><code>def f(): print __name__ </code></pre> <p><strong>bar.py:</strong></p> <pre><code>from foo import f def b(): f() </code></pre> <p>This obviously does not work as <code>__name__</code> is the name of the module that contains the function. What I would like to be access inside the <code>foo</code> module is the name of the current executing module that is using <code>foo</code>. So in the case above it would be <code>bar</code> but if any other module imported <code>foo</code> I would like <code>foo</code> to dynamically have access to the name of that module.</p> <p><strong>Edit:</strong> The <code>inspect</code> module looks quite promising but it is not exactly what I was looking for. What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module. Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.</p> <p><strong>Edit:</strong> Here is how I am trying to use this. I have two different Django applications that both need to log errors to file. Lets say that they are called "AppOne" and "AppTwo". I also have a place to which I would like to log these files: "<code>/home/hare/app_logs</code>". In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file. However what I would like to do is create a directory under <code>app_logs</code> that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.</p> <p>In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.</p>
15
2009-03-02T15:55:53Z
602,968
<p>It's been a while since I've done python, but I believe that you can get access to the globals and locals of a caller through its <a href="http://docs.python.org/library/traceback.html" rel="nofollow">traceback</a>.</p>
0
2009-03-02T16:28:00Z
[ "python", "module" ]
How can I access the current executing module or class name in Python?
602,846
<p>I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code:</p> <p><strong>foo.py:</strong></p> <pre><code>def f(): print __name__ </code></pre> <p><strong>bar.py:</strong></p> <pre><code>from foo import f def b(): f() </code></pre> <p>This obviously does not work as <code>__name__</code> is the name of the module that contains the function. What I would like to be access inside the <code>foo</code> module is the name of the current executing module that is using <code>foo</code>. So in the case above it would be <code>bar</code> but if any other module imported <code>foo</code> I would like <code>foo</code> to dynamically have access to the name of that module.</p> <p><strong>Edit:</strong> The <code>inspect</code> module looks quite promising but it is not exactly what I was looking for. What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module. Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.</p> <p><strong>Edit:</strong> Here is how I am trying to use this. I have two different Django applications that both need to log errors to file. Lets say that they are called "AppOne" and "AppTwo". I also have a place to which I would like to log these files: "<code>/home/hare/app_logs</code>". In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file. However what I would like to do is create a directory under <code>app_logs</code> that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.</p> <p>In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.</p>
15
2009-03-02T15:55:53Z
603,460
<p>From the comment -- not the question.</p> <p>"I am simply curious to see if what I am trying to do is possible."</p> <p>The answer to "is it possible" is always "yes". Always. Unless your question involves time travel, anti-gravity or perpetual motion. </p> <p>Since the answer is always "yes", your question is ill-formed. The real question is "what's a good way to have my logging module know the name of the client?" or something like that.</p> <p>The answer is "Accept it as a parameter." Don't mess around with inspecting or looking for mysterious globals or other tricks.</p> <p>Just follow the design pattern of logging.getLogger() and use explicitly-named loggers. A common idiom is the following</p> <pre><code>logger= logging.getLogger( __name__ ) </code></pre> <p>That handles almost all log naming perfectly.</p>
26
2009-03-02T18:36:31Z
[ "python", "module" ]
How can I access the current executing module or class name in Python?
602,846
<p>I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code:</p> <p><strong>foo.py:</strong></p> <pre><code>def f(): print __name__ </code></pre> <p><strong>bar.py:</strong></p> <pre><code>from foo import f def b(): f() </code></pre> <p>This obviously does not work as <code>__name__</code> is the name of the module that contains the function. What I would like to be access inside the <code>foo</code> module is the name of the current executing module that is using <code>foo</code>. So in the case above it would be <code>bar</code> but if any other module imported <code>foo</code> I would like <code>foo</code> to dynamically have access to the name of that module.</p> <p><strong>Edit:</strong> The <code>inspect</code> module looks quite promising but it is not exactly what I was looking for. What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module. Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.</p> <p><strong>Edit:</strong> Here is how I am trying to use this. I have two different Django applications that both need to log errors to file. Lets say that they are called "AppOne" and "AppTwo". I also have a place to which I would like to log these files: "<code>/home/hare/app_logs</code>". In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file. However what I would like to do is create a directory under <code>app_logs</code> that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.</p> <p>In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.</p>
15
2009-03-02T15:55:53Z
603,503
<p><code>__file__</code> is the path of current module the call is made.</p>
2
2009-03-02T18:49:32Z
[ "python", "module" ]
How can I access the current executing module or class name in Python?
602,846
<p>I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code:</p> <p><strong>foo.py:</strong></p> <pre><code>def f(): print __name__ </code></pre> <p><strong>bar.py:</strong></p> <pre><code>from foo import f def b(): f() </code></pre> <p>This obviously does not work as <code>__name__</code> is the name of the module that contains the function. What I would like to be access inside the <code>foo</code> module is the name of the current executing module that is using <code>foo</code>. So in the case above it would be <code>bar</code> but if any other module imported <code>foo</code> I would like <code>foo</code> to dynamically have access to the name of that module.</p> <p><strong>Edit:</strong> The <code>inspect</code> module looks quite promising but it is not exactly what I was looking for. What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module. Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.</p> <p><strong>Edit:</strong> Here is how I am trying to use this. I have two different Django applications that both need to log errors to file. Lets say that they are called "AppOne" and "AppTwo". I also have a place to which I would like to log these files: "<code>/home/hare/app_logs</code>". In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file. However what I would like to do is create a directory under <code>app_logs</code> that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.</p> <p>In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.</p>
15
2009-03-02T15:55:53Z
7,810,592
<p>This should work for referencing the current module:</p> <pre><code>import sys sys.modules[__name__] </code></pre>
13
2011-10-18T16:27:55Z
[ "python", "module" ]
python opens text file with a space between every character
603,115
<p>Whenever I try to open a .csv file with the python command <code>fread = open('input.csv', 'r')</code> it always opens the file with spaces between every single character. I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly. Does anyone know why a text file would load like this in python?</p> <p>Thanks.</p> <p><strong>Update</strong></p> <p>Ok, I got it with the help of Jarret Hardie's post</p> <p>this is the code that I used to convert the file to ascii</p> <pre><code>fread = open('input.csv', 'rb').read() mytext = fread.decode('utf-16') mytext = mytext.encode('ascii', 'ignore') fwrite = open('input-ascii.csv', 'wb') fwrite.write(mytext) </code></pre> <p>Thanks!</p>
8
2009-03-02T17:09:38Z
603,122
<p>First of all, use an hex-editor to view the file, see if there is anything irregular about it.</p> <p>Secondly, please post the code you are using.</p>
1
2009-03-02T17:11:52Z
[ "python", "csv", "text-files" ]
python opens text file with a space between every character
603,115
<p>Whenever I try to open a .csv file with the python command <code>fread = open('input.csv', 'r')</code> it always opens the file with spaces between every single character. I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly. Does anyone know why a text file would load like this in python?</p> <p>Thanks.</p> <p><strong>Update</strong></p> <p>Ok, I got it with the help of Jarret Hardie's post</p> <p>this is the code that I used to convert the file to ascii</p> <pre><code>fread = open('input.csv', 'rb').read() mytext = fread.decode('utf-16') mytext = mytext.encode('ascii', 'ignore') fwrite = open('input-ascii.csv', 'wb') fwrite.write(mytext) </code></pre> <p>Thanks!</p>
8
2009-03-02T17:09:38Z
603,135
<p>It did never ocurred to me, but as truppo said, it must be something wrong with the file.</p> <p>Try to open the file in Excel/BrOffice Calc and Save As the file as Csv again.</p> <p>If the problem persists, try a subset of the data: fist 10/last 10/intermediate 10 lines of the file.</p>
0
2009-03-02T17:15:28Z
[ "python", "csv", "text-files" ]
python opens text file with a space between every character
603,115
<p>Whenever I try to open a .csv file with the python command <code>fread = open('input.csv', 'r')</code> it always opens the file with spaces between every single character. I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly. Does anyone know why a text file would load like this in python?</p> <p>Thanks.</p> <p><strong>Update</strong></p> <p>Ok, I got it with the help of Jarret Hardie's post</p> <p>this is the code that I used to convert the file to ascii</p> <pre><code>fread = open('input.csv', 'rb').read() mytext = fread.decode('utf-16') mytext = mytext.encode('ascii', 'ignore') fwrite = open('input-ascii.csv', 'wb') fwrite.write(mytext) </code></pre> <p>Thanks!</p>
8
2009-03-02T17:09:38Z
603,152
<p>Isn't csv a simple txt file with values separated with comma. Just try to open it with a text editor to see if the file is correctly formed.</p>
1
2009-03-02T17:18:54Z
[ "python", "csv", "text-files" ]
python opens text file with a space between every character
603,115
<p>Whenever I try to open a .csv file with the python command <code>fread = open('input.csv', 'r')</code> it always opens the file with spaces between every single character. I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly. Does anyone know why a text file would load like this in python?</p> <p>Thanks.</p> <p><strong>Update</strong></p> <p>Ok, I got it with the help of Jarret Hardie's post</p> <p>this is the code that I used to convert the file to ascii</p> <pre><code>fread = open('input.csv', 'rb').read() mytext = fread.decode('utf-16') mytext = mytext.encode('ascii', 'ignore') fwrite = open('input-ascii.csv', 'wb') fwrite.write(mytext) </code></pre> <p>Thanks!</p>
8
2009-03-02T17:09:38Z
603,157
<p>You might as well upload the file in question to a site like <a href="http://drop.io/" rel="nofollow">http://drop.io/</a> and give us a link.</p>
0
2009-03-02T17:20:43Z
[ "python", "csv", "text-files" ]
python opens text file with a space between every character
603,115
<p>Whenever I try to open a .csv file with the python command <code>fread = open('input.csv', 'r')</code> it always opens the file with spaces between every single character. I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly. Does anyone know why a text file would load like this in python?</p> <p>Thanks.</p> <p><strong>Update</strong></p> <p>Ok, I got it with the help of Jarret Hardie's post</p> <p>this is the code that I used to convert the file to ascii</p> <pre><code>fread = open('input.csv', 'rb').read() mytext = fread.decode('utf-16') mytext = mytext.encode('ascii', 'ignore') fwrite = open('input-ascii.csv', 'wb') fwrite.write(mytext) </code></pre> <p>Thanks!</p>
8
2009-03-02T17:09:38Z
603,162
<p>The file is encoded in some unicode encoding, but you are reading it as ascii. Try to convert the file to ascii before using it in python.</p>
7
2009-03-02T17:22:06Z
[ "python", "csv", "text-files" ]
python opens text file with a space between every character
603,115
<p>Whenever I try to open a .csv file with the python command <code>fread = open('input.csv', 'r')</code> it always opens the file with spaces between every single character. I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly. Does anyone know why a text file would load like this in python?</p> <p>Thanks.</p> <p><strong>Update</strong></p> <p>Ok, I got it with the help of Jarret Hardie's post</p> <p>this is the code that I used to convert the file to ascii</p> <pre><code>fread = open('input.csv', 'rb').read() mytext = fread.decode('utf-16') mytext = mytext.encode('ascii', 'ignore') fwrite = open('input-ascii.csv', 'wb') fwrite.write(mytext) </code></pre> <p>Thanks!</p>
8
2009-03-02T17:09:38Z
603,233
<p>The post by recursive is probably right... the contents of the file are likely encoded with a multi-byte charset. If this is, in fact, the case you can likely read the file in python itself without having to convert it first outside of python.</p> <p>Try something like:</p> <pre><code>fread = open('input.csv', 'rb').read() mytext = fread.decode('utf-16') </code></pre> <p>The 'b' flag ensures the file is read as binary data. You'll need to know (or guess) the original encoding... in this example, I've used utf-16, but YMMV. This will convert the file to unicode. If you truly have a file with multi-byte chars, I don't recommend converting it to ascii as you may end up losing a lot of the characters in the process.</p> <p>EDIT: Thanks for uploading the file. There are two bytes at the front of the file which indicates that it does, indeed, use a wide charset. If you're curious, open the file in a hex editor as some have suggested... you'll see something in the text version like 'I.D.|.' (etc). The dot is the extra byte for each char.</p> <p>The code snippet above seems to work on my machine with that file.</p>
12
2009-03-02T17:36:55Z
[ "python", "csv", "text-files" ]
python opens text file with a space between every character
603,115
<p>Whenever I try to open a .csv file with the python command <code>fread = open('input.csv', 'r')</code> it always opens the file with spaces between every single character. I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly. Does anyone know why a text file would load like this in python?</p> <p>Thanks.</p> <p><strong>Update</strong></p> <p>Ok, I got it with the help of Jarret Hardie's post</p> <p>this is the code that I used to convert the file to ascii</p> <pre><code>fread = open('input.csv', 'rb').read() mytext = fread.decode('utf-16') mytext = mytext.encode('ascii', 'ignore') fwrite = open('input-ascii.csv', 'wb') fwrite.write(mytext) </code></pre> <p>Thanks!</p>
8
2009-03-02T17:09:38Z
603,321
<p>Ok, I got it with the help of Jarret Hardie's post</p> <p>this is the code that I used to convert the file to ascii</p> <pre><code>fread = open('input.csv', 'rb').read() mytext = fread.decode('utf-16') mytext = mytext.encode('ascii', 'ignore') fwrite = open('input-ascii.csv', 'wb') fwrite.write(mytext) </code></pre> <p>Thanks!</p>
1
2009-03-02T17:54:02Z
[ "python", "csv", "text-files" ]
python opens text file with a space between every character
603,115
<p>Whenever I try to open a .csv file with the python command <code>fread = open('input.csv', 'r')</code> it always opens the file with spaces between every single character. I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly. Does anyone know why a text file would load like this in python?</p> <p>Thanks.</p> <p><strong>Update</strong></p> <p>Ok, I got it with the help of Jarret Hardie's post</p> <p>this is the code that I used to convert the file to ascii</p> <pre><code>fread = open('input.csv', 'rb').read() mytext = fread.decode('utf-16') mytext = mytext.encode('ascii', 'ignore') fwrite = open('input-ascii.csv', 'wb') fwrite.write(mytext) </code></pre> <p>Thanks!</p>
8
2009-03-02T17:09:38Z
603,331
<p>Open the file in binary mode, 'rb'. Check it in a HEX Editor and check for null padding '00'. Open the file in something like Scintilla Text Editor to check the characters present in the file.</p>
0
2009-03-02T17:55:56Z
[ "python", "csv", "text-files" ]
python opens text file with a space between every character
603,115
<p>Whenever I try to open a .csv file with the python command <code>fread = open('input.csv', 'r')</code> it always opens the file with spaces between every single character. I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly. Does anyone know why a text file would load like this in python?</p> <p>Thanks.</p> <p><strong>Update</strong></p> <p>Ok, I got it with the help of Jarret Hardie's post</p> <p>this is the code that I used to convert the file to ascii</p> <pre><code>fread = open('input.csv', 'rb').read() mytext = fread.decode('utf-16') mytext = mytext.encode('ascii', 'ignore') fwrite = open('input-ascii.csv', 'wb') fwrite.write(mytext) </code></pre> <p>Thanks!</p>
8
2009-03-02T17:09:38Z
874,253
<p>To read an encoded file, you can simply replace <code>open</code> with <code>codecs.open</code>.</p> <pre><code>fread = codecs.open('input.csv', 'r', 'utf-16') </code></pre>
1
2009-05-17T09:39:21Z
[ "python", "csv", "text-files" ]
python opens text file with a space between every character
603,115
<p>Whenever I try to open a .csv file with the python command <code>fread = open('input.csv', 'r')</code> it always opens the file with spaces between every single character. I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly. Does anyone know why a text file would load like this in python?</p> <p>Thanks.</p> <p><strong>Update</strong></p> <p>Ok, I got it with the help of Jarret Hardie's post</p> <p>this is the code that I used to convert the file to ascii</p> <pre><code>fread = open('input.csv', 'rb').read() mytext = fread.decode('utf-16') mytext = mytext.encode('ascii', 'ignore') fwrite = open('input-ascii.csv', 'wb') fwrite.write(mytext) </code></pre> <p>Thanks!</p>
8
2009-03-02T17:09:38Z
10,708,164
<p>Here's the quick and easy way, esp if python won't parse the input correctly</p> <pre><code>sed 's/ \(.\)/\1/g' </code></pre>
0
2012-05-22T18:48:31Z
[ "python", "csv", "text-files" ]
Finding anchor text when there are tags there
603,199
<p>I want to find the text between a pair of &lt;a&gt; tags that link to a given site</p> <p>Here's the re string that I'm using to find the content:</p> <pre><code>r'''(&lt;a([^&lt;&gt;]*)href=("|')(http://)?(www\.)?%s([^'"]*)("|')([^&lt;&gt;]*)&gt;([^&lt;]*))&lt;/a&gt;''' % our_url </code></pre> <p>The result will be something like this:</p> <pre><code>r'''(&lt;a([^&lt;&gt;]*)href=("|')(http://)?(www\.)?stackoverflow.com([^'"]*)("|')([^&lt;&gt;]*)&gt;([^&lt;]*))&lt;/a&gt;''' </code></pre> <p>This is great for most links but it errors with a link with tags within it. I tried changing the final part of the regex from:</p> <pre><code>([^&lt;]*))&lt;/a&gt;''' </code></pre> <p>to:</p> <pre><code>(.*))&lt;/a&gt;''' </code></pre> <p>But that just got everything on the page after the link, which I don't want. Are there any suggestions on what I can do to solve this?</p>
3
2009-03-02T17:29:43Z
603,211
<p>I would not use a regex - use an HTML parser like <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a>.</p>
2
2009-03-02T17:32:17Z
[ "python", "regex" ]
Finding anchor text when there are tags there
603,199
<p>I want to find the text between a pair of &lt;a&gt; tags that link to a given site</p> <p>Here's the re string that I'm using to find the content:</p> <pre><code>r'''(&lt;a([^&lt;&gt;]*)href=("|')(http://)?(www\.)?%s([^'"]*)("|')([^&lt;&gt;]*)&gt;([^&lt;]*))&lt;/a&gt;''' % our_url </code></pre> <p>The result will be something like this:</p> <pre><code>r'''(&lt;a([^&lt;&gt;]*)href=("|')(http://)?(www\.)?stackoverflow.com([^'"]*)("|')([^&lt;&gt;]*)&gt;([^&lt;]*))&lt;/a&gt;''' </code></pre> <p>This is great for most links but it errors with a link with tags within it. I tried changing the final part of the regex from:</p> <pre><code>([^&lt;]*))&lt;/a&gt;''' </code></pre> <p>to:</p> <pre><code>(.*))&lt;/a&gt;''' </code></pre> <p>But that just got everything on the page after the link, which I don't want. Are there any suggestions on what I can do to solve this?</p>
3
2009-03-02T17:29:43Z
603,216
<p>Do a non greedy search i.e. </p> <pre><code>(.*?) </code></pre>
1
2009-03-02T17:32:35Z
[ "python", "regex" ]
Finding anchor text when there are tags there
603,199
<p>I want to find the text between a pair of &lt;a&gt; tags that link to a given site</p> <p>Here's the re string that I'm using to find the content:</p> <pre><code>r'''(&lt;a([^&lt;&gt;]*)href=("|')(http://)?(www\.)?%s([^'"]*)("|')([^&lt;&gt;]*)&gt;([^&lt;]*))&lt;/a&gt;''' % our_url </code></pre> <p>The result will be something like this:</p> <pre><code>r'''(&lt;a([^&lt;&gt;]*)href=("|')(http://)?(www\.)?stackoverflow.com([^'"]*)("|')([^&lt;&gt;]*)&gt;([^&lt;]*))&lt;/a&gt;''' </code></pre> <p>This is great for most links but it errors with a link with tags within it. I tried changing the final part of the regex from:</p> <pre><code>([^&lt;]*))&lt;/a&gt;''' </code></pre> <p>to:</p> <pre><code>(.*))&lt;/a&gt;''' </code></pre> <p>But that just got everything on the page after the link, which I don't want. Are there any suggestions on what I can do to solve this?</p>
3
2009-03-02T17:29:43Z
603,235
<p>Instead of:</p> <pre><code>[^&lt;&gt;]* </code></pre> <p>Try:</p> <pre><code>((?!&lt;/a).)* </code></pre> <p>In other words, match any character that isn't the start of a <code>&lt;/a</code> sequence.</p>
3
2009-03-02T17:37:13Z
[ "python", "regex" ]
Finding anchor text when there are tags there
603,199
<p>I want to find the text between a pair of &lt;a&gt; tags that link to a given site</p> <p>Here's the re string that I'm using to find the content:</p> <pre><code>r'''(&lt;a([^&lt;&gt;]*)href=("|')(http://)?(www\.)?%s([^'"]*)("|')([^&lt;&gt;]*)&gt;([^&lt;]*))&lt;/a&gt;''' % our_url </code></pre> <p>The result will be something like this:</p> <pre><code>r'''(&lt;a([^&lt;&gt;]*)href=("|')(http://)?(www\.)?stackoverflow.com([^'"]*)("|')([^&lt;&gt;]*)&gt;([^&lt;]*))&lt;/a&gt;''' </code></pre> <p>This is great for most links but it errors with a link with tags within it. I tried changing the final part of the regex from:</p> <pre><code>([^&lt;]*))&lt;/a&gt;''' </code></pre> <p>to:</p> <pre><code>(.*))&lt;/a&gt;''' </code></pre> <p>But that just got everything on the page after the link, which I don't want. Are there any suggestions on what I can do to solve this?</p>
3
2009-03-02T17:29:43Z
604,606
<pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; pattern = re.compile(r'&lt;a.+href=[\'|\"](.+)[\'|\"].*?&gt;(.+)&lt;/a&gt;', re.IGNORECASE) &gt;&gt;&gt; link = '&lt;a href="http://stackoverflow.com/questions/603199/finding-anchor-text-when-there-are-tags-there"&gt;Finding anchor text when there are tags there&lt;/a&gt;' &gt;&gt;&gt; re.match(pattern, link).group(1) 'http://stackoverflow.com/questions/603199/finding-anchor-text-when-there-are-tags-there' &gt;&gt;&gt; re.match(pattern, link).group(2) 'Finding anchor text when there are tags there' </code></pre>
3
2009-03-03T00:13:46Z
[ "python", "regex" ]
Need python lxml syntax help for parsing html
603,287
<p>I am brand new to python, and I need some help with the syntax for finding and iterating through html tags using lxml. Here are the use-cases I am dealing with:</p> <p>HTML file is fairly well formed (but not perfect). Has multiple tables on screen, one containing a set of search results, and one each for a header and footer. Each result row contains a link for the search result detail.</p> <ol> <li><p>I need to find the middle table with the search result rows (this one I was able to figure out):</p> <pre><code> self.mySearchTables = self.mySearchTree.findall(".//table") self.myResultRows = self.mySearchTables[1].findall(".//tr") </code></pre></li> <li><p>I need to find the links contained in this table (this is where I'm getting stuck):</p> <pre><code> for searchRow in self.myResultRows: searchLink = patentRow.findall(".//a") </code></pre> <p>It doesn't seem to actually locate the link elements.</p></li> <li><p>I need the plain text of the link. I imagine it would be something like <code>searchLink.text</code> if I actually got the link elements in the first place.</p></li> </ol> <p>Finally, in the actual API reference for lxml, I wasn't able to find information on the find and the findall calls. I gleaned these from bits of code I found on google. Am I missing something about how to effectively find and iterate over HTML tags using lxml?</p>
16
2009-03-02T17:48:28Z
603,308
<p>Is there a reason you're not using <a href="http://www.crummy.com/software/BeautifulSoup/">Beautiful Soup</a> for this project? It will make dealing with imperfectly formed documents much easier.</p>
5
2009-03-02T17:51:14Z
[ "python", "html-parsing", "lxml" ]
Need python lxml syntax help for parsing html
603,287
<p>I am brand new to python, and I need some help with the syntax for finding and iterating through html tags using lxml. Here are the use-cases I am dealing with:</p> <p>HTML file is fairly well formed (but not perfect). Has multiple tables on screen, one containing a set of search results, and one each for a header and footer. Each result row contains a link for the search result detail.</p> <ol> <li><p>I need to find the middle table with the search result rows (this one I was able to figure out):</p> <pre><code> self.mySearchTables = self.mySearchTree.findall(".//table") self.myResultRows = self.mySearchTables[1].findall(".//tr") </code></pre></li> <li><p>I need to find the links contained in this table (this is where I'm getting stuck):</p> <pre><code> for searchRow in self.myResultRows: searchLink = patentRow.findall(".//a") </code></pre> <p>It doesn't seem to actually locate the link elements.</p></li> <li><p>I need the plain text of the link. I imagine it would be something like <code>searchLink.text</code> if I actually got the link elements in the first place.</p></li> </ol> <p>Finally, in the actual API reference for lxml, I wasn't able to find information on the find and the findall calls. I gleaned these from bits of code I found on google. Am I missing something about how to effectively find and iterate over HTML tags using lxml?</p>
16
2009-03-02T17:48:28Z
603,630
<p>Okay, first, in regards to parsing the HTML: if you follow the recommendation of zweiterlinde and S.Lott at least use the version of <a href="http://lxml.de/elementsoup.html" rel="nofollow">beautifulsoup included with lxml</a>. That way you will also reap the benefit of a nice xpath or css selector interface.</p> <p>However, I personally prefer Ian Bicking's <a href="http://lxml.de/lxmlhtml.html" rel="nofollow">HTML parser included in lxml</a>.</p> <p>Secondly, <code>.find()</code> and <code>.findall()</code> come from lxml trying to be compatible with ElementTree, and those two methods are described in <a href="http://effbot.org/zone/element-xpath.htm" rel="nofollow">XPath Support in ElementTree</a>.</p> <p>Those two functions are fairly easy to use but they are very limited XPath. I recommend trying to use either the full lxml <a href="http://lxml.de/xpathxslt.html#the-xpath-method" rel="nofollow"><code>xpath()</code> method</a> or, if you are already familiar with CSS, using the <a href="http://lxml.de/cssselect.html" rel="nofollow"><code>cssselect()</code> method</a>.</p> <p>Here are some examples, with an HTML string parsed like this:</p> <pre><code>from lxml.html import fromstring mySearchTree = fromstring(your_input_string) </code></pre> <p>Using the css selector class your program would roughly look something like this:</p> <pre><code># Find all 'a' elements inside 'tr' table rows with css selector for a in mySearchTree.cssselect('tr a'): print 'found "%s" link to href "%s"' % (a.text, a.get('href')) </code></pre> <p>The equivalent using xpath method would be:</p> <pre><code># Find all 'a' elements inside 'tr' table rows with xpath for a in mySearchTree.xpath('.//tr/*/a'): print 'found "%s" link to href "%s"' % (a.text, a.get('href')) </code></pre>
27
2009-03-02T19:27:20Z
[ "python", "html-parsing", "lxml" ]
Using PyQT, how do you filter mousePressEvent for a QComboBox with custom list
603,528
<p>I've got a <code>QComboBox</code> with a custom list object. </p> <p><img src="http://i.stack.imgur.com/r71L2.png" alt="Screenshot."></p> <p>The custom list object has a custom <code>mousePressEvent</code> so that when the user click on one of the circles with a +/- (a twisty), the list is expanded/collapsed. </p> <p>When I use the list with the combo box, when the user clicks on a twisty, the list is expanded/collapsed, but the selection is changed, and the list is hidden. How can I filter this so that when the user click on a twisty, the selection is not changed, and the list not hidden.</p> <h2>Additional screenshots</h2> <p>All of the nodes collapsed: <img src="http://i.stack.imgur.com/tz1Qs.png" alt="All nodes collapsed."></p> <p>List hidden: <img src="http://i.stack.imgur.com/sJFuw.png" alt="Screenshot with the list hidden."></p>
3
2009-03-02T18:55:19Z
605,260
<p>Off the top of my head, you could subclass <code>QComboBox</code> and override <code>hideEvent(QHideEvent)</code> (inherited from <code>QWidget</code>)</p> <pre><code>def hideEvent(self, event): if self.OkToHide(): event.accept() else: event.ignore() </code></pre> <p>Your screenshot looks like an interesting use of a combo box, I'm curious as to why you haven't used a <code>TreeView</code> style control instead of a list?</p> <p><strong>Edit (Mar 14 2009):</strong></p> <p>I looked at the Qt source code and it looks like when the keyboard and mouse events are captured, that as soon as qt has decided to emit the <code>"activated(int index)"</code> signal, <code>"hidePopup()"</code> has been called. </p> <p>So apart from rewriting their event filter code, another option is to connect the <code>"activated(int index)"</code> or <code>"highlighted(int index)"</code> signal to a slot that can call <code>"showPopup()"</code> which would re-raise the list items. If you get a nasty disappear/appear paint issue you may have to get Qt to delay the paint events while the popup is visible.</p> <p>Hope that helps!</p>
1
2009-03-03T05:55:00Z
[ "python", "qt", "qt4", "pyqt", "qcombobox" ]
Using PyQT, how do you filter mousePressEvent for a QComboBox with custom list
603,528
<p>I've got a <code>QComboBox</code> with a custom list object. </p> <p><img src="http://i.stack.imgur.com/r71L2.png" alt="Screenshot."></p> <p>The custom list object has a custom <code>mousePressEvent</code> so that when the user click on one of the circles with a +/- (a twisty), the list is expanded/collapsed. </p> <p>When I use the list with the combo box, when the user clicks on a twisty, the list is expanded/collapsed, but the selection is changed, and the list is hidden. How can I filter this so that when the user click on a twisty, the selection is not changed, and the list not hidden.</p> <h2>Additional screenshots</h2> <p>All of the nodes collapsed: <img src="http://i.stack.imgur.com/tz1Qs.png" alt="All nodes collapsed."></p> <p>List hidden: <img src="http://i.stack.imgur.com/sJFuw.png" alt="Screenshot with the list hidden."></p>
3
2009-03-02T18:55:19Z
664,455
<p>QT has a <code>eventFilter</code> that "captures" <code>QEvent.MouseButtonRelease</code>. So what I have done is installed my own <code>eventFilter</code> that filters <code>QEvent.MouseButtonRelease</code> events if the user click on a node. </p> <p>In my list object I have the following method:</p> <pre><code>def mousePressEvent (self, e): self.colapse_expand_click = False if &lt;user clicked node&gt;: colapse_expand_node() e.accept () self.colapse_expand_click = True </code></pre> <p>The <code>mousePressEvent</code> runs before <code>mouseReleaseEvent</code>.</p> <p>Then in the custom combobox, I filter the event:</p> <pre><code>class RevisionSelectorWidget(QtGui.QComboBox): def __init__(self, parent = None): QtGui.QComboBox.__init__(self, parent) self.log_list = RevisionSelectorLogList(self) self.setView(self.log_list) self.log_list.installEventFilter(self) self.log_list.viewport().installEventFilter(self) def eventFilter(self, object, event): if event.type() == QtCore.QEvent.MouseButtonRelease: if self.log_list.colapse_expand_click: return True return False </code></pre>
1
2009-03-19T23:32:48Z
[ "python", "qt", "qt4", "pyqt", "qcombobox" ]
What is the proper way to address permissions?
603,595
<p>I added a new model with one permission, and now I need to add that permission to a few users on the production machine after deploying the code and running syncdb for the new app involved. I haven't found the correct way to do this. The auth docs mention User.user_permissions.add(permission), but never tell me what 'permission' is or the best way to get it.</p>
3
2009-03-02T19:18:05Z
603,620
<p><code>Permission</code> (which lives in <code>django.contrib.auth.models</code>) is a database object. You'll be able to see all of them with <code>Permission.objects.all()</code>. They are created automatically by a post-sync signal for each model (and <a href="http://docs.djangoproject.com/en/dev/topics/auth/#id1" rel="nofollow">as the docs mention</a>, you can also define your own).</p> <p>To assign the permissions to a User, you will first have to get the <code>Permission</code> objects (using <code>Permission.objects.get(*args)</code>), and then you can add it to the User with <code>User.user_permissions.add(permission)</code> as you mentioned.</p> <p>Alternatively, and the easier way if you can do this, is just to use the Django admin site. In the detail page for each user, there is a section relating to permissions. I'm guessing you aren't using these permissions outside of the admin, so that's the only area they will affect. If you want all of your users to have all permissions, you can make them superusers by setting the <code>is_superuser</code> flag on each User to <code>True</code>.</p>
4
2009-03-02T19:25:26Z
[ "python", "django" ]
Using for...else in Python generators
603,641
<p>I'm a big fan of Python's <a href="http://docs.python.org/reference/compound_stmts.html#the-for-statement">for...else syntax</a> - it's surprising how often it's applicable, and how effectively it can simplify code.</p> <p>However, I've not figured out a nice way to use it in a generator, for example:</p> <pre><code>def iterate(i): for value in i: yield value else: print 'i is empty' </code></pre> <p>In the above example, I'd like the <code>print</code> statement to be executed only if <code>i</code> is empty. However, as <code>else</code> only respects <code>break</code> and <code>return</code>, it is always executed, regardless of the length of <code>i</code>.</p> <p>If it's impossible to use <code>for...else</code> in this way, what's the best approach to this so that the <code>print</code> statement is only executed when nothing is yielded?</p>
7
2009-03-02T19:28:09Z
603,651
<p>You're breaking the definition of a generator, which should throw a StopIteration exception when iteration is complete (which is automatically handled by a return statement in a generator function)</p> <p>So:</p> <pre><code>def iterate(i): for value in i: yield value return </code></pre> <p>Best to let the calling code handle the case of an empty iterator:</p> <pre><code>count = 0 for value in iterate(range([])): print value count += 1 else: if count == 0: print "list was empty" </code></pre> <p>Might be a cleaner way of doing the above, but that ought to work fine, and doesn't fall into any of the common 'treating an iterator like a list' traps below.</p>
11
2009-03-02T19:32:18Z
[ "python", "syntax", "for-loop", "generator", "yield" ]
Using for...else in Python generators
603,641
<p>I'm a big fan of Python's <a href="http://docs.python.org/reference/compound_stmts.html#the-for-statement">for...else syntax</a> - it's surprising how often it's applicable, and how effectively it can simplify code.</p> <p>However, I've not figured out a nice way to use it in a generator, for example:</p> <pre><code>def iterate(i): for value in i: yield value else: print 'i is empty' </code></pre> <p>In the above example, I'd like the <code>print</code> statement to be executed only if <code>i</code> is empty. However, as <code>else</code> only respects <code>break</code> and <code>return</code>, it is always executed, regardless of the length of <code>i</code>.</p> <p>If it's impossible to use <code>for...else</code> in this way, what's the best approach to this so that the <code>print</code> statement is only executed when nothing is yielded?</p>
7
2009-03-02T19:28:09Z
603,666
<p>What about simple if-else?</p> <pre><code>def iterate(i): if len(i) == 0: print 'i is empty' else: for value in i: yield value </code></pre>
-2
2009-03-02T19:36:27Z
[ "python", "syntax", "for-loop", "generator", "yield" ]
Using for...else in Python generators
603,641
<p>I'm a big fan of Python's <a href="http://docs.python.org/reference/compound_stmts.html#the-for-statement">for...else syntax</a> - it's surprising how often it's applicable, and how effectively it can simplify code.</p> <p>However, I've not figured out a nice way to use it in a generator, for example:</p> <pre><code>def iterate(i): for value in i: yield value else: print 'i is empty' </code></pre> <p>In the above example, I'd like the <code>print</code> statement to be executed only if <code>i</code> is empty. However, as <code>else</code> only respects <code>break</code> and <code>return</code>, it is always executed, regardless of the length of <code>i</code>.</p> <p>If it's impossible to use <code>for...else</code> in this way, what's the best approach to this so that the <code>print</code> statement is only executed when nothing is yielded?</p>
7
2009-03-02T19:28:09Z
603,691
<p>There are a couple ways of doing this. You could always use the <code>Iterator</code> directly:</p> <pre><code>def iterate(i): try: i_iter = iter(i) next = i_iter.next() except StopIteration: print 'i is empty' return while True: yield next next = i_iter.next() </code></pre> <p>But if you know more about what to expect from the argument <code>i</code>, you can be more concise:</p> <pre><code>def iterate(i): if i: # or if len(i) == 0 for next in i: yield next else: print 'i is empty' raise StopIteration() </code></pre>
5
2009-03-02T19:44:40Z
[ "python", "syntax", "for-loop", "generator", "yield" ]