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
sequence
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
386,770
<p>While at uni we were writing a computer vision system for analysing human behaviour based on video clips. We used python because of the excellent PIL, to speed up development and let us get easy access to the image frames we'd extracted from the video for converting to arrays etc.</p> <p>For 90% of what we wanted it was fine and since the images were reasonably low resolution the speed wasn't bad. However, a few of the processes required some complex pixel-by-pixel computations as well as convolutions which are notoriously slow. For these particular areas we re-wrote the innermost parts of the loops in C and just updated the old Python functions to call the C functions.</p> <p>This gave us the best of both worlds. We had the ease of data access that python provides, which enabled to develop fast, and then the straight-line speed of C for the most intensive computations.</p>
7
2008-12-22T17:12:50Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
386,909
<p>Whenever I find a Python bottleneck, I rewrite that code in C as a Python module.</p> <p>For example, I have some hardware that sends image pixels as 4-byte 0RGB. Converting 8M from 0RGB to RGB in Python takes too long so I rewrote it as a Python module.</p> <p>Writing Python (or other higher level languages) is much faster than writing in C so I use Python until I can't.</p>
5
2008-12-22T18:03:54Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
386,999
<p>Not so far. I work for a company that has a molecular simulation engine and a bunch of programs written in python for processing the large multi-gigabyte datasets. All of our analysis software is now being written in Python because of the huge advantages in development flexibility and time. </p> <p>If something is not fast enough we profile it with cProfile and find the bottlenecks. Usually there are one or two functions which take up 80 or 90% of the runtime. We then take those functions and rewrite them in C, something which Python makes dead easy with its C API. In many cases this results in an order of magnitude or more speedup. Problem gone. We then go on our merry way continuing to write everything else in Python. Rinse and repeat...</p> <p>For entire modules or classes we tend to use Boost.python, it can be a bit of a bear but ultimately works well. If it's just a function or two, we sometimes inline it with scipy.weave if the project is already using scipy.</p>
7
2008-12-22T18:41:19Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
387,988
<p>No, I've never had to rewrite. In fact, I started using Python in Maya 8.5. Before Maya 8, the only scripting language available was the built in MEL (Maya Expression Language). Python is actually faster than the built in language that it wraps.</p> <p>Python's ability to work with complex data types also made it faster because MEL can only store single dimensional arrays (and no pointers). This would require multi-dimensional arrays be faked by either using multiple parallel arrays, or by using slow string concatenation.</p>
1
2008-12-23T02:14:06Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
390,700
<p>This kind of question is likely to start a religious war among language people so let me answer it a little bit differently.</p> <p>For most cases in today's computing environments your choice of programming language should be based on what you can program efficiently, program well and what makes you happy not the performance characteristics of the language. Also, optimization should generally be the last concern when programming any system. </p> <p>The typical python way to do things is to start out writing your program in python and then if you notice the performance suffering profile the application and attempt to optimize the hot-spots in python first. If optimizing the python code still isn't good enough the areas of the code that are weighing you down should be re-written as a python module in C. If even after all of that your program isn't fast enough you can either change languages or look at scaling up in hardware or concurrency.</p> <p>That's the long answer, to answer your question directly; no, python (sometimes with C extensions) has been fast enough for everything I need it to do. The only time I really dip into C is to get access to stuff that donesn't have python bindings.</p> <p>Edit: My background is a python programmer at a large .com where we use python for everything from the front-end of our websites all the way down to all the back-office systems. Python is very much an enterprise-grade language.</p>
4
2008-12-24T03:55:24Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
393,185
<p>A month ago i had this little program written in Python (for work) that analyzes logs. When then number of log files grew, the program begun to be very slow and i thought i could rewrite it in Java.</p> <p>I was very interesting. It took a whole day to migrate the same algorithm from Python to Java. At the end of the day, a few benchmark trials showed me clearly that the Java program was some 20% / 25% slower than its Python counterpart. It was a surprise to me.</p> <p>Writing for the second time the algorithm also showed me that some optimization was possible. So in two hours i completely rewrote the whole thing in Python and it was some 40% faster than the original Python implementation (hence orders of time faster than the Java version I had).</p> <p>So:</p> <ol> <li><p>Python is a slow language but still it can be faster, for certain tasks, that other supposedly faster languages</p></li> <li><p>If you have to spend time writing something in a language whose execution is faster but whose development time is slower (most languages), consider using the same time to analyze the problem, search for libraries, profile and then write better Python code.</p></li> </ol>
1
2008-12-25T20:57:40Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
393,200
<p>I once had to write a pseudo-random number generator for a simulator. I wrote it in Python first, but Python proved to be way too slow; I ended up rewriting it in C, and even that was slow, but not nearly as slow as Python.</p> <p>Luckily, it's fairly easy to bridge Python and C, so I was able to write the PRNG as a C module and still write the rest of the simulator in Python.</p>
1
2008-12-25T21:29:04Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
397,300
<p>The following link provides an on going comparison between a number of computer languages. It should give you an idea of some of Python's strengths and weaknesses across different problem domains.</p> <p><a href="http://shootout.alioth.debian.org/gp4/" rel="nofollow">Computer Language Benchmarks Game </a></p>
1
2008-12-29T07:56:05Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
397,313
<p>I'm in the process of rewriting the Perl program <a href="http://www.openkore.com" rel="nofollow">OpenKore</a> in Python under the name <a href="http://erok.sf.net" rel="nofollow">Erok</a> (reverse of the original <a href="http://kore.sf.net" rel="nofollow">Kore</a>). So far, Python is proving to be an overall better language, especially because of its powerful string parsing functions that don't require the use of regular expressions, which really speeds up a lot of its file parsing.</p>
1
2008-12-29T08:07:11Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
478,872
<p>Adding my $0.02 for the record.</p> <p>My work involves developing numeric models that run over 100's of gigabytes of data. The hard problems are in coming up with a revenue-generating solution quickly (i.e. time-to-market). To be commercially successful the solution also has to <em>execute</em> quickly (compute the solution in minimal amounts of time).</p> <p>For us Python has proven to be an excellent choice to develop solutions for the reasons commonly cited: fast development time, language expressiveness, rich libraries, etc. But to meet the execution speed needs we've adopted the 'Hybrid' approach that several responses have already mentioned. </p> <ol> <li>Using numpy for computationally intense parts. We get within 1.1x to 2.5x the speed of a 'native' C++ solution with numpy with less code, fewer bugs, and shorter development times.</li> <li>Pickling (Python's object serialization) intermediate results to minimize re-computation. The nature of our system requires multiple steps over the same data, so we 'memorize' the results and re-use them where possible.</li> <li>Profiling and choosing better algorithms. It's been said in other responses, but I'll repeat it: we whip-out cProfile and try to replace hot-spots with a better algorithm. Not applicable in all cases.</li> <li>Going to C++. If the above fails then we call a C++ library. We use <a href="http://code.google.com/p/pybindgen/">PyBindGen</a> to write our Python/C++ wrappers. We found it far superior to SWIG, SIP, and Boost.Python as it produces direct Python C API code without an intermediate layer. </li> </ol> <p>Reading this list you might think "What a lot of re-work! I'll just do it in [C/C++/Java/assembler] the first time around and be done with it." </p> <p>Let me put it into perspective. Using Python we were able to produce a working revenue-generating application in 5 weeks that, in other languages, had previously required 3 months for projects of similar scope. This includes the time needed to optimize the Python parts we found to be slow.</p>
14
2009-01-26T04:54:13Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
501,942
<p>I am developing in python for several years now. Recently i had to list all files in a directory and build a struct with filename, size, attributes and modification date. I did this with <code>os.listdir</code> and <code>os.stat</code>. The code was quite fast, but the more entries in the directories, the slower my code became comapred to other filemanagers listing the same directory, so i rewrote the code using SWIG/C++ and was really surprised how much faster the code was. </p>
2
2009-02-02T00:56:30Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
673,767
<p>While implementing a specialized memcache server for a certain datatype, storage backend would be more memory efficient and lookup time could be decreased by bit wise lookup operations (<em>i.e: O(1) lookups</em>).</p> <p>I wrote all the protocol implementation and event driven daemon part with Python within 2 days, giving us enough time to test on functionality and focusing on performance while team was validating protocol conformance and other bits. </p> <p>Given the the tools like <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow">Pyrex</a>, implementing C extensions for Python is next to trivial for any developer a bit experienced in C. I rewrote the <a href="http://en.wikipedia.org/wiki/Radix_tree" rel="nofollow">Radix Tree</a> based storage backend in C and made it a Python module with Pyrex within a day. Memory usage for 475K prefixes went down from 90MB to 8MB. We got a 1200% jump in the query performance.</p> <p>Today, this application is running with <a href="http://code.google.com/p/pyevent/" rel="nofollow">pyevent</a> <em>(Python interface for libevent)</em> and the new storage backend handles 8000 queries per second on a modest single core server, running as a <strong>single process daemon</strong> <em>(thanks to libevent)</em> consuming less than 40MB of memory <em>(including the Python interpreter)</em> while handling 300+ simultaneous connections.</p> <p>That's a project designed and implemented to production quality in less than 5 days. Without Python and Pyrex, it would take longer.</p> <p>We could have troubleshoot the performance problem by just using more powerful servers and switch to a multiprocess/multi-instance model while complicating the code and administration tasks, accompanied with much larger memory footprint. </p> <p>I think you're on the right track to go with Python.</p>
4
2009-03-23T15:12:34Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
1,900,043
<p>I generally don't rewrite to C before I :</p> <ul> <li>profile</li> <li>rewrite with bette algorithms (generally this is enough)</li> <li>rewrite python code with low level performance in mind (but never to the point of having non pythonic / non readable code)</li> <li>spend some time rechecking a library cannot do this (first in stdlib, or an external lib)</li> <li>tried psyco / other implementations (rarely achieves to get a REAL speed boost in my case)</li> </ul> <p>Then sometimes I created a shared library to do heavy matrix computation code (which couldn't be done with numarray) and called it with ctypes : </p> <ul> <li>simple to write/build/test a .so / dll in pure C, </li> <li>simple to encapsulate the C to python function (ie. you don't if you use basic datatypes since ctypes does all the work of calling the right arguments for you) and certainly fast enough then .</li> </ul>
0
2009-12-14T10:09:46Z
[ "python", "performance", "optimization", "rewrite" ]
Python Performance - have you ever had to rewrite in something else?
386,655
<p>Has anyone ever had code in Python, that turned out not to perform fast enough?</p> <p>I mean, you were forced to <em>choose another language</em> because of it?</p> <p>We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.</p> <p>I wanted to see if people had instances where they started out in Python, <strong>but</strong> ended up having to go with something else because of performance.</p> <p>Thanks. </p>
42
2008-12-22T16:23:13Z
3,122,149
<p>Yes, twice:</p> <ul> <li><p>An audio DSP application I wound up completely rewriting in C++ because I couldn't get appropriate performance in Python; I don't consider the Python implementation wasted because it let me prototype the concept very easily, and the C++ port went smoothly because I had a working reference implementaton.</p></li> <li><p>A procedural graphic rendering project, where generating large 2D texture maps in Python was taking a long time; I wrote a C++ DLL and used ctypes/windll to use it from Python.</p></li> </ul>
2
2010-06-25T23:55:49Z
[ "python", "performance", "optimization", "rewrite" ]
Tricky Python string literals in passing parameter to timeit.Timer() function
386,664
<p>I'm having a hard time with the setup statement in Python's timeit.Timer(stmt, setup_stmt). I appreciate any help to get me out of this tricky problem:</p> <p>So my sniplet looks like this:</p> <pre><code>def compare(string1, string2): # compare 2 strings if __name__ = '__main__': str1 = "This string has \n several new lines \n in the middle" str2 = "This string hasn't any new line, but a single quote ('), in the middle" t = timeit.Timer('compare(p1, p2)', "from __main__ import compare; p1=%s, p2=%s" % (str1,str2)) </code></pre> <p>I don't know how to escape the metacharacter in the variable str1, str2 without changing their meaning in the setup statement: </p> <pre><code>"from __main__ import compare; p1=%s, p2=%s" % (str1,str2) </code></pre> <p>I tried various combination but always have the following errors: SyntaxError: can't assign to literal<br /> SyntaxError: EOL while scanning single-quoted string<br /> SyntaxError: invalid syntax</p>
4
2008-12-22T16:25:42Z
386,718
<p>Consider This as an alternative.</p> <pre><code>t = timeit.Timer('compare(p1, p2)', "from __main__ import compare; p1=%r; p2=%r" % (str1,str2)) </code></pre> <p>The <code>%r</code> uses the repr for the string, which Python always quotes and escapes correctly.</p> <p>EDIT: Fixed code by changing a comma to a semicolon; the error is now gone.</p>
5
2008-12-22T16:47:19Z
[ "python", "string-literals", "timeit" ]
Tricky Python string literals in passing parameter to timeit.Timer() function
386,664
<p>I'm having a hard time with the setup statement in Python's timeit.Timer(stmt, setup_stmt). I appreciate any help to get me out of this tricky problem:</p> <p>So my sniplet looks like this:</p> <pre><code>def compare(string1, string2): # compare 2 strings if __name__ = '__main__': str1 = "This string has \n several new lines \n in the middle" str2 = "This string hasn't any new line, but a single quote ('), in the middle" t = timeit.Timer('compare(p1, p2)', "from __main__ import compare; p1=%s, p2=%s" % (str1,str2)) </code></pre> <p>I don't know how to escape the metacharacter in the variable str1, str2 without changing their meaning in the setup statement: </p> <pre><code>"from __main__ import compare; p1=%s, p2=%s" % (str1,str2) </code></pre> <p>I tried various combination but always have the following errors: SyntaxError: can't assign to literal<br /> SyntaxError: EOL while scanning single-quoted string<br /> SyntaxError: invalid syntax</p>
4
2008-12-22T16:25:42Z
387,911
<p>Why bother quoting the strings at all? Just use them directly. ie. change your last line to:</p> <pre><code>t = timeit.Timer('compare(str1, str2)', "from __main__ import compare, str1, str2") </code></pre>
2
2008-12-23T01:14:42Z
[ "python", "string-literals", "timeit" ]
How do I convert part of a python tuple (byte array) into an integer
386,753
<p>I am trying to talk to a device using python. I have been handed a tuple of bytes which contains the storage information. How can I convert the data into the correct values:</p> <p>response = (0, 0, 117, 143, 6)</p> <p>The first 4 values are a 32-bit int telling me how many bytes have been used and the last value is the percentage used.</p> <p>I can access the tuple as response[0] but cannot see how I can get the first 4 values into the int I require.</p>
4
2008-12-22T17:06:00Z
386,763
<p>See <a href="http://stackoverflow.com/questions/5415/">Convert Bytes to Floating Point Numbers in Python</a> </p> <p>You probably want to use the struct module, e.g.</p> <pre><code>import struct response = (0, 0, 117, 143, 6) struct.unpack("&gt;I", ''.join([chr(x) for x in response[:-1]])) </code></pre> <p>Assuming an unsigned int. There may be a better way to do the conversion to unpack, a list comprehension with join was just the first thing that I came up with. </p> <p><strong>EDIT</strong>: See also ΤΖΩΤΖΙΟΥ's comment on this answer regarding endianness as well.</p> <p><strong>EDIT #2</strong>: If you don't mind using the array module as well, here is an alternate method that obviates the need for a list comprehension. Thanks to @<a href="http://stackoverflow.com/questions/386753/how-do-i-convert-part-of-a-python-tuple-byte-array-into-an-integer#386998">JimB</a> for pointing out that unpack can operate on arrays as well.</p> <pre><code>import struct from array import array response = (0, 0, 117, 143, 6) bytes = array('B', response[:-1]) struct.unpack('&gt;I', bytes) </code></pre>
9
2008-12-22T17:10:02Z
[ "python", "tuples" ]
How do I convert part of a python tuple (byte array) into an integer
386,753
<p>I am trying to talk to a device using python. I have been handed a tuple of bytes which contains the storage information. How can I convert the data into the correct values:</p> <p>response = (0, 0, 117, 143, 6)</p> <p>The first 4 values are a 32-bit int telling me how many bytes have been used and the last value is the percentage used.</p> <p>I can access the tuple as response[0] but cannot see how I can get the first 4 values into the int I require.</p>
4
2008-12-22T17:06:00Z
386,830
<p>Would,</p> <blockquote> <p>num = (response[0] &lt;&lt; 24) + (response[1] &lt;&lt; 16) + (response[2] &lt;&lt; 8) + response[3]</p> </blockquote> <p>meet your needs?</p> <p>aid</p>
13
2008-12-22T17:36:02Z
[ "python", "tuples" ]
How do I convert part of a python tuple (byte array) into an integer
386,753
<p>I am trying to talk to a device using python. I have been handed a tuple of bytes which contains the storage information. How can I convert the data into the correct values:</p> <p>response = (0, 0, 117, 143, 6)</p> <p>The first 4 values are a 32-bit int telling me how many bytes have been used and the last value is the percentage used.</p> <p>I can access the tuple as response[0] but cannot see how I can get the first 4 values into the int I require.</p>
4
2008-12-22T17:06:00Z
386,841
<p>OK, You don't specify the endinanness or whether the integer is signed or and it (perhaps) is faster to with the struct module but:</p> <pre><code>b = (8, 1, 0, 0) sum(b[i] &lt;&lt; (i * 8) for i in range(4)) </code></pre>
4
2008-12-22T17:39:55Z
[ "python", "tuples" ]
How do I convert part of a python tuple (byte array) into an integer
386,753
<p>I am trying to talk to a device using python. I have been handed a tuple of bytes which contains the storage information. How can I convert the data into the correct values:</p> <p>response = (0, 0, 117, 143, 6)</p> <p>The first 4 values are a 32-bit int telling me how many bytes have been used and the last value is the percentage used.</p> <p>I can access the tuple as response[0] but cannot see how I can get the first 4 values into the int I require.</p>
4
2008-12-22T17:06:00Z
386,998
<p>You could also make use of the array module</p> <pre><code>import struct from array import array response = (0, 0, 117, 143, 6) a = array('B', response[:4]) struct.unpack('&gt;I', a) (30095L,) </code></pre>
4
2008-12-22T18:41:19Z
[ "python", "tuples" ]
How do I convert part of a python tuple (byte array) into an integer
386,753
<p>I am trying to talk to a device using python. I have been handed a tuple of bytes which contains the storage information. How can I convert the data into the correct values:</p> <p>response = (0, 0, 117, 143, 6)</p> <p>The first 4 values are a 32-bit int telling me how many bytes have been used and the last value is the percentage used.</p> <p>I can access the tuple as response[0] but cannot see how I can get the first 4 values into the int I require.</p>
4
2008-12-22T17:06:00Z
903,377
<p>How about using the map function:</p> <pre><code>a = (0, 0, 117, 143, 6) b = [] map(b.append, a) </code></pre> <p>Also, I don't know if this is you are looking for:</p> <pre><code>response = (0, 0, 117, 143, 6) response[0:4] </code></pre>
0
2009-05-24T08:56:54Z
[ "python", "tuples" ]
How do I convert part of a python tuple (byte array) into an integer
386,753
<p>I am trying to talk to a device using python. I have been handed a tuple of bytes which contains the storage information. How can I convert the data into the correct values:</p> <p>response = (0, 0, 117, 143, 6)</p> <p>The first 4 values are a 32-bit int telling me how many bytes have been used and the last value is the percentage used.</p> <p>I can access the tuple as response[0] but cannot see how I can get the first 4 values into the int I require.</p>
4
2008-12-22T17:06:00Z
5,737,783
<p>This looks like a job for reduce!</p> <p>What you basically need is to, bit-shift a byte at a time, and then add (addition) the next byte in the sequence. </p> <pre><code>a = (0, 0, 117, 143, 6) reduce(lambda x, y: (x&lt;&lt;8) + y, a) 7704326 </code></pre>
3
2011-04-20T23:26:12Z
[ "python", "tuples" ]
Evaluate environment variables into a string
386,934
<p>I have a string representing a path. Because this application is used on Windows, OSX and Linux, we've defined environment variables to properly map volumes from the different file systems. The result is:</p> <pre><code>"$C/test/testing" </code></pre> <p>What I want to do is evaluate the environment variables in the string so that they're replaced by their respective volume names. Is there a specific command I'm missing, or do I have to take os.environ.keys() and manually replace the strings?</p>
24
2008-12-22T18:18:05Z
386,978
<p>Use <a href="http://docs.python.org/library/os.path.html#os.path.expandvars">os.path.expandvars</a> to expand the environment variables in the string, for example:</p> <pre><code>&gt;&gt;&gt; os.path.expandvars('$C/test/testing') '/stackoverflow/test/testing' </code></pre>
41
2008-12-22T18:35:16Z
[ "python", "filesystems", "environment-variables" ]
Using user input to find information in a Mysql database
387,606
<p>I need to design a program using python that will ask the user for a barcode. Then, using this barcode, it will search a mysql to find its corresponding product. </p> <p>I am a bit stuck on how to get started. Does anyone have any tips for me?</p>
0
2008-12-22T22:37:08Z
387,622
<p>A barcode is simply a graphical representation of a series of characters (alphanumeric)</p> <p>So if you have a method for users to enter this code (a barcode scanner), then its just an issue of querying the mysql database for the character string.</p>
1
2008-12-22T22:40:49Z
[ "python", "sql", "user-input" ]
Using user input to find information in a Mysql database
387,606
<p>I need to design a program using python that will ask the user for a barcode. Then, using this barcode, it will search a mysql to find its corresponding product. </p> <p>I am a bit stuck on how to get started. Does anyone have any tips for me?</p>
0
2008-12-22T22:37:08Z
387,694
<p>That is a very ambiguous question. What you want can be done in many ways depending on what you actually want to do.</p> <p>How are your users going to enter the bar code? Are they going to use a bar code scanner? Are they entering the bar code numbers manually? </p> <p>Is this going to run on a desktop/laptop computer or is it going to run on a handheld device? </p> <p>Is the bar code scanner storing the bar codes for later retrieval or is it sending them directly to the computer. Will it send them through a USB cable or wireless?</p>
0
2008-12-22T23:01:49Z
[ "python", "sql", "user-input" ]
Using user input to find information in a Mysql database
387,606
<p>I need to design a program using python that will ask the user for a barcode. Then, using this barcode, it will search a mysql to find its corresponding product. </p> <p>I am a bit stuck on how to get started. Does anyone have any tips for me?</p>
0
2008-12-22T22:37:08Z
387,800
<p>To start with, treat the barcode input as plain old text. </p> <p>It has been quite a while since I worked with barcode scanners, but I doubt they have changed that much, the older ones used to just piggyback on the keyboard input, so from a programming perspective, the net result was a stream of characters in the keyboard buffer, either typed or scanned made no difference. </p> <p>If the device you are targeting differs from that, you will need to write something to deal with that before you get to the database query. </p> <p>If you have one of the devices to play with, plug it in, start notepad, start scanning some barcodes and see what happens.</p>
0
2008-12-22T23:47:58Z
[ "python", "sql", "user-input" ]
Using user input to find information in a Mysql database
387,606
<p>I need to design a program using python that will ask the user for a barcode. Then, using this barcode, it will search a mysql to find its corresponding product. </p> <p>I am a bit stuck on how to get started. Does anyone have any tips for me?</p>
0
2008-12-22T22:37:08Z
393,356
<p>Use <a href="http://mysql-python.sourceforge.net/MySQLdb.html#using-and-extending" rel="nofollow">python-mysql</a>. It is a <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">dbapi-compatible</a> module that lets you talk to the database.</p> <pre><code>import MySQLdb user_input = raw_input("Please enter barcode and press Enter button: ") db = MySQLdb.connect(passwd="moonpie",db="thangs") mycursor = db.cursor() mycursor.execute("""SELECT name, price FROM Product WHERE barcode = %s""", (user_input,)) # calls fetchone until None is returned (no more rows) for row in iter(mycursor.fetchone, None): print row </code></pre> <p>If you want something more high-level, consider using <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> as a layer. It could allow you to do: </p> <pre><code>product = session.query(Product).filter(Product.barcode == user_input).scalar() print product.name, product.price </code></pre>
3
2008-12-26T01:07:53Z
[ "python", "sql", "user-input" ]
Mysql Connection, one or many?
387,619
<p>I'm writing a script in python which basically queries WMI and updates the information in a mysql database. One of those "write something you need" to learn to program exercises.</p> <p>In case something breaks in the middle of the script, for example, the remote computer turns off, it's separated out into functions.</p> <p>Query Some WMI data<br /> Update that to the database<br /> Query Other WMI data<br /> Update that to the database </p> <p>Is it better to open one mysql connection at the beginning and leave it open or close the connection after each update?</p> <p>It seems as though one connection would use less resources. (Although I'm just learning, so this is a complete guess.) However, opening and closing the connection with each update seems more 'neat'. Functions would be more stand alone, rather than depend on code outside that function.</p>
2
2008-12-22T22:40:09Z
387,735
<p>I don't think that there is "better" solution. Its too early to think about resources. And since wmi is quite slow ( in comparison to sql connection ) the db is not an issue.</p> <p>Just make it work. And then make it better.</p> <p>The good thing about working with open connection here, is that the "natural" solution is to use objects and not just functions. So it will be a learning experience( In case you are learning python and not mysql).</p>
2
2008-12-22T23:16:46Z
[ "python", "mysql" ]
Mysql Connection, one or many?
387,619
<p>I'm writing a script in python which basically queries WMI and updates the information in a mysql database. One of those "write something you need" to learn to program exercises.</p> <p>In case something breaks in the middle of the script, for example, the remote computer turns off, it's separated out into functions.</p> <p>Query Some WMI data<br /> Update that to the database<br /> Query Other WMI data<br /> Update that to the database </p> <p>Is it better to open one mysql connection at the beginning and leave it open or close the connection after each update?</p> <p>It seems as though one connection would use less resources. (Although I'm just learning, so this is a complete guess.) However, opening and closing the connection with each update seems more 'neat'. Functions would be more stand alone, rather than depend on code outside that function.</p>
2
2008-12-22T22:40:09Z
387,759
<p>Think for a moment about the following scenario:</p> <pre><code>for dataItem in dataSet: update(dataItem) </code></pre> <p>If you open and close your connection inside of the <em>update</em> function and your <em>dataSet</em> contains a thousand items then you will destroy the performance of your application and ruin any transactional capabilities.</p> <p>A better way would be to open a connection and pass it to the <em>update</em> function. You could even have your <em>update</em> function call a connection manager of sorts. If you intend to perform single updates periodically then open and close your connection around your <em>update</em> function calls.</p> <p>In this way you will be able to use functions to encapsulate your data operations and be able to share a connection between them.</p> <p>However, this approach is not great for performing bulk inserts or updates.</p>
1
2008-12-22T23:26:00Z
[ "python", "mysql" ]
Mysql Connection, one or many?
387,619
<p>I'm writing a script in python which basically queries WMI and updates the information in a mysql database. One of those "write something you need" to learn to program exercises.</p> <p>In case something breaks in the middle of the script, for example, the remote computer turns off, it's separated out into functions.</p> <p>Query Some WMI data<br /> Update that to the database<br /> Query Other WMI data<br /> Update that to the database </p> <p>Is it better to open one mysql connection at the beginning and leave it open or close the connection after each update?</p> <p>It seems as though one connection would use less resources. (Although I'm just learning, so this is a complete guess.) However, opening and closing the connection with each update seems more 'neat'. Functions would be more stand alone, rather than depend on code outside that function.</p>
2
2008-12-22T22:40:09Z
387,932
<p>"However, opening and closing the connection with each update seems more 'neat'. " </p> <p>It's also a huge amount of overhead -- and there's no actual benefit.</p> <p>Creating and disposing of connections is relatively expensive. More importantly, what's the actual reason? How does it improve, simplify, clarify?</p> <p>Generally, most applications have one connection that they use from when they start to when they stop. </p>
6
2008-12-23T01:36:24Z
[ "python", "mysql" ]
Mysql Connection, one or many?
387,619
<p>I'm writing a script in python which basically queries WMI and updates the information in a mysql database. One of those "write something you need" to learn to program exercises.</p> <p>In case something breaks in the middle of the script, for example, the remote computer turns off, it's separated out into functions.</p> <p>Query Some WMI data<br /> Update that to the database<br /> Query Other WMI data<br /> Update that to the database </p> <p>Is it better to open one mysql connection at the beginning and leave it open or close the connection after each update?</p> <p>It seems as though one connection would use less resources. (Although I'm just learning, so this is a complete guess.) However, opening and closing the connection with each update seems more 'neat'. Functions would be more stand alone, rather than depend on code outside that function.</p>
2
2008-12-22T22:40:09Z
389,364
<p>Useful clues in S.Lott's and Igal Serban's answers. I think you should first find out your actual requirements and code accordingly.</p> <p>Just to mention a different strategy; some applications keep a pool of database (or whatever) connections and in case of a transaction just pull one from that pool. It seems rather obvious you just need one connection for this kind of application. But you can still keep a pool of one connection and apply following;</p> <ul> <li>Whenever database transaction is needed the connection is pulled from the pool and returned back at the end.</li> <li>(optional) The connection is expired (and of replaced by a new one) after a certain amount of time.</li> <li>(optional) The connection is expired after a certain amount of usage.</li> <li>(optional) The pool can check (by sending an inexpensive query) if the connection is alive before handing it over the program.</li> </ul> <p>This is somewhat in between <em>single connection</em> and <em>connection per transaction</em> strategies.</p>
0
2008-12-23T16:36:23Z
[ "python", "mysql" ]
What are the steps to make a ModelForm work with a ManyToMany relationship with an intermediary model in Django?
387,686
<ul> <li>I have a <em>Client</em> and <em>Groupe</em> Model.</li> <li>A <em>Client</em> can be part of multiple <em>groups</em>.</li> <li><em>Clients</em> that are part of a group can use its group's free rental rate at anytime but only once. That is where the intermediary model (<em>ClientGroupe</em>) comes in with that extra data.</li> </ul> <p>For now, when I try to save the m2m data, it just dies and says I should use the ClientGroupe Manager...so what's missing?</p> <h2>Here are my models:</h2> <pre><code>class Groupe(models.Model): nom = models.CharField(max_length=1500, blank=True) class Client(models.Model): nom = models.CharField(max_length=450, blank=True) prenom = models.CharField(max_length=450, blank=True) groupes = models.ManyToManyField(Groupe, null = True, blank = True, through='ClientGroupe') class ClientGroupe(models.Model): client = models.ForeignKey(Client) groupe = models.ForeignKey(Groupe) dt = models.DateField(null=True, blank=True) # the date the client is using its group's free rental rate class Meta: db_table = u'clients_groupes' </code></pre> <h2>and here's my view:</h2> <pre><code>def modifier(request, id): client = Client.objects.get(id=id) form = ClientForm(instance = client) dict = { "form": form , "instance" : client } if request.method == "POST": form = ClientForm(request.POST, instance = client) if form.is_valid(): client_mod = form.save() id = client_mod.id return HttpResponseRedirect( "/client/%(id)s/?err=success" % {"id" : id} ) else: return HttpResponseRedirect( "/client/%(id)s/?err=warning" % {"id" : id} ) return render_to_response( "client/modifier.html" , dict , context_instance=RequestContext(request) ) </code></pre> <p><strong>EDIT</strong>:</p> <p>and here's the ClientForm code:</p> <pre><code>class ClientForm(ModelForm): class Meta: model = Client </code></pre> <p><strong>EDIT #2</strong>: here's the error message:</p> <pre><code>AttributeError at /client/445/ Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead. Request Method: POST Request URL: http://localhost/client/445/ Exception Type: AttributeError Exception Value: Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead. Exception Location: C:\Python25\lib\site-packages\django\db\models\fields\related.py in __set__, line 574 Python Executable: C:\xampp\apache\bin\apache.exe Python Version: 2.5.2 </code></pre>
30
2008-12-22T22:58:24Z
478,384
<p>When you save your form, you save Client object. Now if you want to assign client to the group you should do this:</p> <pre><code>clientgroupe = ClientGroupe.objects.create(client=client_instance, groupe=groupe_instance, dt=datetime.datetime.now()) </code></pre> <p>where client_instance and groupe_instance your client and groupe objets.</p>
0
2009-01-25T21:56:02Z
[ "python", "django", "django-models", "django-templates", "django-forms" ]
What are the steps to make a ModelForm work with a ManyToMany relationship with an intermediary model in Django?
387,686
<ul> <li>I have a <em>Client</em> and <em>Groupe</em> Model.</li> <li>A <em>Client</em> can be part of multiple <em>groups</em>.</li> <li><em>Clients</em> that are part of a group can use its group's free rental rate at anytime but only once. That is where the intermediary model (<em>ClientGroupe</em>) comes in with that extra data.</li> </ul> <p>For now, when I try to save the m2m data, it just dies and says I should use the ClientGroupe Manager...so what's missing?</p> <h2>Here are my models:</h2> <pre><code>class Groupe(models.Model): nom = models.CharField(max_length=1500, blank=True) class Client(models.Model): nom = models.CharField(max_length=450, blank=True) prenom = models.CharField(max_length=450, blank=True) groupes = models.ManyToManyField(Groupe, null = True, blank = True, through='ClientGroupe') class ClientGroupe(models.Model): client = models.ForeignKey(Client) groupe = models.ForeignKey(Groupe) dt = models.DateField(null=True, blank=True) # the date the client is using its group's free rental rate class Meta: db_table = u'clients_groupes' </code></pre> <h2>and here's my view:</h2> <pre><code>def modifier(request, id): client = Client.objects.get(id=id) form = ClientForm(instance = client) dict = { "form": form , "instance" : client } if request.method == "POST": form = ClientForm(request.POST, instance = client) if form.is_valid(): client_mod = form.save() id = client_mod.id return HttpResponseRedirect( "/client/%(id)s/?err=success" % {"id" : id} ) else: return HttpResponseRedirect( "/client/%(id)s/?err=warning" % {"id" : id} ) return render_to_response( "client/modifier.html" , dict , context_instance=RequestContext(request) ) </code></pre> <p><strong>EDIT</strong>:</p> <p>and here's the ClientForm code:</p> <pre><code>class ClientForm(ModelForm): class Meta: model = Client </code></pre> <p><strong>EDIT #2</strong>: here's the error message:</p> <pre><code>AttributeError at /client/445/ Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead. Request Method: POST Request URL: http://localhost/client/445/ Exception Type: AttributeError Exception Value: Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead. Exception Location: C:\Python25\lib\site-packages\django\db\models\fields\related.py in __set__, line 574 Python Executable: C:\xampp\apache\bin\apache.exe Python Version: 2.5.2 </code></pre>
30
2008-12-22T22:58:24Z
559,703
<p>You probably need to remove the ManyToMany field from your Client model, or else carefully exclude it from your form. Unfortunately, the default widget for the ManyToMany field cannot populate the ClientGroupe Model properly (even if the missing field, dt, had been set to autonow=True). This is something you'll either need to break out into another form, or handle in your view.</p>
4
2009-02-18T03:15:42Z
[ "python", "django", "django-models", "django-templates", "django-forms" ]
What are the steps to make a ModelForm work with a ManyToMany relationship with an intermediary model in Django?
387,686
<ul> <li>I have a <em>Client</em> and <em>Groupe</em> Model.</li> <li>A <em>Client</em> can be part of multiple <em>groups</em>.</li> <li><em>Clients</em> that are part of a group can use its group's free rental rate at anytime but only once. That is where the intermediary model (<em>ClientGroupe</em>) comes in with that extra data.</li> </ul> <p>For now, when I try to save the m2m data, it just dies and says I should use the ClientGroupe Manager...so what's missing?</p> <h2>Here are my models:</h2> <pre><code>class Groupe(models.Model): nom = models.CharField(max_length=1500, blank=True) class Client(models.Model): nom = models.CharField(max_length=450, blank=True) prenom = models.CharField(max_length=450, blank=True) groupes = models.ManyToManyField(Groupe, null = True, blank = True, through='ClientGroupe') class ClientGroupe(models.Model): client = models.ForeignKey(Client) groupe = models.ForeignKey(Groupe) dt = models.DateField(null=True, blank=True) # the date the client is using its group's free rental rate class Meta: db_table = u'clients_groupes' </code></pre> <h2>and here's my view:</h2> <pre><code>def modifier(request, id): client = Client.objects.get(id=id) form = ClientForm(instance = client) dict = { "form": form , "instance" : client } if request.method == "POST": form = ClientForm(request.POST, instance = client) if form.is_valid(): client_mod = form.save() id = client_mod.id return HttpResponseRedirect( "/client/%(id)s/?err=success" % {"id" : id} ) else: return HttpResponseRedirect( "/client/%(id)s/?err=warning" % {"id" : id} ) return render_to_response( "client/modifier.html" , dict , context_instance=RequestContext(request) ) </code></pre> <p><strong>EDIT</strong>:</p> <p>and here's the ClientForm code:</p> <pre><code>class ClientForm(ModelForm): class Meta: model = Client </code></pre> <p><strong>EDIT #2</strong>: here's the error message:</p> <pre><code>AttributeError at /client/445/ Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead. Request Method: POST Request URL: http://localhost/client/445/ Exception Type: AttributeError Exception Value: Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead. Exception Location: C:\Python25\lib\site-packages\django\db\models\fields\related.py in __set__, line 574 Python Executable: C:\xampp\apache\bin\apache.exe Python Version: 2.5.2 </code></pre>
30
2008-12-22T22:58:24Z
932,234
<p>If you use the save method right now, Django will try to save using the manager (which Django doesn't allow). Unfortunately, the behavior you want is a little bit trickier than what <code>ModelForm</code> does by default. What you need to do is create a <em>formset</em>.</p> <p>First of all, you will need to change the options of your <code>ClientForm</code> so that it doesn't display the <code>groupes</code> attribute.</p> <pre><code>class ClientForm(ModelForm): class Meta: model = Client exclude = ('groupes',) </code></pre> <p>Next, you must change the view to display the formset:</p> <pre><code>from django.forms.models import inlineformset_factory def modifier(request, id): client = Client.objects.get(id=id) form = ClientForm(instance = client) # Create the formset class GroupeFormset = inlineformset_factory(Client, Groupe) # Create the formset formset = GroupeFormset(instance = client) dict = { "form": form , "formset" : formset , "instance" : client } if request.method == "POST": form = ClientForm(request.POST, instance = client) formset = GroupeFormset(request.POST, instance = client) if form.is_valid() and formset.is_valid(): client_mod = form.save() formset.save() id = client_mod.id return HttpResponseRedirect( "/client/%(id)s/?err=success" % {"id" : id} ) else: return HttpResponseRedirect( "/client/%(id)s/?err=warning" % {"id" : id} ) return render_to_response( "client/modifier.html" , dict , context_instance=RequestContext(request) ) </code></pre> <p>And obviously, you must also tweak your template to render the formset.</p> <p>If you need any other advice on formsets, see these articles:</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets">Model formsets</a><br /> <a href="http://docs.djangoproject.com/en/dev/topics/forms/formsets/#topics-forms-formsets">Formsets</a></p>
18
2009-05-31T15:27:30Z
[ "python", "django", "django-models", "django-templates", "django-forms" ]
What are the steps to make a ModelForm work with a ManyToMany relationship with an intermediary model in Django?
387,686
<ul> <li>I have a <em>Client</em> and <em>Groupe</em> Model.</li> <li>A <em>Client</em> can be part of multiple <em>groups</em>.</li> <li><em>Clients</em> that are part of a group can use its group's free rental rate at anytime but only once. That is where the intermediary model (<em>ClientGroupe</em>) comes in with that extra data.</li> </ul> <p>For now, when I try to save the m2m data, it just dies and says I should use the ClientGroupe Manager...so what's missing?</p> <h2>Here are my models:</h2> <pre><code>class Groupe(models.Model): nom = models.CharField(max_length=1500, blank=True) class Client(models.Model): nom = models.CharField(max_length=450, blank=True) prenom = models.CharField(max_length=450, blank=True) groupes = models.ManyToManyField(Groupe, null = True, blank = True, through='ClientGroupe') class ClientGroupe(models.Model): client = models.ForeignKey(Client) groupe = models.ForeignKey(Groupe) dt = models.DateField(null=True, blank=True) # the date the client is using its group's free rental rate class Meta: db_table = u'clients_groupes' </code></pre> <h2>and here's my view:</h2> <pre><code>def modifier(request, id): client = Client.objects.get(id=id) form = ClientForm(instance = client) dict = { "form": form , "instance" : client } if request.method == "POST": form = ClientForm(request.POST, instance = client) if form.is_valid(): client_mod = form.save() id = client_mod.id return HttpResponseRedirect( "/client/%(id)s/?err=success" % {"id" : id} ) else: return HttpResponseRedirect( "/client/%(id)s/?err=warning" % {"id" : id} ) return render_to_response( "client/modifier.html" , dict , context_instance=RequestContext(request) ) </code></pre> <p><strong>EDIT</strong>:</p> <p>and here's the ClientForm code:</p> <pre><code>class ClientForm(ModelForm): class Meta: model = Client </code></pre> <p><strong>EDIT #2</strong>: here's the error message:</p> <pre><code>AttributeError at /client/445/ Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead. Request Method: POST Request URL: http://localhost/client/445/ Exception Type: AttributeError Exception Value: Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead. Exception Location: C:\Python25\lib\site-packages\django\db\models\fields\related.py in __set__, line 574 Python Executable: C:\xampp\apache\bin\apache.exe Python Version: 2.5.2 </code></pre>
30
2008-12-22T22:58:24Z
3,882,808
<pre><code>… if form.is_valid(): client_mod = form.save(commit=False) client_mod.save() for groupe in form.cleaned_data.get('groupes'): clientgroupe = ClientGroupe(client=client_mod, groupe=groupe) clientgroupe.save() … </code></pre>
10
2010-10-07T14:41:20Z
[ "python", "django", "django-models", "django-templates", "django-forms" ]
What are the steps to make a ModelForm work with a ManyToMany relationship with an intermediary model in Django?
387,686
<ul> <li>I have a <em>Client</em> and <em>Groupe</em> Model.</li> <li>A <em>Client</em> can be part of multiple <em>groups</em>.</li> <li><em>Clients</em> that are part of a group can use its group's free rental rate at anytime but only once. That is where the intermediary model (<em>ClientGroupe</em>) comes in with that extra data.</li> </ul> <p>For now, when I try to save the m2m data, it just dies and says I should use the ClientGroupe Manager...so what's missing?</p> <h2>Here are my models:</h2> <pre><code>class Groupe(models.Model): nom = models.CharField(max_length=1500, blank=True) class Client(models.Model): nom = models.CharField(max_length=450, blank=True) prenom = models.CharField(max_length=450, blank=True) groupes = models.ManyToManyField(Groupe, null = True, blank = True, through='ClientGroupe') class ClientGroupe(models.Model): client = models.ForeignKey(Client) groupe = models.ForeignKey(Groupe) dt = models.DateField(null=True, blank=True) # the date the client is using its group's free rental rate class Meta: db_table = u'clients_groupes' </code></pre> <h2>and here's my view:</h2> <pre><code>def modifier(request, id): client = Client.objects.get(id=id) form = ClientForm(instance = client) dict = { "form": form , "instance" : client } if request.method == "POST": form = ClientForm(request.POST, instance = client) if form.is_valid(): client_mod = form.save() id = client_mod.id return HttpResponseRedirect( "/client/%(id)s/?err=success" % {"id" : id} ) else: return HttpResponseRedirect( "/client/%(id)s/?err=warning" % {"id" : id} ) return render_to_response( "client/modifier.html" , dict , context_instance=RequestContext(request) ) </code></pre> <p><strong>EDIT</strong>:</p> <p>and here's the ClientForm code:</p> <pre><code>class ClientForm(ModelForm): class Meta: model = Client </code></pre> <p><strong>EDIT #2</strong>: here's the error message:</p> <pre><code>AttributeError at /client/445/ Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead. Request Method: POST Request URL: http://localhost/client/445/ Exception Type: AttributeError Exception Value: Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead. Exception Location: C:\Python25\lib\site-packages\django\db\models\fields\related.py in __set__, line 574 Python Executable: C:\xampp\apache\bin\apache.exe Python Version: 2.5.2 </code></pre>
30
2008-12-22T22:58:24Z
21,145,127
<p>I'm providing an alternative solution due to issues I encountered with forms_valid not being called:</p> <pre><code>class SplingCreate(forms.ModelForm): class Meta: model = SplingModel fields = ('Link', 'Genres', 'Image', 'ImageURL',) def save(self, commit=True): from django.forms.models import save_instance if self.instance.pk is None: fail_message = 'created' else: fail_message = 'changed' fields = set(self._meta.fields) - set(('Genres',)) instance = save_instance(self, self.instance, fields, fail_message, commit, construct=False) genres = self.cleaned_data.get('Genres') for genre in genres: SplingGenreModel.objects.get_or_create(spling=instance, genre=genre) return instance </code></pre> <p>I've copied the logic from djangos forms/models.py, my field Genres is a manytomany with an intermediary table - I exclude it from the save_instance and then save it separately.</p>
0
2014-01-15T18:11:46Z
[ "python", "django", "django-models", "django-templates", "django-forms" ]
printing a list of persons with more than one home, each home with more than one phone number
387,991
<p>I have a class Person which can have several Homes, each one with one or many Phone numbers.</p> <p>I have defined the classes, but now i am trying to create a view wich list every person, with all its homes and all the phone numbers for each home address... something like:</p> <pre><code>john smith 123 fake str 305-99-8877 305-99-8876 321 oak road 444-98-7654 peter guy 453 north ave... </code></pre> <p>so far i have something like this:</p> <p>(on my views.py)</p> <pre><code>def ViewAll(request): people = Person.objects.all() render_to_response('viewall.html', {'people': people}) </code></pre> <p>(and on my template)</p> <pre><code>{% for guy in people %} {{ guy.name }} {% if person.home_address_set.all %} {{ home_address }} {% for ?????? in ???? %} #print phone numbers in each home {% endfor %} {% endif %} {% endfor %} </code></pre> <p>any idea of how to write the for I'm missing? of course, if there is another way (a better more elegant or efficient way) of doing what I need, I would love to hear it.</p>
1
2008-12-23T02:15:08Z
388,009
<p>You have what appears to be three nested collections: Person, Home, Phone Number.</p> <p>Step 1 - How would you write this in a view function?</p> <pre><code>for p in Person.objects.all(): print "person", p for h in p.home_address_set.all(): print " home", h for ph in h.phone_set.all(): print " phone", ph </code></pre> <p>Don't omit this step. If you can't make it work in a view function, your model is wrong. Take the time to get this part right.</p> <p>Step 2 - Convert this into template syntax.</p> <pre><code>{% for p on people %} {% for h in p.home_address_set.all %} {% fpr ph in h.phone_set.all %} {% endfor %} {% endfor %} {% endfor %} </code></pre> <p>The results should be the same as your view function.</p>
6
2008-12-23T02:25:53Z
[ "python", "django", "django-templates" ]
How to gracefully deal with failed future feature (__future__) imports due to old interpreter version?
388,069
<p>How do you gracefully handle failed future feature imports? If a user is running using Python 2.5 and the first statement in my module is:</p> <pre><code>from __future__ import print_function </code></pre> <p>Compiling this module for Python 2.5 will fail with a:</p> <pre><code> File "__init__.py", line 1 from __future__ import print_function SyntaxError: future feature print_function is not defined </code></pre> <p>I'd like to inform the user that they need to rerun the program with Python >= 2.6 and maybe provide some instructions on how to do so. However, to quote <a href="http://www.python.org/dev/peps/pep-0236/">PEP 236</a>:</p> <blockquote> <p>The only lines that can appear before a future_statement are:</p> <ul> <li>The module docstring (if any).</li> <li>Comments.</li> <li>Blank lines.</li> <li>Other future_statements.</li> </ul> </blockquote> <p>So I can't do something like:</p> <pre><code>import __future__ if hasattr(__future__, 'print_function'): from __future__ import print_function else: raise ImportError('Python &gt;= 2.6 is required') </code></pre> <p>Because it yields:</p> <pre><code> File "__init__.py", line 4 from __future__ import print_function SyntaxError: from __future__ imports must occur at the beginning of the file </code></pre> <p>This snippet from the PEP seems to give hope of doing it inline:</p> <blockquote> <p>Q: I want to wrap future_statements in try/except blocks, so I can use different code depending on which version of Python I'm running. Why can't I?</p> <p>A: Sorry! try/except is a runtime feature; future_statements are primarily compile-time gimmicks, and your try/except happens long after the compiler is done. That is, by the time you do try/except, the semantics in effect for the module are already a done deal. Since the try/except wouldn't accomplish what it <em>looks</em> like it should accomplish, it's simply not allowed. We also want to keep these special statements very easy to find and to recognize.</p> <p>Note that you <em>can</em> import __future__ directly, and use the information in it, along with sys.version_info, to figure out where the release you're running under stands in relation to a given feature's status.</p> </blockquote> <p>Ideas?</p>
68
2008-12-23T03:10:51Z
388,083
<p>"I'd like to inform the user that they need to rerun the program with Python >= 2.6 and maybe provide some instructions on how to do so."</p> <p>Isn't that what a README file is for?</p> <p>Here's your alternative. A "wrapper": a little blob of Python that checks the environment before running your target aop.</p> <p>File: appwrapper.py</p> <pre><code>import sys major, minor, micro, releaselevel, serial = sys.version_info if (major,minor) &lt;= (2,5): # provide advice on getting version 2.6 or higher. sys.exit(2) import app app.main() </code></pre> <hr> <p>What "direct import" means. You can examine the contents of <code>__future__</code>. You're still bound by the fact the a <code>from __future__ import print_function</code> is information to the compiler, but you can poke around before importing the module that does the real work.</p> <pre><code>import __future__, sys if hasattr(__future__, 'print_function'): # Could also check sys.version_info &gt;= __future__. print_function.optional import app app.main() else: print "instructions for upgrading" </code></pre>
57
2008-12-23T03:20:03Z
[ "python", "python-import" ]
How to gracefully deal with failed future feature (__future__) imports due to old interpreter version?
388,069
<p>How do you gracefully handle failed future feature imports? If a user is running using Python 2.5 and the first statement in my module is:</p> <pre><code>from __future__ import print_function </code></pre> <p>Compiling this module for Python 2.5 will fail with a:</p> <pre><code> File "__init__.py", line 1 from __future__ import print_function SyntaxError: future feature print_function is not defined </code></pre> <p>I'd like to inform the user that they need to rerun the program with Python >= 2.6 and maybe provide some instructions on how to do so. However, to quote <a href="http://www.python.org/dev/peps/pep-0236/">PEP 236</a>:</p> <blockquote> <p>The only lines that can appear before a future_statement are:</p> <ul> <li>The module docstring (if any).</li> <li>Comments.</li> <li>Blank lines.</li> <li>Other future_statements.</li> </ul> </blockquote> <p>So I can't do something like:</p> <pre><code>import __future__ if hasattr(__future__, 'print_function'): from __future__ import print_function else: raise ImportError('Python &gt;= 2.6 is required') </code></pre> <p>Because it yields:</p> <pre><code> File "__init__.py", line 4 from __future__ import print_function SyntaxError: from __future__ imports must occur at the beginning of the file </code></pre> <p>This snippet from the PEP seems to give hope of doing it inline:</p> <blockquote> <p>Q: I want to wrap future_statements in try/except blocks, so I can use different code depending on which version of Python I'm running. Why can't I?</p> <p>A: Sorry! try/except is a runtime feature; future_statements are primarily compile-time gimmicks, and your try/except happens long after the compiler is done. That is, by the time you do try/except, the semantics in effect for the module are already a done deal. Since the try/except wouldn't accomplish what it <em>looks</em> like it should accomplish, it's simply not allowed. We also want to keep these special statements very easy to find and to recognize.</p> <p>Note that you <em>can</em> import __future__ directly, and use the information in it, along with sys.version_info, to figure out where the release you're running under stands in relation to a given feature's status.</p> </blockquote> <p>Ideas?</p>
68
2008-12-23T03:10:51Z
3,037,220
<p>A rather hacky but simple method I've used before is to exploit the fact that byte literals were introduced in Python 2.6 and use something like this near the start of the file:</p> <pre><code>b'This module needs Python 2.6 or later. Please do xxx.' </code></pre> <p>This is harmless in Python 2.6 or later, but a <code>SyntaxError</code> in any earlier versions. Anyone trying to compile your file will still get an error, but they also get whatever message you want to give.</p> <p>You might think that as you will have to have this line after your <code>from __future__ import print_function</code> then it will be the import that generates the <code>SyntaxError</code> and you won't get to see the useful error message, but strangely enough the later error takes precedence. I suspect that as the error from the import isn't really a syntax error in itself it isn't raised on the first compilation pass, and so real syntax errors get raised first (but I'm guessing).</p> <p>This might not meet you criteria for being 'graceful', and it is very Python 2.6 specific, but it is quick and easy to do.</p>
46
2010-06-14T12:36:33Z
[ "python", "python-import" ]
How to gracefully deal with failed future feature (__future__) imports due to old interpreter version?
388,069
<p>How do you gracefully handle failed future feature imports? If a user is running using Python 2.5 and the first statement in my module is:</p> <pre><code>from __future__ import print_function </code></pre> <p>Compiling this module for Python 2.5 will fail with a:</p> <pre><code> File "__init__.py", line 1 from __future__ import print_function SyntaxError: future feature print_function is not defined </code></pre> <p>I'd like to inform the user that they need to rerun the program with Python >= 2.6 and maybe provide some instructions on how to do so. However, to quote <a href="http://www.python.org/dev/peps/pep-0236/">PEP 236</a>:</p> <blockquote> <p>The only lines that can appear before a future_statement are:</p> <ul> <li>The module docstring (if any).</li> <li>Comments.</li> <li>Blank lines.</li> <li>Other future_statements.</li> </ul> </blockquote> <p>So I can't do something like:</p> <pre><code>import __future__ if hasattr(__future__, 'print_function'): from __future__ import print_function else: raise ImportError('Python &gt;= 2.6 is required') </code></pre> <p>Because it yields:</p> <pre><code> File "__init__.py", line 4 from __future__ import print_function SyntaxError: from __future__ imports must occur at the beginning of the file </code></pre> <p>This snippet from the PEP seems to give hope of doing it inline:</p> <blockquote> <p>Q: I want to wrap future_statements in try/except blocks, so I can use different code depending on which version of Python I'm running. Why can't I?</p> <p>A: Sorry! try/except is a runtime feature; future_statements are primarily compile-time gimmicks, and your try/except happens long after the compiler is done. That is, by the time you do try/except, the semantics in effect for the module are already a done deal. Since the try/except wouldn't accomplish what it <em>looks</em> like it should accomplish, it's simply not allowed. We also want to keep these special statements very easy to find and to recognize.</p> <p>Note that you <em>can</em> import __future__ directly, and use the information in it, along with sys.version_info, to figure out where the release you're running under stands in relation to a given feature's status.</p> </blockquote> <p>Ideas?</p>
68
2008-12-23T03:10:51Z
7,252,783
<p>Just put a comment on the same line with the <code>"from __future__ import ..."</code>, like this:</p> <pre><code>from __future__ import print_function, division # We require Python 2.6 or later </code></pre> <p>Since Python displays the line containing the error, if you try to run the module with Python 2.5 you'll get a nice, descriptive error:</p> <pre><code> from __future__ import print_function, division # We require Python 2.6 or later SyntaxError: future feature print_function is not defined </code></pre>
38
2011-08-31T05:10:18Z
[ "python", "python-import" ]
Python: flush a buffer before program termination via a finalizer
388,154
<p>I keep a cache of transactions to flush (to persistent storage) on the event of a watermark or object finalization. Since <code>__del__</code> is <a href="http://docs.python.org/reference/datamodel.html?highlight=__del__#object.__del__" rel="nofollow">no longer guaranteed to be called</a> on every object, is the appropriate approach to hook a similar function (or <code>__del__</code> itself) into <code>atexit.register</code> (during initialization)?</p> <p>If I'm not mistaken, this <em>will</em> cause the object to which the method is bound to hang around until program termination. This isn't likely to be a problem, but maybe there's a more elegant solution?</p> <p>Note: I know using <code>__del__</code> is non-ideal because <a href="http://docs.python.org/reference/datamodel.html?highlight=__del__#object.__del__" rel="nofollow">it can cause uncatchable exceptions</a>, but I can't think of another way to do this short of cascading <code>finalize()</code> calls all the way through my program. TIA!</p>
3
2008-12-23T04:15:05Z
388,224
<p>If you have to handle ressources the prefered way is to have an explicit call to a <code>close()</code> or <code>finalize()</code> method. Have a look at the <code>with</code> statement to abstract that. In your case the <code>weakref</code> module might be an option. The cached object can be garbage collected by the system and have their <code>__del__()</code> method called or you finalize them if they are still alive.</p>
4
2008-12-23T05:10:35Z
[ "python", "buffer", "destructor", "finalizer" ]
Python: flush a buffer before program termination via a finalizer
388,154
<p>I keep a cache of transactions to flush (to persistent storage) on the event of a watermark or object finalization. Since <code>__del__</code> is <a href="http://docs.python.org/reference/datamodel.html?highlight=__del__#object.__del__" rel="nofollow">no longer guaranteed to be called</a> on every object, is the appropriate approach to hook a similar function (or <code>__del__</code> itself) into <code>atexit.register</code> (during initialization)?</p> <p>If I'm not mistaken, this <em>will</em> cause the object to which the method is bound to hang around until program termination. This isn't likely to be a problem, but maybe there's a more elegant solution?</p> <p>Note: I know using <code>__del__</code> is non-ideal because <a href="http://docs.python.org/reference/datamodel.html?highlight=__del__#object.__del__" rel="nofollow">it can cause uncatchable exceptions</a>, but I can't think of another way to do this short of cascading <code>finalize()</code> calls all the way through my program. TIA!</p>
3
2008-12-23T04:15:05Z
388,323
<p>I think <code>atexit</code> is the way to go here.</p>
0
2008-12-23T06:51:34Z
[ "python", "buffer", "destructor", "finalizer" ]
Python: flush a buffer before program termination via a finalizer
388,154
<p>I keep a cache of transactions to flush (to persistent storage) on the event of a watermark or object finalization. Since <code>__del__</code> is <a href="http://docs.python.org/reference/datamodel.html?highlight=__del__#object.__del__" rel="nofollow">no longer guaranteed to be called</a> on every object, is the appropriate approach to hook a similar function (or <code>__del__</code> itself) into <code>atexit.register</code> (during initialization)?</p> <p>If I'm not mistaken, this <em>will</em> cause the object to which the method is bound to hang around until program termination. This isn't likely to be a problem, but maybe there's a more elegant solution?</p> <p>Note: I know using <code>__del__</code> is non-ideal because <a href="http://docs.python.org/reference/datamodel.html?highlight=__del__#object.__del__" rel="nofollow">it can cause uncatchable exceptions</a>, but I can't think of another way to do this short of cascading <code>finalize()</code> calls all the way through my program. TIA!</p>
3
2008-12-23T04:15:05Z
388,609
<p>Put the following in a file called <code>destructor.py</code></p> <pre><code>import atexit objects = [] def _destructor(): global objects for obj in objects: obj.destroy() del objects atexit.register(_destructor) </code></pre> <p>now use it this way:</p> <pre><code>import destructor class MyObj(object): def __init__(self): destructor.objects.append(self) # ... other init stuff def destroy(self): # clean up resources here </code></pre>
2
2008-12-23T10:46:14Z
[ "python", "buffer", "destructor", "finalizer" ]
Python: flush a buffer before program termination via a finalizer
388,154
<p>I keep a cache of transactions to flush (to persistent storage) on the event of a watermark or object finalization. Since <code>__del__</code> is <a href="http://docs.python.org/reference/datamodel.html?highlight=__del__#object.__del__" rel="nofollow">no longer guaranteed to be called</a> on every object, is the appropriate approach to hook a similar function (or <code>__del__</code> itself) into <code>atexit.register</code> (during initialization)?</p> <p>If I'm not mistaken, this <em>will</em> cause the object to which the method is bound to hang around until program termination. This isn't likely to be a problem, but maybe there's a more elegant solution?</p> <p>Note: I know using <code>__del__</code> is non-ideal because <a href="http://docs.python.org/reference/datamodel.html?highlight=__del__#object.__del__" rel="nofollow">it can cause uncatchable exceptions</a>, but I can't think of another way to do this short of cascading <code>finalize()</code> calls all the way through my program. TIA!</p>
3
2008-12-23T04:15:05Z
388,959
<p>I would say <code>atexit</code> or try and see if you can refactor the code into being able to be expressed using a <code>with_statement</code> which is in the <code>__future__</code> in 2.5 and in 2.6 by default. 2.5 includes a module contextlib to simplify things a bit. I've done something like this when using Canonical's Storm ORM.</p> <p>from <strong>future</strong> import with_statement</p> <pre><code>@contextlib.contextmanager def start_transaction(db): db.start() yield db.end() with start_transaction(db) as transaction: ... </code></pre> <p>For a non-db case, you could just register the objects to be flushed with a global and then use something similar. The benefit of this approach is that it keeps things explicit.</p>
3
2008-12-23T14:21:43Z
[ "python", "buffer", "destructor", "finalizer" ]
Python: flush a buffer before program termination via a finalizer
388,154
<p>I keep a cache of transactions to flush (to persistent storage) on the event of a watermark or object finalization. Since <code>__del__</code> is <a href="http://docs.python.org/reference/datamodel.html?highlight=__del__#object.__del__" rel="nofollow">no longer guaranteed to be called</a> on every object, is the appropriate approach to hook a similar function (or <code>__del__</code> itself) into <code>atexit.register</code> (during initialization)?</p> <p>If I'm not mistaken, this <em>will</em> cause the object to which the method is bound to hang around until program termination. This isn't likely to be a problem, but maybe there's a more elegant solution?</p> <p>Note: I know using <code>__del__</code> is non-ideal because <a href="http://docs.python.org/reference/datamodel.html?highlight=__del__#object.__del__" rel="nofollow">it can cause uncatchable exceptions</a>, but I can't think of another way to do this short of cascading <code>finalize()</code> calls all the way through my program. TIA!</p>
3
2008-12-23T04:15:05Z
390,177
<p>If you don't need your object to be alive at the time you perform the flush, you could use <a href="http://docs.python.org/library/weakref.html" rel="nofollow">weak references</a></p> <p>This is similar to your proposed solution, but rather than using a real reference, store a list of weak references, with a callback function to perform the flush. This way, the references aren't going to keep those objects alive, and you won't run into any circular garbage problems with <code>__del__</code> methods.</p> <p>You can run through the list of weak references on termination to manually flush any still alive if this needs to be guaranteed done at a certain point.</p>
2
2008-12-23T21:52:16Z
[ "python", "buffer", "destructor", "finalizer" ]
Tidier way of trying to import a module from multiple locations?
388,173
<p>Is there a way to tidy-up the following code, rather than a series of nested try/except statements?</p> <pre><code>try: import simplejson as json except ImportError: try: import json except ImportError: try: from django.utils import simplejson as json except: raise "Requires either simplejson, Python 2.6 or django.utils!" </code></pre>
8
2008-12-23T04:25:09Z
388,360
<p>I found the following function at <a href="http://mail.python.org/pipermail/python-list/2007-May/441896.html" rel="nofollow">http://mail.python.org/pipermail/python-list/2007-May/441896.html</a>. It seems to work quite well, and I'm pretty sure the way its importing won't stomp on any existing imports you might already have.</p> <pre><code>def module_exists(module_name): try: mod = __import__(module_name) except ImportError: return False else: return True if module_exists('simplejson'): import simplejson as json elif module_exists('json'): import json elif module_exists('django.utils'): from django.utils import simplejson as json else: raise ImportError('Requires either simplejson, Python 2.6 or django.utils') </code></pre> <p>I know this seems like more code, but the function is reusable elsewhere if you're doing a lot of this.</p>
6
2008-12-23T07:28:56Z
[ "python", "refactoring", "python-import" ]
Tidier way of trying to import a module from multiple locations?
388,173
<p>Is there a way to tidy-up the following code, rather than a series of nested try/except statements?</p> <pre><code>try: import simplejson as json except ImportError: try: import json except ImportError: try: from django.utils import simplejson as json except: raise "Requires either simplejson, Python 2.6 or django.utils!" </code></pre>
8
2008-12-23T04:25:09Z
388,511
<pre><code>def import_any(*mod_list): res = None for mod in mod_list: try: res = __import__(mod) return res except ImportError: pass raise ImportError("Requires one of " + ', '.join(mod_list)) json = import_any('simplejson', 'json', 'django.utils.simplejson') </code></pre>
3
2008-12-23T09:45:03Z
[ "python", "refactoring", "python-import" ]
Tidier way of trying to import a module from multiple locations?
388,173
<p>Is there a way to tidy-up the following code, rather than a series of nested try/except statements?</p> <pre><code>try: import simplejson as json except ImportError: try: import json except ImportError: try: from django.utils import simplejson as json except: raise "Requires either simplejson, Python 2.6 or django.utils!" </code></pre>
8
2008-12-23T04:25:09Z
388,606
<p>I appreciate the pretty functions for doing this, but the pattern you illustrate in the original question is the most commonly used pattern for this requirement. You can see it used in many open source projects.</p> <p>I suggest you stick with it. Remember "ugly" is not always "bad".</p>
1
2008-12-23T10:45:05Z
[ "python", "refactoring", "python-import" ]
Tidier way of trying to import a module from multiple locations?
388,173
<p>Is there a way to tidy-up the following code, rather than a series of nested try/except statements?</p> <pre><code>try: import simplejson as json except ImportError: try: import json except ImportError: try: from django.utils import simplejson as json except: raise "Requires either simplejson, Python 2.6 or django.utils!" </code></pre>
8
2008-12-23T04:25:09Z
31,116,274
<p>I've come up with a simple alternative that doesn't rely on defining functions:</p> <pre><code># Create a dummy enclosing while True: try: import simplejson as json break except: pass try: import json break except: pass try: from django.utils import simplejson as json break except: pass raise ImportError('Requires either simplejson, Python 2.6 or django.utils') </code></pre> <p>Note, I'm not entirely sure whether it's prettier than the approach using the helper function.</p>
0
2015-06-29T12:53:54Z
[ "python", "refactoring", "python-import" ]
How can i create a lookup in Django?
388,233
<p>I have a Question model &amp; Form, one of the fields in this model is <strong>userid=ForeignKey(User)</strong>, this Works perfectly well on the Question Model, am able to pick the user from a drop down. </p> <p>But kind a tricky when i want to list the question from the model, which is the best way to <strong>lookup</strong> the user name from the Users table? becouse at this point i cant have the dropdown!</p> <p>I want to have a simple thing e.g.</p> <p>Question Title asked by:<strong>lookup user Name</strong> </p>
0
2008-12-23T05:18:07Z
388,296
<p>I find your question vague. If you want to fetch all <code>Question</code> instances that are related to a particular <code>User</code> instance given a <code>user_name</code>, you can do thus:</p> <pre><code>questions = Question.objects.filter( userid__username='user_name' ) </code></pre> <p>If you already have a <code>User</code> instance (held, say, in a variable called <code>user</code>) and would like to fetch all <code>Question</code> objects related to it, you can get those with:</p> <pre><code>questions = user.question_set.all() </code></pre>
0
2008-12-23T06:20:27Z
[ "python", "django", "lookup" ]
How can i create a lookup in Django?
388,233
<p>I have a Question model &amp; Form, one of the fields in this model is <strong>userid=ForeignKey(User)</strong>, this Works perfectly well on the Question Model, am able to pick the user from a drop down. </p> <p>But kind a tricky when i want to list the question from the model, which is the best way to <strong>lookup</strong> the user name from the Users table? becouse at this point i cant have the dropdown!</p> <p>I want to have a simple thing e.g.</p> <p>Question Title asked by:<strong>lookup user Name</strong> </p>
0
2008-12-23T05:18:07Z
389,701
<p>The name of your field (<code>userid</code> instead of <code>user</code>) makes me think that you may be confused about the behavior of Django's <code>ForeignKey</code>.</p> <p>If you define a model like this:</p> <pre><code>from django.contrib.auth.models import User from django.db import models class Question(models.Model): user = models.ForeignKey(User) title = models.CharField(max_length=100) ... def __unicode__(self): return self.title </code></pre> <p>And then instantiate a <code>Question</code> as <code>question</code>:</p> <pre><code>&gt;&gt;&gt; question.user # the `User` instance &lt;User: username&gt; &gt;&gt;&gt; question.user_id # the user's primary key 1 </code></pre> <p>It looks like you may be expecting <code>question.userid</code> to be the user's primary key, rather than what it actually is: the <code>User</code> instance itself. When you access <code>question.userid</code>, a database lookup is performed, but it's done automatically by Django using the value of <code>question.userid_id</code>. I would rename the <code>userid</code> field to <code>user</code> to avoid confusion.</p> <p>With that out of the way, I think what you are trying to do is list the questions along with their associated users. If that's the case, do something like this in your template:</p> <pre><code>&lt;ol&gt; {% for question in questions %} &lt;li&gt;{{ question }} asked by: {{ question.user }}&lt;/li&gt; {% endfor %} &lt;/ol&gt; </code></pre>
5
2008-12-23T18:35:56Z
[ "python", "django", "lookup" ]
How do I use the built in password reset/change views with my own templates
388,800
<p>For example I can point the <code>url '^/accounts/password/reset/$'</code> to <code>django.contrib.auth.views.password_reset</code> with my template filename in the context but I think need to send more context details.</p> <p>I need to know exactly what context to add for each of the password reset and change views.</p>
67
2008-12-23T12:47:32Z
388,811
<p>The <a href="http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.django.contrib.auth.views.password_change" rel="nofollow">documentation</a> says that there only one context variable, <code>form</code>.</p> <p>If you're having trouble with login (which is common), the <a href="http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.views.login" rel="nofollow">documentation</a> says there are three context variables:</p> <ul> <li><code>form</code>: A Form object representing the login form. See the forms documentation for more on Form objects.</li> <li><code>next</code>: The URL to redirect to after successful login. This may contain a query string, too.</li> <li><code>site_name</code>: The name of the current Site, according to the SITE_ID setting.</li> </ul>
1
2008-12-23T12:54:28Z
[ "python", "django", "passwords" ]
How do I use the built in password reset/change views with my own templates
388,800
<p>For example I can point the <code>url '^/accounts/password/reset/$'</code> to <code>django.contrib.auth.views.password_reset</code> with my template filename in the context but I think need to send more context details.</p> <p>I need to know exactly what context to add for each of the password reset and change views.</p>
67
2008-12-23T12:47:32Z
388,858
<p>If you take a look at the sources for <a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py">django.contrib.auth.views.password_reset</a> you'll see that it uses <a href="http://code.djangoproject.com/browser/django/trunk/django/template/__init__.py"><code>RequestContext</code></a>. The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.</p> <p>The b-list has a good <a href="http://www.b-list.org/weblog/2006/jun/14/django-tips-template-context-processors/">introduction to context processors</a>.</p> <p>Edit (I seem to have been confused about what the actual question was):</p> <p>You'll notice that <code>password_reset</code> takes a named parameter called <code>template_name</code>:</p> <pre><code>def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html', email_template_name='registration/password_reset_email.html', password_reset_form=PasswordResetForm, token_generator=default_token_generator, post_reset_redirect=None): </code></pre> <p>Check <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.views.password_reset">password_reset</a> for more information.</p> <p>... thus, with a urls.py like:</p> <pre><code>from django.conf.urls.defaults import * from django.contrib.auth.views import password_reset urlpatterns = patterns('', (r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}), ... ) </code></pre> <p><code>django.contrib.auth.views.password_reset</code> will be called for URLs matching <code>'/accounts/password/reset'</code> with the keyword argument <code>template_name = 'my_templates/password_reset.html'</code>.</p> <p>Otherwise, you don't need to provide any context as the <code>password_reset</code> view takes care of itself. If you want to see what context you have available, you can trigger a <code>TemplateSyntax</code> error and look through the stack trace find the frame with a local variable named <code>context</code>. If you want to modify the context then what I said above about context processors is probably the way to go.</p> <p>In summary: what do you need to do to use your own template? Provide a <code>template_name</code> keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple.</p>
74
2008-12-23T13:21:11Z
[ "python", "django", "passwords" ]
How do I use the built in password reset/change views with my own templates
388,800
<p>For example I can point the <code>url '^/accounts/password/reset/$'</code> to <code>django.contrib.auth.views.password_reset</code> with my template filename in the context but I think need to send more context details.</p> <p>I need to know exactly what context to add for each of the password reset and change views.</p>
67
2008-12-23T12:47:32Z
389,679
<p>You just need to wrap the existing functions and pass in the template you want. For example:</p> <pre><code>from django.contrib.auth.views import password_reset def my_password_reset(request, template_name='path/to/my/template'): return password_reset(request, template_name) </code></pre> <p>To see this just have a look at the function declartion of the built in views:</p> <p><a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py#L74">http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py#L74</a></p>
9
2008-12-23T18:27:06Z
[ "python", "django", "passwords" ]
How do I use the built in password reset/change views with my own templates
388,800
<p>For example I can point the <code>url '^/accounts/password/reset/$'</code> to <code>django.contrib.auth.views.password_reset</code> with my template filename in the context but I think need to send more context details.</p> <p>I need to know exactly what context to add for each of the password reset and change views.</p>
67
2008-12-23T12:47:32Z
14,868,595
<p>Strongly recommend this article.</p> <p>I just plugged it in and it worked</p> <p><a href="http://garmoncheg.blogspot.com.au/2012/07/django-resetting-passwords-with.html">http://garmoncheg.blogspot.com.au/2012/07/django-resetting-passwords-with.html</a></p>
22
2013-02-14T05:52:07Z
[ "python", "django", "passwords" ]
How do I use the built in password reset/change views with my own templates
388,800
<p>For example I can point the <code>url '^/accounts/password/reset/$'</code> to <code>django.contrib.auth.views.password_reset</code> with my template filename in the context but I think need to send more context details.</p> <p>I need to know exactly what context to add for each of the password reset and change views.</p>
67
2008-12-23T12:47:32Z
15,203,487
<p>I was using this two lines in the url and the template from the admin what i was changing to my need</p> <pre><code>url(r'^change-password/$', 'django.contrib.auth.views.password_change', { 'template_name': 'password_change_form.html'}, name="password-change"), url(r'^change-password-done/$', 'django.contrib.auth.views.password_change_done', { 'template_name': 'password_change_done.html' }, name="password-change-done") </code></pre>
1
2013-03-04T14:11:37Z
[ "python", "django", "passwords" ]
How do I use the built in password reset/change views with my own templates
388,800
<p>For example I can point the <code>url '^/accounts/password/reset/$'</code> to <code>django.contrib.auth.views.password_reset</code> with my template filename in the context but I think need to send more context details.</p> <p>I need to know exactly what context to add for each of the password reset and change views.</p>
67
2008-12-23T12:47:32Z
16,193,133
<p>You can do the following:</p> <ol> <li>add to your urlpatterns (r'^/accounts/password/reset/$', password_reset)</li> <li>put your template in '/templates/registration/password_reset_form.html'</li> <li>make your app come before 'django.contrib.auth' in INSTALLED_APPS</li> </ol> <p>Explanation:</p> <p>When the templates are loaded, they are searched in your INSTALLED_APPS variable in settings.py . The order is dictated by the definition's rank in INSTALLED_APPS, so since your app come before 'django.contrib.auth' your template were loaded (reference: <a href="https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.app_directories.Loader">https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.app_directories.Loader</a>).</p> <p>Motivation of approach:</p> <ol> <li>I want be more dry and don't repeat for any view(defined by django) the template name (they are already defined in django)</li> <li>I want a smallest url.py</li> </ol>
5
2013-04-24T13:20:44Z
[ "python", "django", "passwords" ]
Trouble with encoding in emails
389,398
<p>I have a little python script that pulls emails from a POP mail address and dumps them into a file (one file one email)</p> <p>Then a PHP script runs through the files and displays them.</p> <p>I am having an issue with ISO-8859-1 (Latin-1) encoded email</p> <p>Here's an example of the text i get: =?iso-8859-1?Q?G=EDsli_Karlsson?= and Sj=E1um hva=F0 =F3li er kl=E1r J</p> <p>The way i pull emails is this code.</p> <pre><code>pop = poplib.POP3(server) mail_list = pop.list()[1] for m in mail_list: mno, size = m.split() lines = pop.retr(mno)[1] file = StringIO.StringIO("\r\n".join(lines)) msg = rfc822.Message(file) body = file.readlines() f = open(str(random.randint(1,100)) + ".email", "w") f.write(msg["From"] + "\n") f.write(msg["Subject"] + "\n") f.write(msg["Date"] + "\n") for b in body: f.write(b) </code></pre> <p>I have tried probably all combinations of encode / decode within python and php.</p>
1
2008-12-23T16:46:47Z
389,408
<p>That's MIME content, and that's how the email actually looks like, not a bug somewhere. You have to use a MIME decoding library (or decode it yourself manually) on the PHP side of things (which, if I understood correctly, is the one acting as email renderer).</p> <p>In Python you'd use <a href="http://docs.python.org/library/mimetools.html" rel="nofollow">mimetools</a>. In PHP, I'm not sure. It seems the Zend framework has a MIME parser somewhere, and there are probably zillions of snippets floating around.</p> <p><a href="http://en.wikipedia.org/wiki/MIME#Encoded-Word" rel="nofollow">http://en.wikipedia.org/wiki/MIME#Encoded-Word</a></p>
0
2008-12-23T16:50:58Z
[ "python", "email", "encoding" ]
Trouble with encoding in emails
389,398
<p>I have a little python script that pulls emails from a POP mail address and dumps them into a file (one file one email)</p> <p>Then a PHP script runs through the files and displays them.</p> <p>I am having an issue with ISO-8859-1 (Latin-1) encoded email</p> <p>Here's an example of the text i get: =?iso-8859-1?Q?G=EDsli_Karlsson?= and Sj=E1um hva=F0 =F3li er kl=E1r J</p> <p>The way i pull emails is this code.</p> <pre><code>pop = poplib.POP3(server) mail_list = pop.list()[1] for m in mail_list: mno, size = m.split() lines = pop.retr(mno)[1] file = StringIO.StringIO("\r\n".join(lines)) msg = rfc822.Message(file) body = file.readlines() f = open(str(random.randint(1,100)) + ".email", "w") f.write(msg["From"] + "\n") f.write(msg["Subject"] + "\n") f.write(msg["Date"] + "\n") for b in body: f.write(b) </code></pre> <p>I have tried probably all combinations of encode / decode within python and php.</p>
1
2008-12-23T16:46:47Z
389,413
<p>Until very recently, plain Latin-N or utf-N were no allowed in headers which means that they would get to be encoded by a method described at first in <a href="http://www.faqs.org/rfcs/rfc1522.html" rel="nofollow">RFC-1522</a> but it has been superseded later. Accents are encoded either in quoted-printable or in Base64 and it is indicated by the ?Q? (or ?B? for Base64). You'll have to decode them. Oh and space is encoded as "_". See <a href="http://en.wikipedia.org/wiki/MIME" rel="nofollow">Wikipedia</a>.</p>
1
2008-12-23T16:53:22Z
[ "python", "email", "encoding" ]
Trouble with encoding in emails
389,398
<p>I have a little python script that pulls emails from a POP mail address and dumps them into a file (one file one email)</p> <p>Then a PHP script runs through the files and displays them.</p> <p>I am having an issue with ISO-8859-1 (Latin-1) encoded email</p> <p>Here's an example of the text i get: =?iso-8859-1?Q?G=EDsli_Karlsson?= and Sj=E1um hva=F0 =F3li er kl=E1r J</p> <p>The way i pull emails is this code.</p> <pre><code>pop = poplib.POP3(server) mail_list = pop.list()[1] for m in mail_list: mno, size = m.split() lines = pop.retr(mno)[1] file = StringIO.StringIO("\r\n".join(lines)) msg = rfc822.Message(file) body = file.readlines() f = open(str(random.randint(1,100)) + ".email", "w") f.write(msg["From"] + "\n") f.write(msg["Subject"] + "\n") f.write(msg["Date"] + "\n") for b in body: f.write(b) </code></pre> <p>I have tried probably all combinations of encode / decode within python and php.</p>
1
2008-12-23T16:46:47Z
390,688
<p>You can use the python email library (python 2.5+) to avoid these problems:</p> <pre><code>import email import poplib import random from cStringIO import StringIO from email.generator import Generator pop = poplib.POP3(server) mail_count = len(pop.list()[1]) for message_num in xrange(mail_count): message = "\r\n".join(pop.retr(message_num)[1]) message = email.message_from_string(message) out_file = StringIO() message_gen = Generator(out_file, mangle_from_=False, maxheaderlen=60) message_gen.flatten(message) message_text = out_file.getvalue() filename = "%s.email" % random.randint(1,100) email_file = open(filename, "w") email_file.write(message_text) email_file.close() </code></pre> <p>This code will get all the messages from your server and turn them into Python message objects then flatten them out into strings again for writing to the file. By using the email package from the Python standard library MIME encoding and decoding issues should be handled for you.</p> <p>DISCLAIMER: I have not tested that code, but it should work just fine.</p>
3
2008-12-24T03:39:06Z
[ "python", "email", "encoding" ]
Trouble with encoding in emails
389,398
<p>I have a little python script that pulls emails from a POP mail address and dumps them into a file (one file one email)</p> <p>Then a PHP script runs through the files and displays them.</p> <p>I am having an issue with ISO-8859-1 (Latin-1) encoded email</p> <p>Here's an example of the text i get: =?iso-8859-1?Q?G=EDsli_Karlsson?= and Sj=E1um hva=F0 =F3li er kl=E1r J</p> <p>The way i pull emails is this code.</p> <pre><code>pop = poplib.POP3(server) mail_list = pop.list()[1] for m in mail_list: mno, size = m.split() lines = pop.retr(mno)[1] file = StringIO.StringIO("\r\n".join(lines)) msg = rfc822.Message(file) body = file.readlines() f = open(str(random.randint(1,100)) + ".email", "w") f.write(msg["From"] + "\n") f.write(msg["Subject"] + "\n") f.write(msg["Date"] + "\n") for b in body: f.write(b) </code></pre> <p>I have tried probably all combinations of encode / decode within python and php.</p>
1
2008-12-23T16:46:47Z
391,031
<p>That's the MIME encoding of headers, <a href="http://www.ietf.org/rfc/rfc2047.txt" rel="nofollow">RFC 2047</a>. Here is how to decode it in Python:</p> <pre><code>import email.Header import sys header_and_encoding = email.Header.decode_header(sys.stdin.readline()) for part in header_and_encoding: if part[1] is None: print part[0], else: upart = (part[0]).decode(part[1]) print upart.encode('latin-1'), print </code></pre> <p>More detailed explanations (in French) in <a href="http://www.bortzmeyer.org/decoder-en-tetes-courrier.html" rel="nofollow">http://www.bortzmeyer.org/decoder-en-tetes-courrier.html</a></p>
2
2008-12-24T08:44:28Z
[ "python", "email", "encoding" ]
Trouble with encoding in emails
389,398
<p>I have a little python script that pulls emails from a POP mail address and dumps them into a file (one file one email)</p> <p>Then a PHP script runs through the files and displays them.</p> <p>I am having an issue with ISO-8859-1 (Latin-1) encoded email</p> <p>Here's an example of the text i get: =?iso-8859-1?Q?G=EDsli_Karlsson?= and Sj=E1um hva=F0 =F3li er kl=E1r J</p> <p>The way i pull emails is this code.</p> <pre><code>pop = poplib.POP3(server) mail_list = pop.list()[1] for m in mail_list: mno, size = m.split() lines = pop.retr(mno)[1] file = StringIO.StringIO("\r\n".join(lines)) msg = rfc822.Message(file) body = file.readlines() f = open(str(random.randint(1,100)) + ".email", "w") f.write(msg["From"] + "\n") f.write(msg["Subject"] + "\n") f.write(msg["Date"] + "\n") for b in body: f.write(b) </code></pre> <p>I have tried probably all combinations of encode / decode within python and php.</p>
1
2008-12-23T16:46:47Z
397,621
<p>There is a better way to do this, but this is what i ended up with. Thanks for your help guys.</p> <pre><code>import poplib, quopri import random, md5 import sys, rfc822, StringIO import email from email.Generator import Generator user = "[email protected]" password = "password" server = "mail.example.com" # connects try: pop = poplib.POP3(server) except: print "Error connecting to server" sys.exit(-1) # user auth try: print pop.user(user) print pop.pass_(password) except: print "Authentication error" sys.exit(-2) # gets the mail list mail_list = pop.list()[1] for m in mail_list: mno, size = m.split() message = "\r\n".join(pop.retr(mno)[1]) message = email.message_from_string(message) # uses the email flatten out_file = StringIO.StringIO() message_gen = Generator(out_file, mangle_from_=False, maxheaderlen=60) message_gen.flatten(message) message_text = out_file.getvalue() # fixes mime encoding issues (for display within html) clean_text = quopri.decodestring(message_text) msg = email.message_from_string(clean_text) # finds the last body (when in mime multipart, html is the last one) for part in msg.walk(): if part.get_content_type(): body = part.get_payload(decode=True) filename = "%s.email" % random.randint(1,100) email_file = open(filename, "w") email_file.write(msg["From"] + "\n") email_file.write(msg["Return-Path"] + "\n") email_file.write(msg["Subject"] + "\n") email_file.write(msg["Date"] + "\n") email_file.write(body) email_file.close() pop.quit() sys.exit() </code></pre>
2
2008-12-29T12:18:41Z
[ "python", "email", "encoding" ]
Producing documentation for Python classes
389,688
<p>I'm about to start a project where I will be the only one doing actual code and two less experienced programmers (scary to think of myself as experienced!) will be watching and making suggestions on the program in general.</p> <p>Is there a good (free) system that I can use to provide documentation for classes and functions based on the code I've written? It'd likely help them a lot in getting to grips with the structure of the data.</p>
11
2008-12-23T18:30:53Z
389,704
<p>I have used <a href="http://epydoc.sourceforge.net/">epydoc</a> to generate documentation for Python modules from embedded docstrings. It's pretty easy to use and generates nice looking output in multiple formats.</p>
12
2008-12-23T18:37:06Z
[ "python", "data-structures", "documentation" ]
Producing documentation for Python classes
389,688
<p>I'm about to start a project where I will be the only one doing actual code and two less experienced programmers (scary to think of myself as experienced!) will be watching and making suggestions on the program in general.</p> <p>Is there a good (free) system that I can use to provide documentation for classes and functions based on the code I've written? It'd likely help them a lot in getting to grips with the structure of the data.</p>
11
2008-12-23T18:30:53Z
389,706
<p>python.org is now using <a href="http://sphinx.pocoo.org/" rel="nofollow">sphinx</a> for it's documentation.</p> <p>I personally like the output of sphinx over epydoc. I also feel the restructured text is easier to read in the docstrings than the epydoc markup.</p>
11
2008-12-23T18:37:36Z
[ "python", "data-structures", "documentation" ]
Producing documentation for Python classes
389,688
<p>I'm about to start a project where I will be the only one doing actual code and two less experienced programmers (scary to think of myself as experienced!) will be watching and making suggestions on the program in general.</p> <p>Is there a good (free) system that I can use to provide documentation for classes and functions based on the code I've written? It'd likely help them a lot in getting to grips with the structure of the data.</p>
11
2008-12-23T18:30:53Z
389,711
<p>See answers to <a href="http://stackoverflow.com/questions/58622/can-i-document-python-code-with-doxygen-and-does-it-make-sense">can-i-document-python-code-with-doxygen-and-does-it-make-sense</a>, especially those mentioning <a href="http://epydoc.sourceforge.net/" rel="nofollow">Epydoc</a> and <a href="http://codespeak.net/~mwh/pydoctor/" rel="nofollow">pydoctor</a>.</p>
2
2008-12-23T18:38:30Z
[ "python", "data-structures", "documentation" ]
Producing documentation for Python classes
389,688
<p>I'm about to start a project where I will be the only one doing actual code and two less experienced programmers (scary to think of myself as experienced!) will be watching and making suggestions on the program in general.</p> <p>Is there a good (free) system that I can use to provide documentation for classes and functions based on the code I've written? It'd likely help them a lot in getting to grips with the structure of the data.</p>
11
2008-12-23T18:30:53Z
390,678
<p><a href="http://sphinx.pocoo.org/" rel="nofollow">Sphinx</a> can be useful for generating very verbose and informative docs that go above and beyond what simple API docs give you. However in many cases you'll be better served to use a wiki for these kind of documents. Also consider writing functional tests which demonstrate the usage of your code instead of documenting in words how to use your code. </p> <p><a href="http://epydoc.sourceforge.net/" rel="nofollow">Epydoc</a> is very good at scanning your docstrings and looking at your code to generate API documents but is not necessarily good at giving much more in-depth information.</p> <p>There is virtue to having both types of documentation for a project. However if you get in a time crunch it is always more beneficial to have good test coverage and meaningful tests than documentation.</p>
4
2008-12-24T03:23:08Z
[ "python", "data-structures", "documentation" ]
Producing documentation for Python classes
389,688
<p>I'm about to start a project where I will be the only one doing actual code and two less experienced programmers (scary to think of myself as experienced!) will be watching and making suggestions on the program in general.</p> <p>Is there a good (free) system that I can use to provide documentation for classes and functions based on the code I've written? It'd likely help them a lot in getting to grips with the structure of the data.</p>
11
2008-12-23T18:30:53Z
900,314
<p>I use Sphinx for my project, not only because it looks good, but also because Sphinx encourages writing documentation for <em>humans</em> to read, not just <em>computers</em>.</p> <p>I find the JavaDoc-style documentation produced by tools like epydoc quite sad to read. It happens all too often that the programmer is mindlessly "documenting" arguments and return types simply because there would otherwise be a gap in the API docs. So you end up with code line this (which is supposed to look like Java, but it's been a while since I wrote Java, so it might not compile...)</p> <pre><code>/** * Set the name. * * @param firstName the first name. * @param lastName the last name. */ public void setName(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } </code></pre> <p>There is a very small amount of information in this so-called "documentation". I much prefer the Sphinx way where you (using the <code>autodoc</code> plugin) simply write</p> <pre><code>.. autofunction:: set_name </code></pre> <p>and Sphinx will then add a line to your documentation that says</p> <blockquote> <p><code>set_name</code>(<code>first_name</code>, <code>last_name</code>)</p> </blockquote> <p>and from that every Python programmer should know what is going on.</p>
3
2009-05-22T22:43:16Z
[ "python", "data-structures", "documentation" ]
How can I read Perl data structures from Python?
389,945
<p>I've often seen people use Perl data structures in lieu of configuration files; i.e. a lone file containing only:</p> <pre><code>%config = ( 'color' =&gt; 'red', 'numbers' =&gt; [5, 8], qr/^spam/ =&gt; 'eggs' ); </code></pre> <p>What's the best way to convert the contents of these files into Python-equivalent data structures, using pure Python? For the time being we can assume that there are no real expressions to evaluate, only structured data.</p>
9
2008-12-23T20:11:08Z
389,970
<p>Is using pure Python a requirement? If not, you can load it in Perl and convert it to YAML or JSON. Then use PyYAML or something similar to load them in Python.</p>
17
2008-12-23T20:19:38Z
[ "python", "perl", "configuration", "data-structures" ]
How can I read Perl data structures from Python?
389,945
<p>I've often seen people use Perl data structures in lieu of configuration files; i.e. a lone file containing only:</p> <pre><code>%config = ( 'color' =&gt; 'red', 'numbers' =&gt; [5, 8], qr/^spam/ =&gt; 'eggs' ); </code></pre> <p>What's the best way to convert the contents of these files into Python-equivalent data structures, using pure Python? For the time being we can assume that there are no real expressions to evaluate, only structured data.</p>
9
2008-12-23T20:11:08Z
390,062
<p>Not sure what the use case is. Here's my assumption: you're going to do a one-time conversion from Perl to Python.</p> <p>Perl has this</p> <pre><code>%config = ( 'color' =&gt; 'red', 'numbers' =&gt; [5, 8], qr/^spam/ =&gt; 'eggs' ); </code></pre> <p>In Python, it would be</p> <pre><code>config = { 'color' : 'red', 'numbers' : [5, 8], re.compile( "^spam" ) : 'eggs' } </code></pre> <p>So, I'm guessing it's a bunch of RE's to replace </p> <ul> <li><code>%variable = (</code> with <code>variable = {</code></li> <li><code>);</code> with <code>}</code></li> <li><code>variable =&gt; value</code> with <code>variable : value</code></li> <li><code>qr/.../ =&gt;</code> with <code>re.compile( r"..." ) : value</code></li> </ul> <p>However, Python's built-in <code>dict</code> doesn't do anything unusual with a regex as a hash key. For that, you'd have to write your own subclass of <code>dict</code>, and override <code>__getitem__</code> to check REGEX keys separately.</p> <pre><code>class PerlLikeDict( dict ): pattern_type= type(re.compile("")) def __getitem__( self, key ): if key in self: return super( PerlLikeDict, self ).__getitem__( key ) for k in self: if type(k) == self.pattern_type: if k.match(key): return self[k] raise KeyError( "key %r not found" % ( key, ) ) </code></pre> <p>Here's the example of using a Perl-like dict.</p> <pre><code>&gt;&gt;&gt; pat= re.compile( "hi" ) &gt;&gt;&gt; a = { pat : 'eggs' } # native dict, no features. &gt;&gt;&gt; x=PerlLikeDict( a ) &gt;&gt;&gt; x['b']= 'c' &gt;&gt;&gt; x {&lt;_sre.SRE_Pattern object at 0x75250&gt;: 'eggs', 'b': 'c'} &gt;&gt;&gt; x['b'] 'c' &gt;&gt;&gt; x['ji'] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 10, in __getitem__ KeyError: "key 'ji' not found" &gt;&gt;&gt; x['hi'] 'eggs' </code></pre>
8
2008-12-23T20:56:23Z
[ "python", "perl", "configuration", "data-structures" ]
How can I read Perl data structures from Python?
389,945
<p>I've often seen people use Perl data structures in lieu of configuration files; i.e. a lone file containing only:</p> <pre><code>%config = ( 'color' =&gt; 'red', 'numbers' =&gt; [5, 8], qr/^spam/ =&gt; 'eggs' ); </code></pre> <p>What's the best way to convert the contents of these files into Python-equivalent data structures, using pure Python? For the time being we can assume that there are no real expressions to evaluate, only structured data.</p>
9
2008-12-23T20:11:08Z
390,441
<p>I've also found <a href="http://search.cpan.org/dist/pyperl/" rel="nofollow">PyPerl</a>, but it doesn't seem to be maintained. I guess something like this is what I was looking for -- a module that did some basic interpretation of Perl and passed the result as a Python object. A Perl interpreter that died on anything too complex would be fine. :-)</p>
0
2008-12-23T23:57:12Z
[ "python", "perl", "configuration", "data-structures" ]
How can I read Perl data structures from Python?
389,945
<p>I've often seen people use Perl data structures in lieu of configuration files; i.e. a lone file containing only:</p> <pre><code>%config = ( 'color' =&gt; 'red', 'numbers' =&gt; [5, 8], qr/^spam/ =&gt; 'eggs' ); </code></pre> <p>What's the best way to convert the contents of these files into Python-equivalent data structures, using pure Python? For the time being we can assume that there are no real expressions to evaluate, only structured data.</p>
9
2008-12-23T20:11:08Z
390,589
<p>I'd just turn the Perl data structure into something else. Not seeing the actual file, there might be some extra work that my solution doesn't do. </p> <p>If the only thing that's in the file is the one variable declaration (so, no <code>1;</code> at the end, and so on), it can be really simple to turn your <code>%config</code> it into YAML:</p> <pre><code>perl -MYAML -le 'print YAML::Dump( { do shift } )' filename </code></pre> <p>The <code>do</code> returns the last thing it evaluated, so in this little code it returns the list of hash key-value pairs. Things such as YAML::Dump like to work with references so they get a hint about the top-level structure, so I make that into a hash reference by surrounding the <code>do</code> with the curly braces. For your example, I'd get this YAML output:</p> <pre> --- (?-xism:^spam): eggs color: red numbers: - 5 - 8 </pre> <p>I don't know how Python will like that stringified regex, though. Do you really have a key that is a regex? I'd be curious to know how that's being used as part of the configuration.</p> <p><hr></p> <p>If there's extra stuff in the file, life is a bit more tough. There's probably a really clever way to get around that, but I used the same idea, but just hard-coded the variable name that I wanted.</p> <p>I tried this on the Perl data structure that the CPAN.pm module uses, and it looks like it came out fine. The only ugliness is the fore-knowledge of the variable name that it supplies. Now that you've seen the error of configuration in Perl code, avoid making the same mistake with Python code. :)</p> <p>YAML:</p> <pre><code> perl -MYAML -le 'do shift; print YAML::Dump( $CPAN::Config )' MyConfig.pm </code></pre> <p>JSON:</p> <pre><code> perl -MJSON::Any -le 'do shift; my $j = JSON::Any-&gt;new; print $j-&gt;objToJson( $CPAN::Config )' MyConfig.pm </code></pre> <p>or</p> <pre><code># suggested by JF Sebastian perl -MJSON -le 'do shift; print to_json( $CPAN::Config )' MyConfig.pm </code></pre> <p>XML::Simple doesn't work out so well because it treated everything like an attribute, but maybe someone can improve on this:</p> <pre><code>perl -MXML::Simple -le 'do shift; print XMLout( $CPAN::Config )' MyConfig.pm </code></pre>
11
2008-12-24T01:41:06Z
[ "python", "perl", "configuration", "data-structures" ]
Elegant ways to support equivalence ("equality") in Python classes
390,250
<p>When writing custom classes it is often important to allow equivalence by means of the <code>==</code> and <code>!=</code> operators. In Python, this is made possible by implementing the <code>__eq__</code> and <code>__ne__</code> special methods, respectively. The easiest way I've found to do this is the following method:</p> <pre><code>class Foo: def __init__(self, item): self.item = item def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __ne__(self, other): return not self.__eq__(other) </code></pre> <p>Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing <code>__dict__</code>s?</p> <p><strong>Note</strong>: A bit of clarification--when <code>__eq__</code> and <code>__ne__</code> are undefined, you'll find this behavior:</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b False </code></pre> <p>That is, <code>a == b</code> evaluates to <code>False</code> because it really runs <code>a is b</code>, a test of identity (i.e., "Is <code>a</code> the same object as <code>b</code>?").</p> <p>When <code>__eq__</code> and <code>__ne__</code> are defined, you'll find this behavior (which is the one we're after):</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b True </code></pre>
222
2008-12-23T22:30:52Z
390,280
<p>You don't have to override both <code>__eq__</code> and <code>__ne__</code> you can override only <code>__cmp__</code> but this will make an implication on the result of ==, !==, &lt; , > and so on.</p> <p><code>is</code> tests for object identity. This means a <code>is</code> b will be <code>True</code> in the case when a and b both hold the reference to the same object. In python you always hold a reference to an object in a variable not the actual object, so essentially for a is b to be true the objects in them should be located in the same memory location. How and most importantly why would you go about overriding this behaviour?</p> <p>Edit: I didn't know <code>__cmp__</code> was removed from python 3 so avoid it.</p>
8
2008-12-23T22:44:26Z
[ "python", "equality", "equivalence" ]
Elegant ways to support equivalence ("equality") in Python classes
390,250
<p>When writing custom classes it is often important to allow equivalence by means of the <code>==</code> and <code>!=</code> operators. In Python, this is made possible by implementing the <code>__eq__</code> and <code>__ne__</code> special methods, respectively. The easiest way I've found to do this is the following method:</p> <pre><code>class Foo: def __init__(self, item): self.item = item def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __ne__(self, other): return not self.__eq__(other) </code></pre> <p>Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing <code>__dict__</code>s?</p> <p><strong>Note</strong>: A bit of clarification--when <code>__eq__</code> and <code>__ne__</code> are undefined, you'll find this behavior:</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b False </code></pre> <p>That is, <code>a == b</code> evaluates to <code>False</code> because it really runs <code>a is b</code>, a test of identity (i.e., "Is <code>a</code> the same object as <code>b</code>?").</p> <p>When <code>__eq__</code> and <code>__ne__</code> are defined, you'll find this behavior (which is the one we're after):</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b True </code></pre>
222
2008-12-23T22:30:52Z
390,335
<p>I think that the two terms you're looking for are <strong>equality</strong> (==) and <strong>identity</strong> (is). For example:</p> <pre><code>&gt;&gt;&gt; a = [1,2,3] &gt;&gt;&gt; b = [1,2,3] &gt;&gt;&gt; a == b True &lt;-- a and b have values which are equal &gt;&gt;&gt; a is b False &lt;-- a and b are not the same list object </code></pre>
2
2008-12-23T23:12:07Z
[ "python", "equality", "equivalence" ]
Elegant ways to support equivalence ("equality") in Python classes
390,250
<p>When writing custom classes it is often important to allow equivalence by means of the <code>==</code> and <code>!=</code> operators. In Python, this is made possible by implementing the <code>__eq__</code> and <code>__ne__</code> special methods, respectively. The easiest way I've found to do this is the following method:</p> <pre><code>class Foo: def __init__(self, item): self.item = item def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __ne__(self, other): return not self.__eq__(other) </code></pre> <p>Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing <code>__dict__</code>s?</p> <p><strong>Note</strong>: A bit of clarification--when <code>__eq__</code> and <code>__ne__</code> are undefined, you'll find this behavior:</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b False </code></pre> <p>That is, <code>a == b</code> evaluates to <code>False</code> because it really runs <code>a is b</code>, a test of identity (i.e., "Is <code>a</code> the same object as <code>b</code>?").</p> <p>When <code>__eq__</code> and <code>__ne__</code> are defined, you'll find this behavior (which is the one we're after):</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b True </code></pre>
222
2008-12-23T22:30:52Z
390,511
<p>The way you describe is the way I've always done it. Since it's totally generic, you can always break that functionality out into a mixin class and inherit it in classes where you want that functionality.</p> <pre><code>class CommonEqualityMixin(object): def __eq__(self, other): return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__) def __ne__(self, other): return not self.__eq__(other) class Foo(CommonEqualityMixin): def __init__(self, item): self.item = item </code></pre>
143
2008-12-24T00:44:13Z
[ "python", "equality", "equivalence" ]
Elegant ways to support equivalence ("equality") in Python classes
390,250
<p>When writing custom classes it is often important to allow equivalence by means of the <code>==</code> and <code>!=</code> operators. In Python, this is made possible by implementing the <code>__eq__</code> and <code>__ne__</code> special methods, respectively. The easiest way I've found to do this is the following method:</p> <pre><code>class Foo: def __init__(self, item): self.item = item def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __ne__(self, other): return not self.__eq__(other) </code></pre> <p>Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing <code>__dict__</code>s?</p> <p><strong>Note</strong>: A bit of clarification--when <code>__eq__</code> and <code>__ne__</code> are undefined, you'll find this behavior:</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b False </code></pre> <p>That is, <code>a == b</code> evaluates to <code>False</code> because it really runs <code>a is b</code>, a test of identity (i.e., "Is <code>a</code> the same object as <code>b</code>?").</p> <p>When <code>__eq__</code> and <code>__ne__</code> are defined, you'll find this behavior (which is the one we're after):</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b True </code></pre>
222
2008-12-23T22:30:52Z
390,640
<p>You need to be careful with inheritance:</p> <pre><code>&gt;&gt;&gt; class Foo: def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False &gt;&gt;&gt; class Bar(Foo):pass &gt;&gt;&gt; b = Bar() &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; f == b True &gt;&gt;&gt; b == f False </code></pre> <p>Check types more strictly, like this:</p> <pre><code>def __eq__(self, other): if type(other) is type(self): return self.__dict__ == other.__dict__ return False </code></pre> <p>Besides that, your approach will work fine, that's what special methods are there for.</p>
166
2008-12-24T02:30:13Z
[ "python", "equality", "equivalence" ]
Elegant ways to support equivalence ("equality") in Python classes
390,250
<p>When writing custom classes it is often important to allow equivalence by means of the <code>==</code> and <code>!=</code> operators. In Python, this is made possible by implementing the <code>__eq__</code> and <code>__ne__</code> special methods, respectively. The easiest way I've found to do this is the following method:</p> <pre><code>class Foo: def __init__(self, item): self.item = item def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __ne__(self, other): return not self.__eq__(other) </code></pre> <p>Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing <code>__dict__</code>s?</p> <p><strong>Note</strong>: A bit of clarification--when <code>__eq__</code> and <code>__ne__</code> are undefined, you'll find this behavior:</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b False </code></pre> <p>That is, <code>a == b</code> evaluates to <code>False</code> because it really runs <code>a is b</code>, a test of identity (i.e., "Is <code>a</code> the same object as <code>b</code>?").</p> <p>When <code>__eq__</code> and <code>__ne__</code> are defined, you'll find this behavior (which is the one we're after):</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b True </code></pre>
222
2008-12-23T22:30:52Z
390,662
<p>The 'is' test will test for identity using the builtin 'id()' function which essentially returns the memory address of the object and therefore isn't overloadable.</p> <p>However in the case of testing the equality of a class you probably want to be a little bit more strict about your tests and only compare the data attributes in your class:</p> <pre><code>import types class ComparesNicely(object): def __eq__(self, other): for key, value in self.__dict__.iteritems(): if (isinstance(value, types.FunctionType) or key.startswith("__")): continue if key not in other.__dict__: return False if other.__dict__[key] != value: return False return True </code></pre> <p>This code will only compare non function data members of your class as well as skipping anything private which is generally what you want. In the case of Plain Old Python Objects I have a base class which implements __init__, __str__, __repr__ and __eq__ so my POPO objects don't carry the burden of all that extra (and in most cases identical) logic.</p>
1
2008-12-24T02:55:28Z
[ "python", "equality", "equivalence" ]
Elegant ways to support equivalence ("equality") in Python classes
390,250
<p>When writing custom classes it is often important to allow equivalence by means of the <code>==</code> and <code>!=</code> operators. In Python, this is made possible by implementing the <code>__eq__</code> and <code>__ne__</code> special methods, respectively. The easiest way I've found to do this is the following method:</p> <pre><code>class Foo: def __init__(self, item): self.item = item def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __ne__(self, other): return not self.__eq__(other) </code></pre> <p>Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing <code>__dict__</code>s?</p> <p><strong>Note</strong>: A bit of clarification--when <code>__eq__</code> and <code>__ne__</code> are undefined, you'll find this behavior:</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b False </code></pre> <p>That is, <code>a == b</code> evaluates to <code>False</code> because it really runs <code>a is b</code>, a test of identity (i.e., "Is <code>a</code> the same object as <code>b</code>?").</p> <p>When <code>__eq__</code> and <code>__ne__</code> are defined, you'll find this behavior (which is the one we're after):</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b True </code></pre>
222
2008-12-23T22:30:52Z
12,494,556
<p>Not a direct answer but seemed relevant enough to be tacked on as it saves a bit of verbose tedium on occasion. Cut straight from the docs...</p> <hr> <p><a href="http://docs.python.org/library/functools.html#functools.total_ordering" rel="nofollow">functools.total_ordering(cls)</a></p> <p><strong>Given a class defining one or more rich comparison ordering methods, this class decorator supplies the rest.</strong> This simplifies the effort involved in specifying all of the possible rich comparison operations:</p> <p>The class must define one of <strong>lt</strong>(), <strong>le</strong>(), <strong>gt</strong>(), or <strong>ge</strong>(). In addition, the class should supply an <strong>eq</strong>() method.</p> <p>New in version 2.7</p> <pre><code>@total_ordering class Student: def __eq__(self, other): return ((self.lastname.lower(), self.firstname.lower()) == (other.lastname.lower(), other.firstname.lower())) def __lt__(self, other): return ((self.lastname.lower(), self.firstname.lower()) &lt; (other.lastname.lower(), other.firstname.lower())) </code></pre>
11
2012-09-19T12:19:09Z
[ "python", "equality", "equivalence" ]
Elegant ways to support equivalence ("equality") in Python classes
390,250
<p>When writing custom classes it is often important to allow equivalence by means of the <code>==</code> and <code>!=</code> operators. In Python, this is made possible by implementing the <code>__eq__</code> and <code>__ne__</code> special methods, respectively. The easiest way I've found to do this is the following method:</p> <pre><code>class Foo: def __init__(self, item): self.item = item def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __ne__(self, other): return not self.__eq__(other) </code></pre> <p>Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing <code>__dict__</code>s?</p> <p><strong>Note</strong>: A bit of clarification--when <code>__eq__</code> and <code>__ne__</code> are undefined, you'll find this behavior:</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b False </code></pre> <p>That is, <code>a == b</code> evaluates to <code>False</code> because it really runs <code>a is b</code>, a test of identity (i.e., "Is <code>a</code> the same object as <code>b</code>?").</p> <p>When <code>__eq__</code> and <code>__ne__</code> are defined, you'll find this behavior (which is the one we're after):</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b True </code></pre>
222
2008-12-23T22:30:52Z
25,176,504
<p>Sorry, but non of the answers fully "work". Consider the simple problem:</p> <pre><code>class Number: """Very basic""" def __init__(self, some_number): self.some_number = some_number n1 = Number(1) n2 = Number(1) print n1 == n2 # False -- oops </code></pre> <p>So, Python by default uses the id of objects for comparison.</p> <pre><code>print id(n1) # 140400634555856 print id(n2) # 140400634555920 </code></pre> <p>Overriding the <strong>eq</strong> function seams to solve the problem:</p> <pre><code>def __eq__(self, other): """Override the default Equals behavior""" if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False print n1 == n2 # True print n1 != n2 # True -- oops </code></pre> <p>Always remember to add the <strong>ne</strong> function override:</p> <pre><code>def __ne__(self, other): """Define a non-equality test""" return not self.__eq__(other) print n1 == n2 # True print n1 != n2 # False </code></pre> <p>But that doesn't solve all our problems. Let's add a subclass:</p> <pre><code>class NumberPlus(Number): pass n3 = NumberPlus(1) print n1 == n3 # True print n3 == n1 # False -- oops </code></pre> <p>Note - new style classes behave <a href="http://stackoverflow.com/a/12984987/78234">a bit differently</a> yet I will provide a generic solution. </p> <p>To fix we need to return the singleton <code>NotImplemented</code> when the object types do not match, delegating the result to <code>superclass.__eq__(subclass)</code>. </p> <p>The result looks like this:</p> <pre><code> def __eq__(self, other): """Override the default Equals behavior""" if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return NotImplemented def __ne__(self, other): """Define a non-equality test""" if isinstance(other, self.__class__): return not self.__eq__(other) return NotImplemented </code></pre> <p>Are we there yet? Not quite. How many unique numbers do we have?</p> <pre><code>print len(set([n1, n2, n3])) # 3 -- oops </code></pre> <p>Hmmm. Sets use the hashes of objects, and by default Python returns the id() of the object as a hash. Let's try to override:</p> <pre><code>def __hash__(self): """Override the default hash behavior (that returns the id or the object)""" return hash(tuple(sorted(self.__dict__.items()))) print len(set([n1, n2, n3])) # 1 </code></pre> <p>The end result looks like this (I added some assertions at the end for validation):</p> <pre><code>class Number(object): """Very basic""" def __init__(self, some_number): self.some_number = some_number def __eq__(self, other): """Override the default Equals behavior""" if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return NotImplemented def __ne__(self, other): """Define a non-equality test""" if isinstance(other, self.__class__): return not self.__eq__(other) return NotImplemented def __hash__(self): """Override the default hash behavior (that returns the id or the object)""" return hash(tuple(sorted(self.__dict__.items()))) n1 = Number(1) n2 = Number(1) class NumberPlus(Number): pass n3 = NumberPlus(1) n4 = NumberPlus(4) assert n1 == n2 assert n2 == n1 assert not n1 != n2 assert not n2 != n1 assert n1 == n3 assert n3 == n1 assert not n1 != n3 assert not n3 != n1 assert not n1 == n4 assert not n4 == n1 assert n1 != n4 assert n4 != n1 assert len(set([n1, n2, n3, ])) == 1 assert len(set([n1, n2, n3, n4])) == 2 </code></pre>
75
2014-08-07T07:24:42Z
[ "python", "equality", "equivalence" ]
Elegant ways to support equivalence ("equality") in Python classes
390,250
<p>When writing custom classes it is often important to allow equivalence by means of the <code>==</code> and <code>!=</code> operators. In Python, this is made possible by implementing the <code>__eq__</code> and <code>__ne__</code> special methods, respectively. The easiest way I've found to do this is the following method:</p> <pre><code>class Foo: def __init__(self, item): self.item = item def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False def __ne__(self, other): return not self.__eq__(other) </code></pre> <p>Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing <code>__dict__</code>s?</p> <p><strong>Note</strong>: A bit of clarification--when <code>__eq__</code> and <code>__ne__</code> are undefined, you'll find this behavior:</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b False </code></pre> <p>That is, <code>a == b</code> evaluates to <code>False</code> because it really runs <code>a is b</code>, a test of identity (i.e., "Is <code>a</code> the same object as <code>b</code>?").</p> <p>When <code>__eq__</code> and <code>__ne__</code> are defined, you'll find this behavior (which is the one we're after):</p> <pre><code>&gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b True </code></pre>
222
2008-12-23T22:30:52Z
30,880,440
<p>From this answer: <a href="http://stackoverflow.com/a/30676267/541136">http://stackoverflow.com/a/30676267/541136</a> I have demonstrated that, while it's correct to define <code>__ne__</code> in terms <code>__eq__</code> - instead of </p> <pre><code>def __ne__(self, other): return not self.__eq__(other) </code></pre> <p>you should use:</p> <pre><code>def __ne__(self, other): return not self == other </code></pre>
2
2015-06-17T00:30:12Z
[ "python", "equality", "equivalence" ]
Interpreting Excel Currency Values
390,263
<p>I am using python to read a currency value from excel. The returned from the range.Value method is a tuple that I don't know how to parse.</p> <p>For example, the cell appears as $548,982, but in python the value is returned as (1, 1194857614).</p> <p>How can I get the numerical amount from excel or how can I convert this tuple value into the numerical value?</p> <p>Thanks!</p>
1
2008-12-23T22:37:51Z
390,304
<p>I tried this with Excel 2007 and VBA. It is giving correct value.</p> <p>1) Try pasting this value in a new excel workbook<br> 2) Press Alt + F11. Gets you to VBA Editor.<br> 3) Press Ctrl + G. Gets you to immediate window.<br> 4) In the immediate window, type ?cells("a1").Value <br> here "a1" is the cell where you have pasted the value.</p> <p>I am doubting that the cell has some value or character due to which it is interpreted this way.</p> <p>Post your observations here.</p>
0
2008-12-23T22:54:07Z
[ "python", "excel", "pywin32" ]
Interpreting Excel Currency Values
390,263
<p>I am using python to read a currency value from excel. The returned from the range.Value method is a tuple that I don't know how to parse.</p> <p>For example, the cell appears as $548,982, but in python the value is returned as (1, 1194857614).</p> <p>How can I get the numerical amount from excel or how can I convert this tuple value into the numerical value?</p> <p>Thanks!</p>
1
2008-12-23T22:37:51Z
391,076
<p>Try this:</p> <pre><code>import struct try: import decimal except ImportError: divisor= 10000.0 else: divisor= decimal.Decimal(10000) def xl_money(i1, i2): byte8= struct.unpack("&gt;q", struct.pack("&gt;ii", i1, i2))[0] return byte8 / divisor &gt;&gt;&gt; xl_money(1, 1194857614) Decimal("548982.491") </code></pre> <p>Money in Microsoft COM is an 8-byte integer; it's fixed point, with 4 decimal places (i.e. 1 is represented by 10000). What my function does, is take the tuple of 4-byte integers, make an 8-byte integer using struct to avoid any issues of sign, and then dividing by the constant 10000. The function uses decimal.Decimal if available, otherwise it uses float.</p> <p>UPDATE (based on comment): So far, it's only COM Currency values being returned as a two-integer tuple, so you might want to check for that, but there are no guarantees that this will always be successful. However, depending on the library you use and its version, it's quite possible that later on, after some upgrade, you will be receiving <code>decimal.Decimal</code>s and not two-integer tuples anymore.</p>
3
2008-12-24T09:19:13Z
[ "python", "excel", "pywin32" ]
How do you debug Mako templates?
390,409
<p>So far I've found it impossible to produce usable tracebacks when Mako templates aren't coded correctly.</p> <p>Is there any way to debug templates besides iterating for every line of code?</p>
31
2008-12-23T23:43:30Z
390,603
<p>I break them down into pieces, and then reassemble the pieces when I've found the problem.</p> <p>Not good, but it's really hard to tell what went wrong in a big, complex template.</p>
1
2008-12-24T01:49:17Z
[ "python", "debugging", "templates", "jinja2", "mako" ]
How do you debug Mako templates?
390,409
<p>So far I've found it impossible to produce usable tracebacks when Mako templates aren't coded correctly.</p> <p>Is there any way to debug templates besides iterating for every line of code?</p>
31
2008-12-23T23:43:30Z
536,087
<p>Mako actually provides a <a href="http://docs.makotemplates.org/en/latest/usage.html#handling-exceptions">VERY nice way to track down errors in a template</a>:</p> <pre><code>from mako import exceptions try: template = lookup.get_template(uri) print template.render() except: print exceptions.html_error_template().render() </code></pre>
38
2009-02-11T09:31:33Z
[ "python", "debugging", "templates", "jinja2", "mako" ]
How do you debug Mako templates?
390,409
<p>So far I've found it impossible to produce usable tracebacks when Mako templates aren't coded correctly.</p> <p>Is there any way to debug templates besides iterating for every line of code?</p>
31
2008-12-23T23:43:30Z
13,316,747
<p>Using flask_mako, I find it's easier to skip over the TemplateError generation and just pass up the exception. I.e. in flask_mako.py, comment out the part that makes the TemplateError and just do a raise:</p> <pre><code>def _render(template, context, app): """Renders the template and fires the signal""" app.update_template_context(context) try: rv = template.render(**context) template_rendered.send(app, template=template, context=context) return rv except: #translated = TemplateError(template) #raise translated raise </code></pre> <p>}</p> <p>Then you'll see a regular python exception that caused the problem along with line numbers in the template.</p>
0
2012-11-09T22:07:43Z
[ "python", "debugging", "templates", "jinja2", "mako" ]
How do you debug Mako templates?
390,409
<p>So far I've found it impossible to produce usable tracebacks when Mako templates aren't coded correctly.</p> <p>Is there any way to debug templates besides iterating for every line of code?</p>
31
2008-12-23T23:43:30Z
21,950,573
<p>Looking at the <a href="http://pythonhosted.org/Flask-Mako/" rel="nofollow">Flask-Mako</a> source, I found an undocumented configuration parameter called <code>MAKO_TRANSLATE_EXCEPTIONS</code>. </p> <p>Set this to <code>False</code> in your Flask app config and you'll get nice exceptions bubbling up from the template. This accomplishes the same thing as @Mariano suggested, without needing to edit the source. Apparently, this parameter was added after Mariano's answer.</p>
3
2014-02-22T06:18:39Z
[ "python", "debugging", "templates", "jinja2", "mako" ]
Is there any built-in way to get the length of an iterable in python?
390,852
<p>For example, files, in Python, are iterable - they iterate over the lines in the file. I want to count the number of lines. </p> <p>One quick way is to do this:</p> <pre><code>lines = len(list(open(fname))) </code></pre> <p>However, this loads the whole file into memory (at once). This rather defeats the purpose of an iterator (which only needs to keep the current line in memory).</p> <p>This doesn't work:</p> <pre><code>lines = len(line for line in open(fname)) </code></pre> <p>as generators don't have a length.</p> <p>Is there any way to do this short of defining a count function?</p> <pre><code>def count(i): c = 0 for el in i: c += 1 return c </code></pre> <p>EDIT: To clarify, I understand that the whole file will have to be read! I just don't want it in memory all at once =).</p>
23
2008-12-24T05:55:37Z
390,861
<p>If you need a count of lines you can do this, I don't know of any better way to do it:</p> <pre><code>line_count = sum(1 for line in open("yourfile.txt")) </code></pre>
15
2008-12-24T06:03:06Z
[ "python", "iterator" ]
Is there any built-in way to get the length of an iterable in python?
390,852
<p>For example, files, in Python, are iterable - they iterate over the lines in the file. I want to count the number of lines. </p> <p>One quick way is to do this:</p> <pre><code>lines = len(list(open(fname))) </code></pre> <p>However, this loads the whole file into memory (at once). This rather defeats the purpose of an iterator (which only needs to keep the current line in memory).</p> <p>This doesn't work:</p> <pre><code>lines = len(line for line in open(fname)) </code></pre> <p>as generators don't have a length.</p> <p>Is there any way to do this short of defining a count function?</p> <pre><code>def count(i): c = 0 for el in i: c += 1 return c </code></pre> <p>EDIT: To clarify, I understand that the whole file will have to be read! I just don't want it in memory all at once =).</p>
23
2008-12-24T05:55:37Z
390,885
<p>Short of iterating through the iterable and counting the number of iterations, no. That's what makes it an iterable and not a list. This isn't really even a python-specific problem. Look at the classic linked-list data structure. Finding the length is an O(n) operation that involves iterating the whole list to find the number of elements.</p> <p>As mcrute mentioned above, you can probably reduce your function to:</p> <pre><code>def count_iterable(i): return sum(1 for e in i) </code></pre> <p>Of course, if you're defining your own iterable object you can always implement <code>__len__</code> yourself and keep an element count somewhere.</p>
43
2008-12-24T06:23:35Z
[ "python", "iterator" ]
Is there any built-in way to get the length of an iterable in python?
390,852
<p>For example, files, in Python, are iterable - they iterate over the lines in the file. I want to count the number of lines. </p> <p>One quick way is to do this:</p> <pre><code>lines = len(list(open(fname))) </code></pre> <p>However, this loads the whole file into memory (at once). This rather defeats the purpose of an iterator (which only needs to keep the current line in memory).</p> <p>This doesn't work:</p> <pre><code>lines = len(line for line in open(fname)) </code></pre> <p>as generators don't have a length.</p> <p>Is there any way to do this short of defining a count function?</p> <pre><code>def count(i): c = 0 for el in i: c += 1 return c </code></pre> <p>EDIT: To clarify, I understand that the whole file will have to be read! I just don't want it in memory all at once =).</p>
23
2008-12-24T05:55:37Z
390,911
<p>We'll, if you think about it, how do you propose you find the number of lines in a file without reading the whole file for newlines? Sure, you can find the size of the file, and if you can gurantee that the length of a line is x, you can get the number of lines in a file. But unless you have some kind of constraint, I fail to see how this can work at all. Also, since iterables can be infinitely long...</p>
0
2008-12-24T06:39:10Z
[ "python", "iterator" ]
Is there any built-in way to get the length of an iterable in python?
390,852
<p>For example, files, in Python, are iterable - they iterate over the lines in the file. I want to count the number of lines. </p> <p>One quick way is to do this:</p> <pre><code>lines = len(list(open(fname))) </code></pre> <p>However, this loads the whole file into memory (at once). This rather defeats the purpose of an iterator (which only needs to keep the current line in memory).</p> <p>This doesn't work:</p> <pre><code>lines = len(line for line in open(fname)) </code></pre> <p>as generators don't have a length.</p> <p>Is there any way to do this short of defining a count function?</p> <pre><code>def count(i): c = 0 for el in i: c += 1 return c </code></pre> <p>EDIT: To clarify, I understand that the whole file will have to be read! I just don't want it in memory all at once =).</p>
23
2008-12-24T05:55:37Z
390,928
<p>Absolutely not, for the simple reason that iterables are not guaranteed to be finite.</p> <p>Consider this perfectly legal generator function:</p> <pre><code>def forever(): while True: yield "I will run forever" </code></pre> <p>Attempting to calculate the length of this function with <code>len([x for x in forever()])</code> will clearly not work.</p> <p>As you noted, much of the purpose of iterators/generators is to be able to work on a large dataset without loading it all into memory. The fact that you can't get an immediate length should be considered a tradeoff.</p>
8
2008-12-24T06:54:08Z
[ "python", "iterator" ]
Is there any built-in way to get the length of an iterable in python?
390,852
<p>For example, files, in Python, are iterable - they iterate over the lines in the file. I want to count the number of lines. </p> <p>One quick way is to do this:</p> <pre><code>lines = len(list(open(fname))) </code></pre> <p>However, this loads the whole file into memory (at once). This rather defeats the purpose of an iterator (which only needs to keep the current line in memory).</p> <p>This doesn't work:</p> <pre><code>lines = len(line for line in open(fname)) </code></pre> <p>as generators don't have a length.</p> <p>Is there any way to do this short of defining a count function?</p> <pre><code>def count(i): c = 0 for el in i: c += 1 return c </code></pre> <p>EDIT: To clarify, I understand that the whole file will have to be read! I just don't want it in memory all at once =).</p>
23
2008-12-24T05:55:37Z
390,989
<p>I've used this redefinition for some time now:</p> <pre><code>def len(thingy): try: return thingy.__len__() except AttributeError: return sum(1 for item in iter(thingy)) </code></pre>
7
2008-12-24T07:49:02Z
[ "python", "iterator" ]
Is there any built-in way to get the length of an iterable in python?
390,852
<p>For example, files, in Python, are iterable - they iterate over the lines in the file. I want to count the number of lines. </p> <p>One quick way is to do this:</p> <pre><code>lines = len(list(open(fname))) </code></pre> <p>However, this loads the whole file into memory (at once). This rather defeats the purpose of an iterator (which only needs to keep the current line in memory).</p> <p>This doesn't work:</p> <pre><code>lines = len(line for line in open(fname)) </code></pre> <p>as generators don't have a length.</p> <p>Is there any way to do this short of defining a count function?</p> <pre><code>def count(i): c = 0 for el in i: c += 1 return c </code></pre> <p>EDIT: To clarify, I understand that the whole file will have to be read! I just don't want it in memory all at once =).</p>
23
2008-12-24T05:55:37Z
28,385,557
<p>The <code>cardinality</code> package provides an efficient <code>count()</code> function and some related functions to count and check the size of any iterable: <a href="http://cardinality.readthedocs.org/" rel="nofollow">http://cardinality.readthedocs.org/</a></p> <p>Internally it uses <code>enumerate()</code> and <code>collections.deque()</code> to move all the actual looping and counting logic to the C level, resulting in a considerable speedup over <code>for</code> loops in Python.</p>
2
2015-02-07T18:04:18Z
[ "python", "iterator" ]
Calling Application Methods from a wx Frame Class
390,867
<p>I'm starting out with wxPython and have been working my way through every tutorial and example I can get my hands on. I've run into a slight problem, however, and it has to do with the wx.App versus the wx.Frame and which should contain specific methods. Just about every example I've seen don't go much beyond layouts/sizers and event handling, none really tackle project organization of a wxPython project.</p> <p>For example, I have a method that gets a list of folders. The way most examples would deal with this would be to stick the method right in the frame class. This method has the potential to be used in several other parts of the application, so it would make more sense to store it at the application class level.</p> <p>How should I organize and call "universal" methods like these so that I don't clutter up my frame classes.</p> <p><strong>UPDATE:</strong></p> <p>To clarify, the "list of folders" was just an example, my actual method does a lot more work. What I'm saying is I have code that isn't Frame-specific. If I had this in the application class, what is the best way to call it from and event method in my frame.</p> <p>I'm looking for actual project organization techniques, not programming fundamentals.</p>
1
2008-12-24T06:07:30Z
390,887
<p>In a proper OOP design, this would be independent or part of a filesystem class - it wouldn't be part of the app or the frame.</p>
0
2008-12-24T06:24:15Z
[ "python", "wxpython", "wxwidgets", "model-view-controller", "project-organization" ]
Calling Application Methods from a wx Frame Class
390,867
<p>I'm starting out with wxPython and have been working my way through every tutorial and example I can get my hands on. I've run into a slight problem, however, and it has to do with the wx.App versus the wx.Frame and which should contain specific methods. Just about every example I've seen don't go much beyond layouts/sizers and event handling, none really tackle project organization of a wxPython project.</p> <p>For example, I have a method that gets a list of folders. The way most examples would deal with this would be to stick the method right in the frame class. This method has the potential to be used in several other parts of the application, so it would make more sense to store it at the application class level.</p> <p>How should I organize and call "universal" methods like these so that I don't clutter up my frame classes.</p> <p><strong>UPDATE:</strong></p> <p>To clarify, the "list of folders" was just an example, my actual method does a lot more work. What I'm saying is I have code that isn't Frame-specific. If I had this in the application class, what is the best way to call it from and event method in my frame.</p> <p>I'm looking for actual project organization techniques, not programming fundamentals.</p>
1
2008-12-24T06:07:30Z
390,912
<p>As Mark stated you should make a new class that handles things like this. </p> <p>The ideal layout of code when using something like wxWidgets is the model view controller where the wxFrame class only has the code needed to display items and all the logic and business rules are handled by other class that interact with the wxFrame. This way you can change logic and business rules with out having to change your interface and change (or swap) your interface with out having to change your logic and business rules.</p>
2
2008-12-24T06:39:56Z
[ "python", "wxpython", "wxwidgets", "model-view-controller", "project-organization" ]
Calling Application Methods from a wx Frame Class
390,867
<p>I'm starting out with wxPython and have been working my way through every tutorial and example I can get my hands on. I've run into a slight problem, however, and it has to do with the wx.App versus the wx.Frame and which should contain specific methods. Just about every example I've seen don't go much beyond layouts/sizers and event handling, none really tackle project organization of a wxPython project.</p> <p>For example, I have a method that gets a list of folders. The way most examples would deal with this would be to stick the method right in the frame class. This method has the potential to be used in several other parts of the application, so it would make more sense to store it at the application class level.</p> <p>How should I organize and call "universal" methods like these so that I don't clutter up my frame classes.</p> <p><strong>UPDATE:</strong></p> <p>To clarify, the "list of folders" was just an example, my actual method does a lot more work. What I'm saying is I have code that isn't Frame-specific. If I had this in the application class, what is the best way to call it from and event method in my frame.</p> <p>I'm looking for actual project organization techniques, not programming fundamentals.</p>
1
2008-12-24T06:07:30Z
394,333
<p>Your classes that inherit from wxWidgets/wxPython data types should not implement any business logic. wxWidgets is a GUI library, so any subclasses of wxApp or wxFrame should remain focused on GUI, that is on displaying the interface and being responsive to user actions. </p> <p>The code that does something useful should be separated from wx, as you can decide later to use it in some web or console application and you don't want to create wxApp object in such case. You can also decide later on to move some computations to separate 'worker threads', while your GUI will be the 'main thread' - responsive, and repainted properly during long lasting computations. </p> <p>Last but not least - the classes that encapsulate your logic might tend to grow during projects lifetime. If they're mixed with your GUI classes they will grow faster, and finally they become so complex that you're almost unable to debug them... </p> <p>While having them separated leads to clean code when you don't mix bugs in logic with bugs in GUI (refreshing/layout/progress bar etc.). Such approach has another nice feature - ability to split work among GUI-people and logic-people, which can do their work without constant conflicts.</p>
2
2008-12-26T22:01:47Z
[ "python", "wxpython", "wxwidgets", "model-view-controller", "project-organization" ]
Calling Application Methods from a wx Frame Class
390,867
<p>I'm starting out with wxPython and have been working my way through every tutorial and example I can get my hands on. I've run into a slight problem, however, and it has to do with the wx.App versus the wx.Frame and which should contain specific methods. Just about every example I've seen don't go much beyond layouts/sizers and event handling, none really tackle project organization of a wxPython project.</p> <p>For example, I have a method that gets a list of folders. The way most examples would deal with this would be to stick the method right in the frame class. This method has the potential to be used in several other parts of the application, so it would make more sense to store it at the application class level.</p> <p>How should I organize and call "universal" methods like these so that I don't clutter up my frame classes.</p> <p><strong>UPDATE:</strong></p> <p>To clarify, the "list of folders" was just an example, my actual method does a lot more work. What I'm saying is I have code that isn't Frame-specific. If I had this in the application class, what is the best way to call it from and event method in my frame.</p> <p>I'm looking for actual project organization techniques, not programming fundamentals.</p>
1
2008-12-24T06:07:30Z
395,992
<p>I probably should have been a lot clearer from the start, but I found what I was looking for:</p> <p><a href="http://wiki.wxpython.org/ModelViewController/" rel="nofollow">http://wiki.wxpython.org/ModelViewController/</a></p> <p>Burried within the wxpython wiki, I found several simple, concrete examples of MVC projects.</p>
2
2008-12-28T08:55:34Z
[ "python", "wxpython", "wxwidgets", "model-view-controller", "project-organization" ]
pyGTK Radio Button Help
391,237
<p>Alright, I'll preface this with the fact that I'm a GTK <em>and</em> Python newb, but I haven't been able to dig up the information I needed. Basically what I have is a list of Radio Buttons, and based on which one is checked, I need to connect a button to a different function. I tried creating all my radio buttons, and then creating a disgusting if/else block checking for sget_active() on each button. The problem is the same button returns true every single time. Any ideas?</p> <p>Here's the code in use:</p> <pre><code> #Radio Buttons Center self.updatePostRadioVBox = gtk.VBox(False, 0) self.updatePageRadio = gtk.RadioButton(None, "Updating Page") self.updatePostRadio = gtk.RadioButton(self.updatePageRadio, "Updating Blog Post") self.pageRadio = gtk.RadioButton(self.updatePageRadio, "New Page") self.blogRadio = gtk.RadioButton(self.updatePageRadio, "New Blog Post") self.addSpaceRadio = gtk.RadioButton(self.updatePageRadio, "Add New Space") self.removePageRadio = gtk.RadioButton(self.updatePageRadio, "Remove Page") self.removePostRadio = gtk.RadioButton(self.updatePageRadio, "Remove Blog Post") self.removeSpaceRadio = gtk.RadioButton(self.updatePageRadio, "Remove Space") #Now the buttons to direct us from here self.returnMainMenuButton = gtk.Button(" Main Menu ") self.returnMainMenuButton.connect("clicked", self.transToMain) self.contentManageHBoxBottom.pack_start(self.returnMainMenuButton, False, False, 30) self.contentProceedButton = gtk.Button(" Proceed ") self.contentManageHBoxBottom.pack_end(self.contentProceedButton, False, False, 30) if self.updatePageRadio.get_active(): self.contentProceedButton.connect("clicked", self.updatePage) elif self.updatePostRadio.get_active(): self.contentProceedButton.connect("clicked", self.updatePost) elif self.pageRadio.get_active(): self.contentProceedButton.connect("clicked", self.newPage) elif self.blogRadio.get_active(): self.contentProceedButton.connect("clicked", self.newBlogPost) elif self.addSpaceRadio.get_active(): self.contentProceedButton.connect("clicked", self.newSpace) elif self.removePageRadio.get_active(): self.contentProceedButton.connect("clicked", self.removePage) elif self.removePostRadio.get_active(): self.contentProceedButton.connect("clicked", self.removeBlogPost) elif self.removeSpaceRadio.get_active(): self.contentProceedButton.connect("clicked", self.removeSpace) </code></pre>
1
2008-12-24T10:54:03Z
391,288
<p>First, I presume that's a typo and you're actually calling get_active() in your code and not set_active()? Other than that, without seeing the code, I can point you to a pygtk tutorial about <a href="http://www.pygtk.org/pygtk2tutorial/sec-RadioButtons.html" rel="nofollow">radio buttons</a></p>
0
2008-12-24T11:31:58Z
[ "python", "gtk", "pygtk" ]
pyGTK Radio Button Help
391,237
<p>Alright, I'll preface this with the fact that I'm a GTK <em>and</em> Python newb, but I haven't been able to dig up the information I needed. Basically what I have is a list of Radio Buttons, and based on which one is checked, I need to connect a button to a different function. I tried creating all my radio buttons, and then creating a disgusting if/else block checking for sget_active() on each button. The problem is the same button returns true every single time. Any ideas?</p> <p>Here's the code in use:</p> <pre><code> #Radio Buttons Center self.updatePostRadioVBox = gtk.VBox(False, 0) self.updatePageRadio = gtk.RadioButton(None, "Updating Page") self.updatePostRadio = gtk.RadioButton(self.updatePageRadio, "Updating Blog Post") self.pageRadio = gtk.RadioButton(self.updatePageRadio, "New Page") self.blogRadio = gtk.RadioButton(self.updatePageRadio, "New Blog Post") self.addSpaceRadio = gtk.RadioButton(self.updatePageRadio, "Add New Space") self.removePageRadio = gtk.RadioButton(self.updatePageRadio, "Remove Page") self.removePostRadio = gtk.RadioButton(self.updatePageRadio, "Remove Blog Post") self.removeSpaceRadio = gtk.RadioButton(self.updatePageRadio, "Remove Space") #Now the buttons to direct us from here self.returnMainMenuButton = gtk.Button(" Main Menu ") self.returnMainMenuButton.connect("clicked", self.transToMain) self.contentManageHBoxBottom.pack_start(self.returnMainMenuButton, False, False, 30) self.contentProceedButton = gtk.Button(" Proceed ") self.contentManageHBoxBottom.pack_end(self.contentProceedButton, False, False, 30) if self.updatePageRadio.get_active(): self.contentProceedButton.connect("clicked", self.updatePage) elif self.updatePostRadio.get_active(): self.contentProceedButton.connect("clicked", self.updatePost) elif self.pageRadio.get_active(): self.contentProceedButton.connect("clicked", self.newPage) elif self.blogRadio.get_active(): self.contentProceedButton.connect("clicked", self.newBlogPost) elif self.addSpaceRadio.get_active(): self.contentProceedButton.connect("clicked", self.newSpace) elif self.removePageRadio.get_active(): self.contentProceedButton.connect("clicked", self.removePage) elif self.removePostRadio.get_active(): self.contentProceedButton.connect("clicked", self.removeBlogPost) elif self.removeSpaceRadio.get_active(): self.contentProceedButton.connect("clicked", self.removeSpace) </code></pre>
1
2008-12-24T10:54:03Z
391,289
<p>Edit: (since you posted some code), just use:</p> <pre><code>active = [r for r in self.updatePageRadio.get_group() if r.get_active()][0] </code></pre> <p>and use that to look up in a dict of functions and call it:</p> <pre><code>my_actions[active]() </code></pre> <p><hr /></p> <p>Edit: I totally forgot to mention that this is not a good use-case at all for RadioButtons, regular gtk.Button would be much better in my opinion.</p> <p><hr /></p> <p>Your answer is to use the RadioButton "groups" system. It is explained in <a href="http://www.pygtk.org/docs/pygtk/class-gtkradiobutton.html">this document</a>, but here is a small practical example.</p> <p>Firstly a group is really just a RadioButton itself that is used to collect a number of other RadioButtons. You specify a group as the first argument to the constructor.</p> <pre><code>r1 = gtk.RadioButton(None, label='Cat') # this has no group, it is the first r2 = gtk.RadioButton(r1, label='Mouse') # use the first radio # button as the group argument r3 = gtk.RadioButton(r1, label='Dog') # again use r1 </code></pre> <p>Now all the radio buttons will be synchronised. And the matter of reading them is as easy as:</p> <pre><code>active_radios = [r for r in r1.get_group() if r.get_active()] </code></pre>
7
2008-12-24T11:32:24Z
[ "python", "gtk", "pygtk" ]
Organising my Python project
391,879
<p>I'm starting a Python project and expect to have 20 or more classes in it. As is good practice I want to put them in a separate file each. However, the project directory quickly becomes swamped with files (or will when I do this).</p> <p>If I put a file to import in a folder I can no longer import it. How do I import a file from another folder and will I need to reference to the class it contains differently now that it's in a folder?</p> <p>Thanks in advance</p>
45
2008-12-24T17:23:14Z
391,899
<p>Create an <code>__init__.py</code> file in your projects folder, and it will be treated like a module by Python.</p> <p>Classes in your package directory can then be imported using syntax like:</p> <pre><code>from package import class import package.class </code></pre> <p>Within <code>__init__.py</code>, you may create an <code>__all__</code> array that defines <code>from package import *</code> behavior:</p> <pre><code># name1 and name2 will be available in calling module's namespace # when using "from package import *" syntax __all__ = ['name1', 'name2'] </code></pre> <p>And here is <a href="http://www.python.org/doc/essays/packages.html">way more information than you even want to know about packages in Python</a></p> <p>Generally speaking, a good way to learn about how to organize a lot of code is to pick a popular Python package and see how they did it. I'd check out <a href="http://www.djangoproject.com/">Django</a> and <a href="http://twistedmatrix.com/trac/">Twisted</a>, for starters.</p>
30
2008-12-24T17:31:40Z
[ "python", "project-organization" ]
Organising my Python project
391,879
<p>I'm starting a Python project and expect to have 20 or more classes in it. As is good practice I want to put them in a separate file each. However, the project directory quickly becomes swamped with files (or will when I do this).</p> <p>If I put a file to import in a folder I can no longer import it. How do I import a file from another folder and will I need to reference to the class it contains differently now that it's in a folder?</p> <p>Thanks in advance</p>
45
2008-12-24T17:23:14Z
391,902
<p>Python doesn't force you into Java's nasty one-class-per-file style. In fact, it's not even considered good style to put each class in a separate file unless they are huge. (If they are huge, you probably have to do refactoring anyway.) Instead, you should group similar classes and functions in modules. For example, if you are writing a GUI calculator, your package layout might look like this:</p> <pre><code>/amazingcalc /__init__.py # This makes it a Python package and importable. /evaluate.py # Contains the code to actually do calculations. /main.py # Starts the application /ui.py # Contains the code to make a pretty interface </code></pre>
13
2008-12-24T17:33:00Z
[ "python", "project-organization" ]
Organising my Python project
391,879
<p>I'm starting a Python project and expect to have 20 or more classes in it. As is good practice I want to put them in a separate file each. However, the project directory quickly becomes swamped with files (or will when I do this).</p> <p>If I put a file to import in a folder I can no longer import it. How do I import a file from another folder and will I need to reference to the class it contains differently now that it's in a folder?</p> <p>Thanks in advance</p>
45
2008-12-24T17:23:14Z
391,904
<p>simple answer is to create an empty file called <code>__init__.py</code> in the new folder you made. Then in your top level .py file include with something like:</p> <pre><code>import mynewsubfolder.mynewclass </code></pre>
7
2008-12-24T17:33:09Z
[ "python", "project-organization" ]