title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Compiled Python CGI | 895,163 | <p>Assuming the webserver is configured to handle <strong><em>.exe</em></strong>, Can i compile a python CGI file into an exe for speed. What would some pros and cons be to such a desession?</p>
| 0 | 2009-05-21T21:06:11Z | 895,181 | <p>Since the RDBMS and the network are the bottlenecks, I see no value in fussing around creating an EXE. </p>
<p>On average, most of a web site's transfers are static content (images, .CSS, .JS, etc.) which is best handled by Apache without any Python in the loop. This has huge impact.</p>
<p>Reserve Python for the "interesting" and "complex" parts of creating the dynamic HTML. Use a framework. </p>
| 0 | 2009-05-21T21:10:56Z | [
"python"
] |
Compiled Python CGI | 895,163 | <p>Assuming the webserver is configured to handle <strong><em>.exe</em></strong>, Can i compile a python CGI file into an exe for speed. What would some pros and cons be to such a desession?</p>
| 0 | 2009-05-21T21:06:11Z | 895,211 | <p>You probably don't want to run Python as a CGI if you want it fast. Look at proxies, mod_python, WSGI or FastCGI, as those techinques avoid re-loading python runtime and your app on each request.</p>
| 1 | 2009-05-21T21:15:14Z | [
"python"
] |
Bubble Sort Homework | 895,371 | <p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p>
<p>This is my attempt in Python:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
</code></pre>
<p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p>
<p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p>
<p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
| 113 | 2009-05-21T21:47:24Z | 895,405 | <p>This is what happens when you use variable name of negative meaning, you need to invert their values. The following would be easier to understand:</p>
<pre><code>sorted = False
while not sorted:
...
</code></pre>
<p>On the other hand, the logic of the algorithm is a little bit off. You need to check whether two elements swapped during the for loop. Here's how I would write it:</p>
<pre><code>def bubble(values):
length = len(values) - 1
sorted = False
while not sorted:
sorted = True
for element in range(0,length):
if values[element] > values[element + 1]:
hold = values[element + 1]
values[element + 1] = values[element]
values[element] = hold
sorted = False
return values
</code></pre>
| 9 | 2009-05-21T21:54:22Z | [
"python",
"algorithm",
"sorting",
"bubble-sort"
] |
Bubble Sort Homework | 895,371 | <p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p>
<p>This is my attempt in Python:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
</code></pre>
<p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p>
<p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p>
<p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
| 113 | 2009-05-21T21:47:24Z | 895,410 | <p>Your use of the Unsorted variable is wrong; you want to have a variable that tells you if you have swapped two elements; if you have done that, you can exit your loop, otherwise, you need to loop again. To fix what you've got here, just put the "unsorted = false" in the body of your if case; remove your else case; and put "unsorted = true before your <code>for</code> loop.</p>
| 8 | 2009-05-21T21:55:33Z | [
"python",
"algorithm",
"sorting",
"bubble-sort"
] |
Bubble Sort Homework | 895,371 | <p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p>
<p>This is my attempt in Python:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
</code></pre>
<p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p>
<p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p>
<p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
| 113 | 2009-05-21T21:47:24Z | 895,477 | <p>You've got a couple of errors in there. The first is in length, and the second is in your use of unsorted (as stated by McWafflestix). You probably also want to return the list if you're going to print it:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 2
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
unsorted = True
return badList
print bubble(mylist)
</code></pre>
<p>eta: You're right, the above is buggy as hell. My bad for not testing through some more examples.</p>
<pre><code>def bubble2(badList):
swapped = True
length = len(badList) - 2
while swapped:
swapped = False
for i in range(0, length):
if badList[i] > badList[i + 1]:
# swap
hold = badList[i + 1]
badList[i + 1] = badList[i]
badList[i] = hold
swapped = True
return badList
</code></pre>
| 2 | 2009-05-21T22:08:14Z | [
"python",
"algorithm",
"sorting",
"bubble-sort"
] |
Bubble Sort Homework | 895,371 | <p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p>
<p>This is my attempt in Python:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
</code></pre>
<p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p>
<p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p>
<p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
| 113 | 2009-05-21T21:47:24Z | 895,733 | <p>Answers provided by the-fury and Martin Cote fixed the problem of the infinite loop, but my code would still not work correctly (for a larger list, it would not sort correctly.). I ended up ditching the <code>unsorted</code> variable and used a counter instead.</p>
<pre><code>def bubble(badList):
length = len(badList) - 1
n = 0
while n < len(badList):
for element in range(0,length):
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
n = 0
else:
n += 1
return badList
if __name__ == '__main__':
mylist = [90, 10, 2, 76, 17, 66, 57, 23, 57, 99]
print bubble(mylist)
</code></pre>
<p>If anyone could provide any pointers on how to improve my code in the comments, it would be much appreciated.</p>
| 0 | 2009-05-21T23:12:40Z | [
"python",
"algorithm",
"sorting",
"bubble-sort"
] |
Bubble Sort Homework | 895,371 | <p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p>
<p>This is my attempt in Python:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
</code></pre>
<p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p>
<p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p>
<p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
| 113 | 2009-05-21T21:47:24Z | 895,748 | <pre><code>def bubble_sort(l):
for passes_left in range(len(l)-1, 0, -1):
for index in range(passes_left):
if l[index] < l[index + 1]:
l[index], l[index + 1] = l[index + 1], l[index]
return l
</code></pre>
| 3 | 2009-05-21T23:17:22Z | [
"python",
"algorithm",
"sorting",
"bubble-sort"
] |
Bubble Sort Homework | 895,371 | <p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p>
<p>This is my attempt in Python:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
</code></pre>
<p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p>
<p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p>
<p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
| 113 | 2009-05-21T21:47:24Z | 895,755 | <p>The goal of bubble sort is to move the <em>heavier</em> items at the bottom in each round, while moving the <em>lighter</em> items up. In the inner loop, where you compare the elements, <strong>you don't have to iterate the whole list in each turn</strong>. The <em>heaviest</em> is already placed last. The <em>swapped</em> variable is an extra check so we can mark that the list is now sorted and avoid continuing with unnecessary calculations.</p>
<pre><code>def bubble(badList):
length = len(badList)
for i in range(0,length):
swapped = False
for element in range(0, length-i-1):
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
swapped = True
if not swapped: break
return badList
</code></pre>
<p>Your version 1, corrected:</p>
<pre><code>def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
unsorted = False
for element in range(0,length):
#unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
unsorted = True
#print badList
#else:
#unsorted = True
return badList
</code></pre>
| 11 | 2009-05-21T23:18:39Z | [
"python",
"algorithm",
"sorting",
"bubble-sort"
] |
Bubble Sort Homework | 895,371 | <p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p>
<p>This is my attempt in Python:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
</code></pre>
<p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p>
<p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p>
<p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
| 113 | 2009-05-21T21:47:24Z | 902,736 | <p>To explain why your script isn't working right now, I'll rename the variable <code>unsorted</code> to <code>sorted</code>.</p>
<p>At first, your list isn't yet sorted. Of course, we set <code>sorted</code> to <code>False</code>.</p>
<p>As soon as we start the <code>while</code> loop, we assume that the list is already sorted. The idea is this: as soon as we find two elements that are not in the right order, we set <code>sorted</code> back to <code>False</code>. <code>sorted</code> will remain <code>True</code> <em>only if there were no elements in the wrong order</em>.</p>
<pre><code>sorted = False # We haven't started sorting yet
while not sorted:
sorted = True # Assume the list is now sorted
for element in range(0, length):
if badList[element] > badList[element + 1]:
sorted = False # We found two elements in the wrong order
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
# We went through the whole list. At this point, if there were no elements
# in the wrong order, sorted is still True. Otherwise, it's false, and the
# while loop executes again.
</code></pre>
<p>There are also minor little issues that would help the code be more efficient or readable.</p>
<ul>
<li><p>In the <code>for</code> loop, you use the variable <code>element</code>. Technically, <code>element</code> is not an element; it's a number representing a list index. Also, it's quite long. In these cases, just use a temporary variable name, like <code>i</code> for "index".</p>
<pre><code>for i in range(0, length):
</code></pre></li>
<li><p>The <code>range</code> command can also take just one argument (named <code>stop</code>). In that case, you get a list of all the integers from 0 to that argument.</p>
<pre><code>for i in range(length):
</code></pre></li>
<li><p>The <a href="http://www.python.org/dev/peps/pep-0008/">Python Style Guide</a> recommends that variables be named in lowercase with underscores. This is a very minor nitpick for a little script like this; it's more to get you accustomed to what Python code most often resembles.</p>
<pre><code>def bubble(bad_list):
</code></pre></li>
<li><p>To swap the values of two variables, write them as a tuple assignment. The right hand side gets evaluated as a tuple (say, <code>(badList[i+1], badList[i])</code> is <code>(3, 5)</code>) and then gets assigned to the two variables on the left hand side (<code>(badList[i], badList[i+1])</code>).</p>
<pre><code>bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i]
</code></pre></li>
</ul>
<p>Put it all together, and you get this:</p>
<pre><code>my_list = [12, 5, 13, 8, 9, 65]
def bubble(bad_list):
length = len(bad_list) - 1
sorted = False
while not sorted:
sorted = True
for i in range(length):
if bad_list[i] > bad_list[i+1]:
sorted = False
bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i]
bubble(my_list)
print my_list
</code></pre>
<p>(I removed your print statement too, by the way.)</p>
| 106 | 2009-05-23T23:49:07Z | [
"python",
"algorithm",
"sorting",
"bubble-sort"
] |
Bubble Sort Homework | 895,371 | <p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p>
<p>This is my attempt in Python:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
</code></pre>
<p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p>
<p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p>
<p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
| 113 | 2009-05-21T21:47:24Z | 16,005,368 | <p>#A very simple function, can be optimized (obviously) by decreasing the problem space of the 2nd array. But same O(n^2) complexity.</p>
<pre><code>def bubble(arr):
l = len(arr)
for a in range(l):
for b in range(l-1):
if (arr[a] < arr[b]):
arr[a], arr[b] = arr[b], arr[a]
return arr
</code></pre>
| 1 | 2013-04-14T23:01:18Z | [
"python",
"algorithm",
"sorting",
"bubble-sort"
] |
Bubble Sort Homework | 895,371 | <p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p>
<p>This is my attempt in Python:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
</code></pre>
<p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p>
<p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p>
<p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
| 113 | 2009-05-21T21:47:24Z | 21,217,166 | <p>I am a fresh fresh beginner, started to read about Python yesterday.
Inspired by your example I created something maybe more in the 80-ties style, but nevertheless it kinda works</p>
<pre><code>lista1 = [12, 5, 13, 8, 9, 65]
i=0
while i < len(lista1)-1:
if lista1[i] > lista1[i+1]:
x = lista1[i]
lista1[i] = lista1[i+1]
lista1[i+1] = x
i=0
continue
else:
i+=1
print(lista1)
</code></pre>
| 0 | 2014-01-19T13:09:36Z | [
"python",
"algorithm",
"sorting",
"bubble-sort"
] |
Bubble Sort Homework | 895,371 | <p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p>
<p>This is my attempt in Python:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
</code></pre>
<p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p>
<p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p>
<p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
| 113 | 2009-05-21T21:47:24Z | 21,298,077 | <p>The problem with the original algorithm is that if you had a lower number further in the list, it would not bring it to the correct sorted position. The program needs to go back the the beginning each time to ensure that the numbers sort all the way through.</p>
<p>I simplified the code and it will now work for any list of numbers regardless of the list and even if there are repeating numbers. Here's the code</p>
<pre><code>mylist = [9, 8, 5, 4, 12, 1, 7, 5, 2]
print mylist
def bubble(badList):
length = len(badList) - 1
element = 0
while element < length:
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
element = 0
print badList
else:
element = element + 1
print bubble(mylist)
</code></pre>
| 1 | 2014-01-23T02:16:20Z | [
"python",
"algorithm",
"sorting",
"bubble-sort"
] |
Bubble Sort Homework | 895,371 | <p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p>
<p>This is my attempt in Python:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
</code></pre>
<p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p>
<p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p>
<p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
| 113 | 2009-05-21T21:47:24Z | 24,583,756 | <pre><code>def bubble_sort(l):
exchanged = True
iteration = 0
n = len(l)
while(exchanged):
iteration += 1
exchanged = False
# Move the largest element to the end of the list
for i in range(n-1):
if l[i] > l[i+1]:
exchanged = True
l[i], l[i+1] = l[i+1], l[i]
n -= 1 # Largest element already towards the end
print 'Iterations: %s' %(iteration)
return l
</code></pre>
| 1 | 2014-07-05T06:41:12Z | [
"python",
"algorithm",
"sorting",
"bubble-sort"
] |
Bubble Sort Homework | 895,371 | <p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p>
<p>This is my attempt in Python:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
</code></pre>
<p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p>
<p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p>
<p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
| 113 | 2009-05-21T21:47:24Z | 28,551,860 | <pre><code>def bubbleSort(alist):
if len(alist) <= 1:
return alist
for i in range(0,len(alist)):
print "i is :%d",i
for j in range(0,i):
print "j is:%d",j
print "alist[i] is :%d, alist[j] is :%d"%(alist[i],alist[j])
if alist[i] > alist[j]:
alist[i],alist[j] = alist[j],alist[i]
return alist
</code></pre>
<p>alist = [54,26,93,17,77,31,44,55,20,-23,-34,16,11,11,11]</p>
<p>print bubbleSort(alist) </p>
| 1 | 2015-02-16T23:02:43Z | [
"python",
"algorithm",
"sorting",
"bubble-sort"
] |
Bubble Sort Homework | 895,371 | <p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p>
<p>This is my attempt in Python:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
</code></pre>
<p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p>
<p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p>
<p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
| 113 | 2009-05-21T21:47:24Z | 29,086,629 | <pre><code>def bubble_sort(a):
t = 0
sorted = False # sorted = False because we have not began to sort
while not sorted:
sorted = True # Assume sorted = True first, it will switch only there is any change
for key in range(1,len(a)):
if a[key-1] > a[key]:
sorted = False
t = a[key-1]; a[key-1] = a[key]; a[key] = t;
print a
</code></pre>
| 0 | 2015-03-16T20:47:13Z | [
"python",
"algorithm",
"sorting",
"bubble-sort"
] |
Bubble Sort Homework | 895,371 | <p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p>
<p>This is my attempt in Python:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
</code></pre>
<p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p>
<p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p>
<p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
| 113 | 2009-05-21T21:47:24Z | 32,392,195 | <p>A simpler example:</p>
<pre><code>a = len(alist)-1
while a > 0:
for b in range(0,a):
#compare with the adjacent element
if alist[b]>=alist[b+1]:
#swap both elements
alist[b], alist[b+1] = alist[b+1], alist[b]
a-=1
</code></pre>
<p>This simply takes the elements from 0 to a(basically, all the unsorted elements in that round) and compares it with its adjacent element, and making a swap if it is greater than its adjacent element. At the end the round, the last element is sorted, and the process runs again without it, until all elements have been sorted.</p>
<p>There is no need for a condition whether <code>sort</code> is true or not.</p>
<p>Note that this algorithm takes into consideration the position of the numbers only when swapping, so repeated numbers will not affect it.</p>
<p>PS. I know it has been very long since this question was posted, but I just wanted to share this idea.</p>
| 1 | 2015-09-04T07:13:41Z | [
"python",
"algorithm",
"sorting",
"bubble-sort"
] |
Bubble Sort Homework | 895,371 | <p>In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them.</p>
<p>This is my attempt in Python:</p>
<pre><code>mylist = [12, 5, 13, 8, 9, 65]
def bubble(badList):
length = len(badList) - 1
unsorted = True
while unsorted:
for element in range(0,length):
unsorted = False
if badList[element] > badList[element + 1]:
hold = badList[element + 1]
badList[element + 1] = badList[element]
badList[element] = hold
print badList
else:
unsorted = True
print bubble(mylist)
</code></pre>
<p>Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely.</p>
<p>How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size?</p>
<p>P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet.</p>
| 113 | 2009-05-21T21:47:24Z | 37,822,474 | <pre><code>def bubble_sort(li):
l = len(li)
tmp = None
sorted_l = sorted(li)
while (li != sorted_l):
for ele in range(0,l-1):
if li[ele] > li[ele+1]:
tmp = li[ele+1]
li[ele+1] = li [ele]
li[ele] = tmp
return li
</code></pre>
| 0 | 2016-06-14T21:30:58Z | [
"python",
"algorithm",
"sorting",
"bubble-sort"
] |
What if I want to store a None value in the memcache? | 895,386 | <p>This is specifically related to the Google App Engine Memcache API, but I'm sure it also applies to other Memcache tools.</p>
<p>The dictionary .get() method allows you to specify a default value, such as dict.get('key', 'defaultval')</p>
<p>This can be useful if it's possible you might want to store None as a value in a dictionary. </p>
<p>However, the memcache.get() does not let you to do this. I've modified my @memoize decorator so it looks like this:</p>
<pre><code>def memoize(keyformat, time=1000000):
"""Decorator to memoize functions using memcache."""
def decorator(fxn):
def wrapper(*args, **kwargs):
key = keyformat + str(args[1:]) + str(kwargs)
from google.appengine.api import memcache
data = memcache.get(key)
if Debug(): return fxn(*args, **kwargs)
if data:
if data is 'None': data = None
return data
data = fxn(*args, **kwargs)
if data is None: data = 'None'
memcache.set(key, data, time)
return data
return wrapper
return decorator
</code></pre>
<p>Now I'm sure there's a good argument that I shouldn't be storing None values in the first place, but let's put that aside for now. Is there a better way I can handle this besides converting None vals to strings and back?</p>
| 10 | 2009-05-21T21:50:03Z | 895,579 | <p>A possible way to do this is to create new class that defines <code>None</code> for this purpose, and assign instances of this to the cache (unfortunately you cannot extend <code>None</code>). Alternatively, you could use the empty string "", or avoid storing None/null values altogether (absence of the key implies None).</p>
<p>Then check for instances of your 'None' class when you check the result of <code>mc.get(key)</code> (<code>is None</code>, <code>== ""</code>, etc)</p>
| 7 | 2009-05-21T22:29:26Z | [
"python",
"google-app-engine",
"memcached"
] |
What if I want to store a None value in the memcache? | 895,386 | <p>This is specifically related to the Google App Engine Memcache API, but I'm sure it also applies to other Memcache tools.</p>
<p>The dictionary .get() method allows you to specify a default value, such as dict.get('key', 'defaultval')</p>
<p>This can be useful if it's possible you might want to store None as a value in a dictionary. </p>
<p>However, the memcache.get() does not let you to do this. I've modified my @memoize decorator so it looks like this:</p>
<pre><code>def memoize(keyformat, time=1000000):
"""Decorator to memoize functions using memcache."""
def decorator(fxn):
def wrapper(*args, **kwargs):
key = keyformat + str(args[1:]) + str(kwargs)
from google.appengine.api import memcache
data = memcache.get(key)
if Debug(): return fxn(*args, **kwargs)
if data:
if data is 'None': data = None
return data
data = fxn(*args, **kwargs)
if data is None: data = 'None'
memcache.set(key, data, time)
return data
return wrapper
return decorator
</code></pre>
<p>Now I'm sure there's a good argument that I shouldn't be storing None values in the first place, but let's put that aside for now. Is there a better way I can handle this besides converting None vals to strings and back?</p>
| 10 | 2009-05-21T21:50:03Z | 896,359 | <p>Not really.</p>
<p>You could store a None value as an empty string, but there isn't really a way to store special data in a memcache.</p>
<p>What's the difference between the cache key not existing and the cache value being None? It's probably better to unify these two situations.</p>
| 0 | 2009-05-22T04:33:50Z | [
"python",
"google-app-engine",
"memcached"
] |
What if I want to store a None value in the memcache? | 895,386 | <p>This is specifically related to the Google App Engine Memcache API, but I'm sure it also applies to other Memcache tools.</p>
<p>The dictionary .get() method allows you to specify a default value, such as dict.get('key', 'defaultval')</p>
<p>This can be useful if it's possible you might want to store None as a value in a dictionary. </p>
<p>However, the memcache.get() does not let you to do this. I've modified my @memoize decorator so it looks like this:</p>
<pre><code>def memoize(keyformat, time=1000000):
"""Decorator to memoize functions using memcache."""
def decorator(fxn):
def wrapper(*args, **kwargs):
key = keyformat + str(args[1:]) + str(kwargs)
from google.appengine.api import memcache
data = memcache.get(key)
if Debug(): return fxn(*args, **kwargs)
if data:
if data is 'None': data = None
return data
data = fxn(*args, **kwargs)
if data is None: data = 'None'
memcache.set(key, data, time)
return data
return wrapper
return decorator
</code></pre>
<p>Now I'm sure there's a good argument that I shouldn't be storing None values in the first place, but let's put that aside for now. Is there a better way I can handle this besides converting None vals to strings and back?</p>
| 10 | 2009-05-21T21:50:03Z | 921,038 | <p>You could do something like what Haskell and Scala does and store an Option dictionary. The dictionary contains two keys: one key to indicate that it is valid and one key that is used to hold the data. Something like this:</p>
<pre><code>{valid: true, data: whatyouwanttostore}
</code></pre>
<p>Then if <code>get</code> return None, you know that the cache was missed; if the result is a dictionary with None as the data, the you know that the data was in the cache but that it was false.</p>
| 2 | 2009-05-28T14:10:46Z | [
"python",
"google-app-engine",
"memcached"
] |
Using python to develop web application | 895,420 | <p>I have been doing some work in python, but that was all for stand alone applications. I'm curious to know whether any offshoot of python supports web development?</p>
<p>Would some one also suggest a good tutorial or a website from where I can pick up some of the basics of web development using python?</p>
| 16 | 2009-05-21T21:58:58Z | 895,439 | <p>Lookup Django.</p>
| 0 | 2009-05-21T22:02:33Z | [
"python"
] |
Using python to develop web application | 895,420 | <p>I have been doing some work in python, but that was all for stand alone applications. I'm curious to know whether any offshoot of python supports web development?</p>
<p>Would some one also suggest a good tutorial or a website from where I can pick up some of the basics of web development using python?</p>
| 16 | 2009-05-21T21:58:58Z | 895,456 | <p>Python can be used for web development, but there isn't a special language extension or anything in the language that will handle all the HTML generation or that works like PHP.</p>
<p>It's pretty much run through some sort of interpreter on a web server (CGI, mod_python, etc.).</p>
<p>I would recommend looking into <a href="http://wiki.python.org/moin/WebFrameworks" rel="nofollow">Python Web Application Frameworks</a> or how to write <a href="http://wiki.python.org/moin/CgiScripts" rel="nofollow">Python CGI scripts</a>.</p>
| 0 | 2009-05-21T22:05:45Z | [
"python"
] |
Using python to develop web application | 895,420 | <p>I have been doing some work in python, but that was all for stand alone applications. I'm curious to know whether any offshoot of python supports web development?</p>
<p>Would some one also suggest a good tutorial or a website from where I can pick up some of the basics of web development using python?</p>
| 16 | 2009-05-21T21:58:58Z | 895,466 | <p><a href="http://wiki.python.org/moin/WebFrameworks" rel="nofollow">Python Wiki: Web Frameworks for Python</a></p>
<p>If you decide to use <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>, <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/" rel="nofollow">the official tutorial</a> is an excellent place to start. <a href="http://www.djangobook.com/" rel="nofollow">The Django Book</a> is also free.</p>
| 2 | 2009-05-21T22:06:48Z | [
"python"
] |
Using python to develop web application | 895,420 | <p>I have been doing some work in python, but that was all for stand alone applications. I'm curious to know whether any offshoot of python supports web development?</p>
<p>Would some one also suggest a good tutorial or a website from where I can pick up some of the basics of web development using python?</p>
| 16 | 2009-05-21T21:58:58Z | 895,472 | <p>There are <a href="http://en.wikipedia.org/wiki/Comparison%5Fof%5Fweb%5Fapplication%5Fframeworks" rel="nofollow">quite a few</a> web frameworks for python out there, but the only one I've used is <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>, and I really like it.</p>
<p>If you've got a few hours, do the <a href="http://docs.djangoproject.com/en/dev/intro/install/" rel="nofollow">tutorial</a>, I promise you, you'll enjoy it :)</p>
| 0 | 2009-05-21T22:07:25Z | [
"python"
] |
Using python to develop web application | 895,420 | <p>I have been doing some work in python, but that was all for stand alone applications. I'm curious to know whether any offshoot of python supports web development?</p>
<p>Would some one also suggest a good tutorial or a website from where I can pick up some of the basics of web development using python?</p>
| 16 | 2009-05-21T21:58:58Z | 895,473 | <p><strong>Edited 3 years later</strong>: Don't use mod_python, use mod_wsgi. Flask and Werkzeug are good frameworks too. Needing to know what's going on is useful, but it isn't a requirement. That would be stupid. </p>
<p>Don't lookup Django until you have a good grasp of what Django is doing on your behalf. for you. Write some basic apps using mod_python and it's request object. I just started learning Python for web-development using mod_python and it has been great.</p>
<p>mod_python also uses a dispatcher in site-packages/mod_python/publisher.py. Have a ganders through this to see how requests can be handled in a simple-ish way.</p>
<p>You may need to add a bit of config to your Apache config file to get mod_python up and running but the mod_python site explains it well.</p>
<pre><code><Directory /path/to/python/files>
AddHandler mod_python .py
PythonHandler mod_python.publisher
PythonDebug On
</Directory>
</code></pre>
<p>And you are away!</p>
<p>use (as a stupidly basic example):</p>
<pre><code>def foo(req):
req.write("Hello World")
</code></pre>
<p>in <code>/path/to/python/files/bar.py</code> assuming <code>/path/to</code> is your site root.</p>
<p>And then you can do </p>
<pre><code>http://www.mysite.com/python/files/bar/foo
</code></pre>
<p>to see "Hello World". Also, something that <strong>tripped me up</strong> is the dispatcher uses a lame method to work out the content-type, so to force HTML use:</p>
<pre><code>req.content_type = 'text/html'
</code></pre>
<p><strong>Good Luck</strong></p>
<p>After you have a good idea of how Python interacts with mod_python and Apache, then use a framework that does all the boring stuff for you. Up to you though, just my recommendation</p>
| 4 | 2009-05-21T22:07:28Z | [
"python"
] |
Using python to develop web application | 895,420 | <p>I have been doing some work in python, but that was all for stand alone applications. I'm curious to know whether any offshoot of python supports web development?</p>
<p>Would some one also suggest a good tutorial or a website from where I can pick up some of the basics of web development using python?</p>
| 16 | 2009-05-21T21:58:58Z | 895,533 | <p>As others have mentioned, one of the more prominent python "offshoots" as you call them would be <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>. It is a rather powerful framework that allows you to quickly and securely build web applications. The first place to look would be <a href="http://docs.djangoproject.com/en/dev/intro/overview/#intro-overview" rel="nofollow">their overview</a> which gives some insight as to what Django does as a framework.</p>
<p>Going through <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/" rel="nofollow">their tutorial</a> taught me alot about the prominent Model-View-Controler design pattern and how it may be used in a web-development context. I found it a great way to start writing an application that worked and learn by improving it.</p>
| 0 | 2009-05-21T22:19:28Z | [
"python"
] |
Using python to develop web application | 895,420 | <p>I have been doing some work in python, but that was all for stand alone applications. I'm curious to know whether any offshoot of python supports web development?</p>
<p>Would some one also suggest a good tutorial or a website from where I can pick up some of the basics of web development using python?</p>
| 16 | 2009-05-21T21:58:58Z | 897,015 | <p>If you really don't want to delve into the frameworks - and you should, I heartily recommend Django or Pylons - there's still need to go down the road of CGI. This is a totally out-of-date technology, not to mention slow and inefficient.</p>
<p>There <em>is</em> a standard way of building Python web applications, and it's called <a href="http://www.wsgi.org/" rel="nofollow">WSGI</a>. If you want to roll your own web app from scratch, this is absolutely the way to go.</p>
<p>That said, if you're just starting out, really you should go with one of the frameworks.</p>
| 3 | 2009-05-22T09:14:49Z | [
"python"
] |
Using python to develop web application | 895,420 | <p>I have been doing some work in python, but that was all for stand alone applications. I'm curious to know whether any offshoot of python supports web development?</p>
<p>Would some one also suggest a good tutorial or a website from where I can pick up some of the basics of web development using python?</p>
| 16 | 2009-05-21T21:58:58Z | 897,434 | <p>Now that everyone has said <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01/">Django</a>, I can add my two cents: I would argue that you might learn more by looking at the different components first, before using Django. For web development with Python, you often want 3 components:</p>
<ol>
<li><p>Something that takes care
of the HTTP stuff (e.g.
<a href="http://www.cherrypy.org/">CherryPy</a>)</p></li>
<li><p>A templating language
to create your web pages.
<a href="http://www.makotemplates.org/">Mako</a>
is very pythonic and <a href="http://docs.cherrypy.org/stable/progguide/choosingtemplate.html">works</a> with Cherrpy.</p></li>
<li><p>If you get your data from a
database, an ORM comes in handy.
<a href="http://www.sqlalchemy.org/">SQLAlchemy</a>
would be an <a href="https://bitbucket.org/Lawouach/cherrypy-recipes/src/c8290261eefb/web/database/sql_alchemy/">example</a>.</p></li>
</ol>
<p>All the links above have good tutorials. For many real-world use-cases, Django will be a better solution than such a stack as it seamlessly integrates this functionality (and more). And if you need a CMS, Django is your best bet short of Zope. Nevertheless, to get a good grasp of what's going on, a stack of loosely coupled programs might be better. Django hides a lot of the details.</p>
| 21 | 2009-05-22T11:35:19Z | [
"python"
] |
Using python to develop web application | 895,420 | <p>I have been doing some work in python, but that was all for stand alone applications. I'm curious to know whether any offshoot of python supports web development?</p>
<p>Would some one also suggest a good tutorial or a website from where I can pick up some of the basics of web development using python?</p>
| 16 | 2009-05-21T21:58:58Z | 908,362 | <p>There are a couple of choices for web development. From my experience, your choice will again be dependent on your application. I used <a href="http://djangoproject.com" rel="nofollow">django</a> and <a href="http://webpy.org/" rel="nofollow">web.py</a> in production and I am about to deploy an app based on <a href="http://pylonshq.com/" rel="nofollow">pylons</a>.</p>
<p><a href="http://djangoproject.com" rel="nofollow">Django</a> hides a lot of choices (comes with its ORM and templating). The documentation is extensive and well-written. There are many reusable app available for django, but you will likely to invest a little time in integrating them seamlessly. One thing <a href="http://www.youtube.com/watch?v=fipFKyW2FA4" rel="nofollow">mentioned on djangocon 08</a> was the fact, that there is cool stuff in django, which can't be easily
accessed in non-django projects.</p>
<p><a href="http://webpy.org/" rel="nofollow">web.py</a> impressed me by its raw simplicity. Before I knew it, I wrote a small app (<a href="http://myyn.org/localwiki" rel="nofollow">78 lines quasi-wiki</a>) in it. </p>
<p><a href="http://pylonshq.com/" rel="nofollow">pylons</a> feels like in the middle of both. I can use <a href="http://www.sqlalchemy.org/" rel="nofollow">sqlalchemy</a> and <a href="http://jinja.pocoo.org/2/" rel="nofollow">jinja</a>, all in all a pleasant experience for the start.</p>
| 1 | 2009-05-25T23:25:10Z | [
"python"
] |
Django App Dependency Cycle | 895,454 | <p>I am in the middle of developing a Django application, which has quite complicated models (it models a university - courses, modules, lectures, students etc.)</p>
<p>I have separated the project into apps, to make the whole thing more organised (apps are courses, schools, people, modules and timeperiods). I am having a problem whereby a model in one app may depend on a model in another - so I must import it. The second app then in turn depends on a model in the first, so there is a cycle and Python throws up an error.</p>
<p>How do people deal with this? I understand that apps should be relatively "independent", but in a system like this it doesn't make sense, for example, to use ContentTypes to link students to a module.</p>
<p>Does anyone have a similar project that could comment on this case?</p>
| 19 | 2009-05-21T22:05:33Z | 895,984 | <p>Normally I advocate for splitting functionality into smaller apps, but a circular dependence between models reflects such a tight integration that you're probably not gaining much from the split and might just consider merging the apps. If that results in an app that feels too large, there may be a way to make the split along a different axis, resulting in a more sane dependency graph.</p>
| 1 | 2009-05-22T00:56:03Z | [
"python",
"django",
"dependencies"
] |
Django App Dependency Cycle | 895,454 | <p>I am in the middle of developing a Django application, which has quite complicated models (it models a university - courses, modules, lectures, students etc.)</p>
<p>I have separated the project into apps, to make the whole thing more organised (apps are courses, schools, people, modules and timeperiods). I am having a problem whereby a model in one app may depend on a model in another - so I must import it. The second app then in turn depends on a model in the first, so there is a cycle and Python throws up an error.</p>
<p>How do people deal with this? I understand that apps should be relatively "independent", but in a system like this it doesn't make sense, for example, to use ContentTypes to link students to a module.</p>
<p>Does anyone have a similar project that could comment on this case?</p>
| 19 | 2009-05-21T22:05:33Z | 896,090 | <p>If you're seeing circular model dependency I'm guessing that one of three things is happening:</p>
<ul>
<li>You've defined an inverse relationship to one that's already defined (for instance both course has many lectures and lecture has one course) which is redundant in django</li>
<li>You have a model method in the wrong app</li>
<li>You're providing functionality in a model method that ought to be in a manager</li>
</ul>
<p>Maybe you could show us what's happening in these models and we can try to figure out why the problem is arising. Circular model dependency is rarely an indication that you need to combine two apps - it's more likely (though not definitely the case) that there's a problem with one of your model definitions.</p>
<p>p.s. I <em>am</em> working on a similar django application, but my app structure is probably quite different to your's. I'd be happy to give you a high-level description of it if you're interested.</p>
| 2 | 2009-05-22T01:58:07Z | [
"python",
"django",
"dependencies"
] |
Django App Dependency Cycle | 895,454 | <p>I am in the middle of developing a Django application, which has quite complicated models (it models a university - courses, modules, lectures, students etc.)</p>
<p>I have separated the project into apps, to make the whole thing more organised (apps are courses, schools, people, modules and timeperiods). I am having a problem whereby a model in one app may depend on a model in another - so I must import it. The second app then in turn depends on a model in the first, so there is a cycle and Python throws up an error.</p>
<p>How do people deal with this? I understand that apps should be relatively "independent", but in a system like this it doesn't make sense, for example, to use ContentTypes to link students to a module.</p>
<p>Does anyone have a similar project that could comment on this case?</p>
| 19 | 2009-05-21T22:05:33Z | 896,995 | <p>If your dependency is with foreign keys referencing models in other applications, you <em>don't</em> need to import the other model. You can use a string in your ForeignKey definition:</p>
<pre><code>class MyModel(models.Model):
myfield = models.ForeignKey('myotherapp.MyOtherModel')
</code></pre>
<p>This way there's no need to import MyOtherModel, so no circular reference. Django resolves the string internally, and it all works as expected.</p>
| 48 | 2009-05-22T09:08:17Z | [
"python",
"django",
"dependencies"
] |
Django App Dependency Cycle | 895,454 | <p>I am in the middle of developing a Django application, which has quite complicated models (it models a university - courses, modules, lectures, students etc.)</p>
<p>I have separated the project into apps, to make the whole thing more organised (apps are courses, schools, people, modules and timeperiods). I am having a problem whereby a model in one app may depend on a model in another - so I must import it. The second app then in turn depends on a model in the first, so there is a cycle and Python throws up an error.</p>
<p>How do people deal with this? I understand that apps should be relatively "independent", but in a system like this it doesn't make sense, for example, to use ContentTypes to link students to a module.</p>
<p>Does anyone have a similar project that could comment on this case?</p>
| 19 | 2009-05-21T22:05:33Z | 7,874,086 | <p>This may not be well-suited to your situation, but ignoring the Django aspect to your question, the general technique for breaking circular dependencies is to break out one of the cross-referenced items into a new module. For example:</p>
<pre><code>moduleA: class1, class2
| ^
v |
moduleB: class3, class4
</code></pre>
<p>could become:</p>
<pre><code>moduleC: class 3
^
|
moduleA: class 1, class 2
^
|
moduleB: class 4
</code></pre>
<p>(Or alternatively, you could have broken class 2 out into its own module. Or both!)</p>
<p>Of course, this is no help if class A & B depend on each other. In that case, maybe they should be in the same module, or better still, maybe some part of these classes could be broken out into a third module, which both classes depend upon.</p>
| 3 | 2011-10-24T10:12:36Z | [
"python",
"django",
"dependencies"
] |
Can reading a list from a disk be better than loading a dictionary? | 895,500 | <p>I am building an application where I am trying to allow users to submit a list of company and date pairs and find out whether or not there was a news event on that date. The news events are stored in a dictionary with a company identifier and a date as a key. </p>
<pre><code>newsDict('identifier','MM/DD/YYYY')=[list of news events for that date]
</code></pre>
<p>The dictionary turned out to be much larger than I thought-too big even to build it in memory so I broke it down into three pieces, each piece is limited to a particular range of company identifiers. </p>
<p>My plan was to take the user submitted list and using a dictionary group the user list of company identifiers to match the particular newsDict that the company events would be expected to be found and then load the newsDicts one after another to get the values.</p>
<p>Well now I am wondering if it would not be better to keep the news events in a list with each item of the list being a sublist list of a tuple and another list</p>
<pre><code>[('identifier','MM/DD/YYYY'),[list of news events for that date]]
</code></pre>
<p>my thought then is that I would have a dictionary that would have the range of the list for each company identifier</p>
<pre><code> companyDict['identifier']=(begofRangeinListforComp,endofRangeinListforComp)
</code></pre>
<p>I would use the user input to look up the ranges I needed and construct a list of the identifiers and ranges sorted by the ranges. Then I would just read the appropriate section of the list to get the data and construct the output.</p>
<p>The biggest reason I see for this is that even with the dictionary broken into thirds each section takes about two minutes to load on my machine and the dictionary ends up taking about 600 to 750 mb of ram. </p>
<p>I was surprised to note that a list of eight million lines took only about 15 seconds to load and used about 1/3 of the memory of the dictionary that had 1/3 the entries.</p>
<p>Further, since I can discard the lines in the list as I work through the list I will be freeing memory as I work down the user list. </p>
<p>I am surprised as I thought a dictionary would be the most efficient way to do this. but my poking at it suggests that the dictionary requires significantly more memory than a list. My reading of other posts on SO and elsewhere suggests that any other structure is going to require pointer allocations that are more expensive than list pointers. Am I missing something here and is there a better way to do this?</p>
<p>After reading Alberto's answer and response to my comment I spent some time trying to figure out how to write the function if I were to use a db. Now I might be hobbled here because I don't know much about db programming but </p>
<p>I think the code to implement using a db would be much more complicated than:</p>
<pre><code>outList=[]
massiveFile=open('theFile','r')
for identifier in sortedUserList
# I get the list and sort it by the key of the dictionary
identifierList=massiveFile[theDict[identifier]['beginPosit']:theDict[identifier]['endPosit']+1]
for item in identifierList:
if item.startswith(manipulation of the identifier)
outList.append(item)
</code></pre>
<p>I have to wrap this in a function I didn't see anything that would be as comparably simple if I converted the list to a db.</p>
<p>Of course simpler was not the reason to bring me to this forum. I still don't see that using another structure will cost less memory. I have 30000 company identifiers and approximately 3600 dates. Each item in my list is an object in the parlance of OOD. That is where I am struggling I spent six hours this morning organizing the data for a dictionary before I gave up. Spending that amount of time to implement a database and then find that I am using half a gig or more of someone else's memory to load it seems problematic</p>
| 2 | 2009-05-21T22:12:17Z | 895,528 | <p>With such a large amount of data, you should be using a database. This would be far better than looking at a list, and would be the most appropriate way of storing your data anyway. If you're using Python, it has SQLite built in I believe.</p>
| 5 | 2009-05-21T22:18:34Z | [
"python",
"list",
"dictionary",
"performance"
] |
Can reading a list from a disk be better than loading a dictionary? | 895,500 | <p>I am building an application where I am trying to allow users to submit a list of company and date pairs and find out whether or not there was a news event on that date. The news events are stored in a dictionary with a company identifier and a date as a key. </p>
<pre><code>newsDict('identifier','MM/DD/YYYY')=[list of news events for that date]
</code></pre>
<p>The dictionary turned out to be much larger than I thought-too big even to build it in memory so I broke it down into three pieces, each piece is limited to a particular range of company identifiers. </p>
<p>My plan was to take the user submitted list and using a dictionary group the user list of company identifiers to match the particular newsDict that the company events would be expected to be found and then load the newsDicts one after another to get the values.</p>
<p>Well now I am wondering if it would not be better to keep the news events in a list with each item of the list being a sublist list of a tuple and another list</p>
<pre><code>[('identifier','MM/DD/YYYY'),[list of news events for that date]]
</code></pre>
<p>my thought then is that I would have a dictionary that would have the range of the list for each company identifier</p>
<pre><code> companyDict['identifier']=(begofRangeinListforComp,endofRangeinListforComp)
</code></pre>
<p>I would use the user input to look up the ranges I needed and construct a list of the identifiers and ranges sorted by the ranges. Then I would just read the appropriate section of the list to get the data and construct the output.</p>
<p>The biggest reason I see for this is that even with the dictionary broken into thirds each section takes about two minutes to load on my machine and the dictionary ends up taking about 600 to 750 mb of ram. </p>
<p>I was surprised to note that a list of eight million lines took only about 15 seconds to load and used about 1/3 of the memory of the dictionary that had 1/3 the entries.</p>
<p>Further, since I can discard the lines in the list as I work through the list I will be freeing memory as I work down the user list. </p>
<p>I am surprised as I thought a dictionary would be the most efficient way to do this. but my poking at it suggests that the dictionary requires significantly more memory than a list. My reading of other posts on SO and elsewhere suggests that any other structure is going to require pointer allocations that are more expensive than list pointers. Am I missing something here and is there a better way to do this?</p>
<p>After reading Alberto's answer and response to my comment I spent some time trying to figure out how to write the function if I were to use a db. Now I might be hobbled here because I don't know much about db programming but </p>
<p>I think the code to implement using a db would be much more complicated than:</p>
<pre><code>outList=[]
massiveFile=open('theFile','r')
for identifier in sortedUserList
# I get the list and sort it by the key of the dictionary
identifierList=massiveFile[theDict[identifier]['beginPosit']:theDict[identifier]['endPosit']+1]
for item in identifierList:
if item.startswith(manipulation of the identifier)
outList.append(item)
</code></pre>
<p>I have to wrap this in a function I didn't see anything that would be as comparably simple if I converted the list to a db.</p>
<p>Of course simpler was not the reason to bring me to this forum. I still don't see that using another structure will cost less memory. I have 30000 company identifiers and approximately 3600 dates. Each item in my list is an object in the parlance of OOD. That is where I am struggling I spent six hours this morning organizing the data for a dictionary before I gave up. Spending that amount of time to implement a database and then find that I am using half a gig or more of someone else's memory to load it seems problematic</p>
| 2 | 2009-05-21T22:12:17Z | 896,125 | <p>The dictionary will take more memory because it is effectively a hash.</p>
<p>You don't have to go so far as using a database, since your lookup requirements are so simple. Just use the file system.</p>
<p>Create a directory structure based on the company name (or ticker), with subdirectories for each date. To find whether data exists and load it up, just form the name of the subdirectory where the data would be, and see if it exists.</p>
<p>E.g., IBM news for May 21 would be in C:\db\IBM\20090521\news.txt, if in fact there were news for that day. You just check if the file exists; no searches.</p>
<p>If you want to try and boost speed from there, come up with a scheme to cache a limited amount of results that are likely to be frequently requested (assuming you're operating a server). For that, you'd use a hash.</p>
| 1 | 2009-05-22T02:15:54Z | [
"python",
"list",
"dictionary",
"performance"
] |
Looking for help, just started with Python today. (3.0) | 895,637 | <p>I am just trying to get into python, but I've found it very difficult to find any resource that is Python 3. All I've got so far is diveintopython3.org, and its limited. Anyways, I was just trying to get a feel for the language by doing some very basic stuff, but I can't figure out why this little program won't do what I intend, which is to add 2 numbers. I'm sure someone here knows how to fix it, but any other resources that contain tutorials in Python 3 would be greatly appreciated:</p>
<pre><code>def add(num=0,num2=0):
sumEm = (num+num2)
print (sumEm)
if __name__ == '__main__':
num = input("Enter a number: ")
num2 = input("Enter a number: ")
add(num,num2)
</code></pre>
<p>output:</p>
<pre><code>Enter a number: 23
Enter a number: 24
23
24
</code></pre>
| 1 | 2009-05-21T22:45:27Z | 895,657 | <p><a href="http://www.swaroopch.com/notes/Python%5Fen:Table%5Fof%5FContents" rel="nofollow">A Byte of Python</a> covers Python 3 in detail. There's also a 2.X version of the book, which can help compare and contrast the differences in the languages.</p>
<p>To fix your problem, you need to convert the input taken into an integer. It's stored as a string by default.</p>
<pre><code>num = int(input("Enter a number: "))
num2 = int(input("Enter a number: "))
</code></pre>
| 7 | 2009-05-21T22:50:00Z | [
"python",
"python-3.x"
] |
Looking for help, just started with Python today. (3.0) | 895,637 | <p>I am just trying to get into python, but I've found it very difficult to find any resource that is Python 3. All I've got so far is diveintopython3.org, and its limited. Anyways, I was just trying to get a feel for the language by doing some very basic stuff, but I can't figure out why this little program won't do what I intend, which is to add 2 numbers. I'm sure someone here knows how to fix it, but any other resources that contain tutorials in Python 3 would be greatly appreciated:</p>
<pre><code>def add(num=0,num2=0):
sumEm = (num+num2)
print (sumEm)
if __name__ == '__main__':
num = input("Enter a number: ")
num2 = input("Enter a number: ")
add(num,num2)
</code></pre>
<p>output:</p>
<pre><code>Enter a number: 23
Enter a number: 24
23
24
</code></pre>
| 1 | 2009-05-21T22:45:27Z | 895,673 | <p>You didn't say what you <em>do</em> get - I'm guessing <code>num</code> and <code>num2</code> concatenated, as the <a href="http://docs.python.org/3.0/library/functions.html#input" rel="nofollow"><code>input</code></a> returns a string. Adding two strings just concatenates them. If you expect <code>num</code> and <code>num2</code> to represent integers, you could use <a href="http://docs.python.org/3.0/library/functions.html#int" rel="nofollow"><code>int</code></a> to convert the strings into integers:</p>
<pre><code>num = int(input("Enter a number:")
num2 = int(input("Enter a number:")
</code></pre>
<p>And you'll likely get better results. Note there's still room for better error-checking, but this might get you started.</p>
<p>One other thing to try - add a line at the end of your <code>__main__</code> like this:</p>
<pre><code>add(4, 3)
</code></pre>
<p>and see what gets printed. That will tell you whether the fault is with <code>add</code> or with your input routines.</p>
<p>Of course, none of that provided you with a resource - are the online docs not helping? I'd start with the <a href="http://docs.python.org/3.0/tutorial/index.html" rel="nofollow">tutorial</a>, if you haven't already.</p>
| 3 | 2009-05-21T22:53:31Z | [
"python",
"python-3.x"
] |
Looking for help, just started with Python today. (3.0) | 895,637 | <p>I am just trying to get into python, but I've found it very difficult to find any resource that is Python 3. All I've got so far is diveintopython3.org, and its limited. Anyways, I was just trying to get a feel for the language by doing some very basic stuff, but I can't figure out why this little program won't do what I intend, which is to add 2 numbers. I'm sure someone here knows how to fix it, but any other resources that contain tutorials in Python 3 would be greatly appreciated:</p>
<pre><code>def add(num=0,num2=0):
sumEm = (num+num2)
print (sumEm)
if __name__ == '__main__':
num = input("Enter a number: ")
num2 = input("Enter a number: ")
add(num,num2)
</code></pre>
<p>output:</p>
<pre><code>Enter a number: 23
Enter a number: 24
23
24
</code></pre>
| 1 | 2009-05-21T22:45:27Z | 895,677 | <p>There's an Addison-Wesley book by Mark Summerfield called "Programming in Python 3", and I have found it to be the best Python book I've read. One nice thing for you, I would imagine, is that Summerfield does not bring up differences between 2.X and 3.x, so someone just picking up Python gets an uninterrupted view of (new and improved) Python. Add to this that he explains things that the other books --- in my case from 1.X --- either never touched or (I think) misstated. The paragraphs on custom exceptions just got me out of a jam, and his treatment of * and ** as unpacking operators cleared up considerable mental fog for me. Top-notch book.</p>
<p>BTW, there's a module called sys that does useful things, like let you access command line arguments. Those args are (sub)strings, and the other day I had to use int(), as commenter dkbits says, to put them to use. (The type() function tells you what type Python considers a variable to be.) I had:</p>
<pre><code>import sys
#Parse the command line.
if len(sys.argv) != 4:
print "Usage: commandName maxValueInCell targetSum nCellsInGroup"
exit()
else:
maxv = int( sys.argv[1])
tgt = int( sys.argv[2])
nc = int( sys.argv[3])
print "maxv =",maxv, "; tgt = ",tgt, "; nc = ",nc
print type(sys.argv[1]) #strings
print type(sys.argv[2])
print type(sys.argv[3])
print type(maxv) #ints
print type(tgt)
print type(nc)
</code></pre>
| 0 | 2009-05-21T22:54:11Z | [
"python",
"python-3.x"
] |
Looking for help, just started with Python today. (3.0) | 895,637 | <p>I am just trying to get into python, but I've found it very difficult to find any resource that is Python 3. All I've got so far is diveintopython3.org, and its limited. Anyways, I was just trying to get a feel for the language by doing some very basic stuff, but I can't figure out why this little program won't do what I intend, which is to add 2 numbers. I'm sure someone here knows how to fix it, but any other resources that contain tutorials in Python 3 would be greatly appreciated:</p>
<pre><code>def add(num=0,num2=0):
sumEm = (num+num2)
print (sumEm)
if __name__ == '__main__':
num = input("Enter a number: ")
num2 = input("Enter a number: ")
add(num,num2)
</code></pre>
<p>output:</p>
<pre><code>Enter a number: 23
Enter a number: 24
23
24
</code></pre>
| 1 | 2009-05-21T22:45:27Z | 895,699 | <p>Interesting, 3 answers, and none of them address your problem correctly.</p>
<p>All you have to do is this:</p>
<pre><code>def add(num=0,num2=0):
sumEm = (int(num)+int(num2)) # may need the int() because in python 3.0 the manual says it only returns strings
return sumEm # use return here not print
</code></pre>
| 1 | 2009-05-21T22:59:46Z | [
"python",
"python-3.x"
] |
How can I start an interactive program(like gdb) from python? | 896,031 | <p>I am going to start up gdb from python.</p>
<p>For example:</p>
<pre><code>prog.shell.py:
#do lots of things
#
#
p.subprocess.Popen("gdb --args myprog", shell=True, stdin=sys.stdin, stdout=sys.stdout)
</code></pre>
<p>But the gdb is not invoked as I expected, the interaction with gdb is broken. I have also tried os.system(), but it still doesnt work. What might I be doing wrong?</p>
| 1 | 2009-05-22T01:21:59Z | 896,037 | <p>I think you meant</p>
<pre><code>p = subprocess.Popen(...)
</code></pre>
<p>You probably need to wait for p to finish:</p>
<pre><code>p.wait()
</code></pre>
| 3 | 2009-05-22T01:27:21Z | [
"python",
"gdb"
] |
Can't create games with pygame | 896,062 | <p>I make a game with python 2.5 and pygame.</p>
<p>but,I can't complete make.
because this errors occured.</p>
<pre><code>C:\Python26\TypeType\src\dist\Main.exe:8: RuntimeWarning: use font: MemoryLoadLibrary failed loading pygame\font.pyd
Traceback (most recent call last):
File "Main.py", line 8, in <module>
File "pygame\__init__.pyo", line 70, in __getattr__
NotImplementedError: font module not available
Traceback (most recent call last):
File "Main.py", line 8, in <module>
File "pygame\sysfont.pyo", line 253, in SysFont
RuntimeError: default font not found 'freesansbold.ttf'
</code></pre>
<p>Perhaps I think that the reason is because it used an object called sysfont. (Because I had the programs that did not use sysfont on an execute file and was able to start with the PC which was not installed Python in)
What's wrong .
sorry I'm begginer.</p>
<p><strong>EDIT</strong>
I can find Python2.5\Lib\site-packages\pygame\freesansbold.ttf</p>
<p>but same error occured..
Where may I copy freesansbold.ttf</p>
| 0 | 2009-05-22T01:42:01Z | 896,080 | <p>It looks like you don't have the <code>freesansbold.ttf</code> file on your computer in an accessible fonts folder. This font should have come with Pygame in the <code>lib</code> directory.</p>
<p>Check the installation folder for your copy of Pygame, and if it's there, modify your Python installation's font path to include that directory. If not, you'll need to find a copy or download a newer version of Pygame.</p>
| 1 | 2009-05-22T01:49:52Z | [
"python",
"fonts",
"pygame"
] |
Can't create games with pygame | 896,062 | <p>I make a game with python 2.5 and pygame.</p>
<p>but,I can't complete make.
because this errors occured.</p>
<pre><code>C:\Python26\TypeType\src\dist\Main.exe:8: RuntimeWarning: use font: MemoryLoadLibrary failed loading pygame\font.pyd
Traceback (most recent call last):
File "Main.py", line 8, in <module>
File "pygame\__init__.pyo", line 70, in __getattr__
NotImplementedError: font module not available
Traceback (most recent call last):
File "Main.py", line 8, in <module>
File "pygame\sysfont.pyo", line 253, in SysFont
RuntimeError: default font not found 'freesansbold.ttf'
</code></pre>
<p>Perhaps I think that the reason is because it used an object called sysfont. (Because I had the programs that did not use sysfont on an execute file and was able to start with the PC which was not installed Python in)
What's wrong .
sorry I'm begginer.</p>
<p><strong>EDIT</strong>
I can find Python2.5\Lib\site-packages\pygame\freesansbold.ttf</p>
<p>but same error occured..
Where may I copy freesansbold.ttf</p>
| 0 | 2009-05-22T01:42:01Z | 1,250,718 | <p>A simple solution would be to simply load the font directly instead of using sysfont. Just use the pygame.font.Font class and directly load a ttf file. This will also make it easier to use py2exe, and you can choose exactly the font you want.</p>
| 2 | 2009-08-09T05:17:25Z | [
"python",
"fonts",
"pygame"
] |
Can't create games with pygame | 896,062 | <p>I make a game with python 2.5 and pygame.</p>
<p>but,I can't complete make.
because this errors occured.</p>
<pre><code>C:\Python26\TypeType\src\dist\Main.exe:8: RuntimeWarning: use font: MemoryLoadLibrary failed loading pygame\font.pyd
Traceback (most recent call last):
File "Main.py", line 8, in <module>
File "pygame\__init__.pyo", line 70, in __getattr__
NotImplementedError: font module not available
Traceback (most recent call last):
File "Main.py", line 8, in <module>
File "pygame\sysfont.pyo", line 253, in SysFont
RuntimeError: default font not found 'freesansbold.ttf'
</code></pre>
<p>Perhaps I think that the reason is because it used an object called sysfont. (Because I had the programs that did not use sysfont on an execute file and was able to start with the PC which was not installed Python in)
What's wrong .
sorry I'm begginer.</p>
<p><strong>EDIT</strong>
I can find Python2.5\Lib\site-packages\pygame\freesansbold.ttf</p>
<p>but same error occured..
Where may I copy freesansbold.ttf</p>
| 0 | 2009-05-22T01:42:01Z | 31,501,648 | <p>You probably found a solution but i want to give one for other.
Create you game with pygame. Then, unzip the librairy file.
Go to </p>
<blockquote>
<p>PythonX.X\Lib\site-packages\pygame and copy freesansbold.ttf</p>
</blockquote>
<p>Back to your library file that you unzipped and go to </p>
<blockquote>
<p>library\pygame</p>
</blockquote>
<p>Put freesansbold.ttf in and zip library.</p>
<p>Now, it's work ! :)</p>
| 0 | 2015-07-19T13:20:55Z | [
"python",
"fonts",
"pygame"
] |
Properly importing modules in Python | 896,112 | <p>How do I set up module imports so that each module can access the objects of all the others?</p>
<p>I have a medium size Python application with modules files in various subdirectories. I have created modules that append these subdirectories to <code>sys.path</code> and imports a group of modules, using <code>import thisModule as tm</code>. Module objects are referred to with that qualification. I then import that module into the others with <code>from moduleImports import *</code>. The code is sloppy right now and has several of these things, which are often duplicative.</p>
<p>First, the application is failing because some module references aren't assigned. This same code does run when unit tested.</p>
<p>Second, I'm worried that I'm causing a problem with recursive module imports. Importing moduleImports imports thisModule, which imports moduleImports . . . .</p>
<p>What is the right way to do this?</p>
| 9 | 2009-05-22T02:09:07Z | 896,128 | <p>You won't get recursion on imports because Python caches each module and won't reload one it already has.</p>
| 3 | 2009-05-22T02:17:58Z | [
"python",
"python-import"
] |
Properly importing modules in Python | 896,112 | <p>How do I set up module imports so that each module can access the objects of all the others?</p>
<p>I have a medium size Python application with modules files in various subdirectories. I have created modules that append these subdirectories to <code>sys.path</code> and imports a group of modules, using <code>import thisModule as tm</code>. Module objects are referred to with that qualification. I then import that module into the others with <code>from moduleImports import *</code>. The code is sloppy right now and has several of these things, which are often duplicative.</p>
<p>First, the application is failing because some module references aren't assigned. This same code does run when unit tested.</p>
<p>Second, I'm worried that I'm causing a problem with recursive module imports. Importing moduleImports imports thisModule, which imports moduleImports . . . .</p>
<p>What is the right way to do this?</p>
| 9 | 2009-05-22T02:09:07Z | 896,137 | <p>Few pointers</p>
<ol>
<li><p>You may have already split
functionality in various module. If
correctly done most of the time you
will not fall into circular import
problems (e.g. if module a depends
on b and b on a you can make a third
module c to remove such circular
dependency). As last resort, in a
import b but in b import a at the
point where a is needed e.g. inside
function.</p></li>
<li><p>Once functionality is properly in
modules group them in packages under
a subdir and add a <code>__init__.py</code> file
to it so that you can import the
package. Keep such pakages in a
folder e.g. lib and then either add
to sys.path or set PYTHONPATH env
variable</p></li>
<li><p>from module import * may not
be good idea. Instead, import whatever
is needed. It may be fully qualified. It
doesn't hurt to be verbose. e.g.
from pakageA.moduleB import
CoolClass.</p></li>
</ol>
| 5 | 2009-05-22T02:20:43Z | [
"python",
"python-import"
] |
Properly importing modules in Python | 896,112 | <p>How do I set up module imports so that each module can access the objects of all the others?</p>
<p>I have a medium size Python application with modules files in various subdirectories. I have created modules that append these subdirectories to <code>sys.path</code> and imports a group of modules, using <code>import thisModule as tm</code>. Module objects are referred to with that qualification. I then import that module into the others with <code>from moduleImports import *</code>. The code is sloppy right now and has several of these things, which are often duplicative.</p>
<p>First, the application is failing because some module references aren't assigned. This same code does run when unit tested.</p>
<p>Second, I'm worried that I'm causing a problem with recursive module imports. Importing moduleImports imports thisModule, which imports moduleImports . . . .</p>
<p>What is the right way to do this?</p>
| 9 | 2009-05-22T02:09:07Z | 897,001 | <p>The way to do this is to avoid magic. In other words, if your module requires something from another module, it should import it explicitly. You shouldn't rely on things being imported automatically.</p>
<p>As the Zen of Python (<code>import this</code>) has it, explicit is better than implicit.</p>
| 4 | 2009-05-22T09:10:17Z | [
"python",
"python-import"
] |
Properly importing modules in Python | 896,112 | <p>How do I set up module imports so that each module can access the objects of all the others?</p>
<p>I have a medium size Python application with modules files in various subdirectories. I have created modules that append these subdirectories to <code>sys.path</code> and imports a group of modules, using <code>import thisModule as tm</code>. Module objects are referred to with that qualification. I then import that module into the others with <code>from moduleImports import *</code>. The code is sloppy right now and has several of these things, which are often duplicative.</p>
<p>First, the application is failing because some module references aren't assigned. This same code does run when unit tested.</p>
<p>Second, I'm worried that I'm causing a problem with recursive module imports. Importing moduleImports imports thisModule, which imports moduleImports . . . .</p>
<p>What is the right way to do this?</p>
| 9 | 2009-05-22T02:09:07Z | 897,186 | <p><strong>"I have a medium size Python application with modules files in various subdirectories."</strong></p>
<p>Good. Make absolutely sure that each directory include a <code>__init__.py</code> file, so that it's a package.</p>
<p><strong>"I have created modules that append these subdirectories to <code>sys.path</code>"</strong></p>
<p>Bad. Use <code>PYTHONPATH</code> or install the whole structure <code>Lib/site-packages</code>. Don't update <code>sys.path</code> dynamically. It's a bad thing. Hard to manage and maintain.</p>
<p><strong>"imports a group of modules, using <code>import thisModule as tm</code>."</strong></p>
<p>Doesn't make sense. Perhaps you have one <code>import thisModule as tm</code> for each module in your structure. This is typical, standard practice: import just the modules you need, no others.</p>
<p><strong>"I then import that module into the others with <code>from moduleImports import *</code>"</strong></p>
<p>Bad. Don't blanket import a bunch of random stuff.</p>
<p>Each module should have a longish list of the specific things it needs. </p>
<pre><code>import this
import that
import package.module
</code></pre>
<p>Explicit list. No magic. No dynamic change to <code>sys.path</code>.</p>
<p>My current project has 100's of modules, a dozen or so packages. Each module imports just what it needs. No magic.</p>
| 19 | 2009-05-22T10:05:51Z | [
"python",
"python-import"
] |
More efficient movements editing python files in vim | 896,145 | <p>Given a python file with the following repeated endlessly:</p>
<pre><code>def myFunction(a, b, c):
if a:
print b
elif c:
print 'hello'
</code></pre>
<p>I'd like to move around and edit this file using familiar vim movements. For instance, using (, ), [[, ]], {, } or deleting/yanking/changing text using commands like di}.</p>
<p>In other languages (like C++, Java, C#, etc) you've got curly brackets abound, so using a movement like di} can easily find a matching curly brace and act on that block. And in fact if I am on the 'b' character on the above text and do a di) in vim, it successfully deletes the text between the two parens.</p>
<p>The issue is in python's detection of code blocks, I think. Using (, ), [[, ]], {, or } as movements all pretty much do the same thing, bringing you to the start (above or on the def line) or end (after the last line of the function) of the function. And there is no way, as far as I know, to easily tell vim "select everything for this indentation block." In the above example, I'd like to be on in 'i' of the if line, type di} and have it delete the entire if block (to the end of this particular function).</p>
<p>I'm sure it should be possible to tell vim to operate on an indentation basis for such movements (well, maybe not that particular movement, but some user defined action). Any thoughts on how to accomplish this?</p>
| 36 | 2009-05-22T02:25:37Z | 898,557 | <p>It's very easy to move indented blocks when you have <code>set foldmethod=indent</code>. For example, if you're on the <code>def main():</code> line in the following snippet:</p>
<pre><code>def main():
+-- 35 lines: gps.init()-----------------------------------------------------
if __name__ == "__main__": main()
</code></pre>
<p>then <code>dj</code> takes the whole main function and it can be pasted elsewhere.</p>
| 6 | 2009-05-22T15:45:11Z | [
"python",
"vim",
"editing"
] |
More efficient movements editing python files in vim | 896,145 | <p>Given a python file with the following repeated endlessly:</p>
<pre><code>def myFunction(a, b, c):
if a:
print b
elif c:
print 'hello'
</code></pre>
<p>I'd like to move around and edit this file using familiar vim movements. For instance, using (, ), [[, ]], {, } or deleting/yanking/changing text using commands like di}.</p>
<p>In other languages (like C++, Java, C#, etc) you've got curly brackets abound, so using a movement like di} can easily find a matching curly brace and act on that block. And in fact if I am on the 'b' character on the above text and do a di) in vim, it successfully deletes the text between the two parens.</p>
<p>The issue is in python's detection of code blocks, I think. Using (, ), [[, ]], {, or } as movements all pretty much do the same thing, bringing you to the start (above or on the def line) or end (after the last line of the function) of the function. And there is no way, as far as I know, to easily tell vim "select everything for this indentation block." In the above example, I'd like to be on in 'i' of the if line, type di} and have it delete the entire if block (to the end of this particular function).</p>
<p>I'm sure it should be possible to tell vim to operate on an indentation basis for such movements (well, maybe not that particular movement, but some user defined action). Any thoughts on how to accomplish this?</p>
| 36 | 2009-05-22T02:25:37Z | 1,315,239 | <p>More information on the Vim script refred to above:</p>
<p><a href="http://www.vim.org/scripts/script.php?script_id=386">http://www.vim.org/scripts/script.php?script_id=386</a></p>
<p>python_match.vim : Extend the % motion and define g%, [%, and ]% motions for Python files</p>
<p>description
This script redefines the % motion so that (in addition to its usual behavior)
it cycles through if/elif/else, try/except/catch, for/continue/break, and
while/continue/break structures. The script also
defines g% to cycle in the opposite direction. Two other motions, [% and ]%,
go to the start and end of the current block, respectively.</p>
<p>All of these motions should work in Normal, Visual, and Operator-pending
modes. For example, d]% should delete (characterwise) until the end of the
current block; v]%d should do the same, going through Visual mode so that
you can see what is being deleted; and V]%d makes it linewise.</p>
| 11 | 2009-08-22T05:44:32Z | [
"python",
"vim",
"editing"
] |
More efficient movements editing python files in vim | 896,145 | <p>Given a python file with the following repeated endlessly:</p>
<pre><code>def myFunction(a, b, c):
if a:
print b
elif c:
print 'hello'
</code></pre>
<p>I'd like to move around and edit this file using familiar vim movements. For instance, using (, ), [[, ]], {, } or deleting/yanking/changing text using commands like di}.</p>
<p>In other languages (like C++, Java, C#, etc) you've got curly brackets abound, so using a movement like di} can easily find a matching curly brace and act on that block. And in fact if I am on the 'b' character on the above text and do a di) in vim, it successfully deletes the text between the two parens.</p>
<p>The issue is in python's detection of code blocks, I think. Using (, ), [[, ]], {, or } as movements all pretty much do the same thing, bringing you to the start (above or on the def line) or end (after the last line of the function) of the function. And there is no way, as far as I know, to easily tell vim "select everything for this indentation block." In the above example, I'd like to be on in 'i' of the if line, type di} and have it delete the entire if block (to the end of this particular function).</p>
<p>I'm sure it should be possible to tell vim to operate on an indentation basis for such movements (well, maybe not that particular movement, but some user defined action). Any thoughts on how to accomplish this?</p>
| 36 | 2009-05-22T02:25:37Z | 1,394,173 | <p>Here is a VIM script <a href="http://www.vim.org/scripts/script.php?script_id=30">http://www.vim.org/scripts/script.php?script_id=30</a></p>
<p>which makes it much easier to navigate around python code blocks.</p>
<p>Shortcuts:</p>
<ul>
<li>]t -- Jump to beginning of block</li>
<li>]e -- Jump to end of block</li>
<li>]v -- Select (Visual Line Mode) block</li>
<li>]< -- Shift block to left</li>
<li>]> -- Shift block to right</li>
<li>]# -- Comment selection</li>
<li>]u -- Uncomment selection</li>
<li>]c -- Select current/previous class</li>
<li>]d -- Select current/previous function</li>
<li>]<up> -- Jump to previous line with the same/lower indentation</li>
<li>]<down> -- Jump to next line with the same/lower indentation</li>
</ul>
| 16 | 2009-09-08T13:56:12Z | [
"python",
"vim",
"editing"
] |
More efficient movements editing python files in vim | 896,145 | <p>Given a python file with the following repeated endlessly:</p>
<pre><code>def myFunction(a, b, c):
if a:
print b
elif c:
print 'hello'
</code></pre>
<p>I'd like to move around and edit this file using familiar vim movements. For instance, using (, ), [[, ]], {, } or deleting/yanking/changing text using commands like di}.</p>
<p>In other languages (like C++, Java, C#, etc) you've got curly brackets abound, so using a movement like di} can easily find a matching curly brace and act on that block. And in fact if I am on the 'b' character on the above text and do a di) in vim, it successfully deletes the text between the two parens.</p>
<p>The issue is in python's detection of code blocks, I think. Using (, ), [[, ]], {, or } as movements all pretty much do the same thing, bringing you to the start (above or on the def line) or end (after the last line of the function) of the function. And there is no way, as far as I know, to easily tell vim "select everything for this indentation block." In the above example, I'd like to be on in 'i' of the if line, type di} and have it delete the entire if block (to the end of this particular function).</p>
<p>I'm sure it should be possible to tell vim to operate on an indentation basis for such movements (well, maybe not that particular movement, but some user defined action). Any thoughts on how to accomplish this?</p>
| 36 | 2009-05-22T02:25:37Z | 28,284,564 | <h1><a href="https://github.com/klen/python-mode" rel="nofollow">python-mode</a></h1>
<p>This vim plugin provides motions similar to built-in ones:</p>
<pre class="lang-none prettyprint-override"><code>2.4 Vim motion ~
*pymode-motion*
Support Vim motion (See |operator|) for python objects (such as functions,
class and methods).
`C` â means class
`M` â means method or function
*pymode-motion-keys*
========== ============================
Key Command (modes)
========== ============================
[[ Jump to previous class or function (normal, visual, operator)
]] Jump to next class or function (normal, visual, operator)
[M Jump to previous class or method (normal, visual, operator)
]M Jump to next class or method (normal, visual, operator)
aC Select a class. Ex: vaC, daC, yaC, caC (normal, operator)
iC Select inner class. Ex: viC, diC, yiC, ciC (normal, operator)
aM Select a function or method. Ex: vaM, daM, yaM, caM (normal, operator)
iM Select inner func. or method. Ex: viM, diM, yiM, ciM (normal, operator)
========== ============================
</code></pre>
<h3>Update vim8</h3>
<p><code>$VIMRUNTIME/ftplugin/python.vim</code> now (2016-09-08) includes these mappings. See <a href="https://github.com/vim/vim/blob/abd468ed0fbcba391e7833feeaa7de3ced841455/runtime/ftplugin/python.vim" rel="nofollow">ftplugin/python.vim@abd468ed0</a>.<br>
However, if you use the textobjects <code>aC,iC,aM,iM</code>, you still need the plugin <code>python-mode</code>.</p>
| 5 | 2015-02-02T18:44:46Z | [
"python",
"vim",
"editing"
] |
More efficient movements editing python files in vim | 896,145 | <p>Given a python file with the following repeated endlessly:</p>
<pre><code>def myFunction(a, b, c):
if a:
print b
elif c:
print 'hello'
</code></pre>
<p>I'd like to move around and edit this file using familiar vim movements. For instance, using (, ), [[, ]], {, } or deleting/yanking/changing text using commands like di}.</p>
<p>In other languages (like C++, Java, C#, etc) you've got curly brackets abound, so using a movement like di} can easily find a matching curly brace and act on that block. And in fact if I am on the 'b' character on the above text and do a di) in vim, it successfully deletes the text between the two parens.</p>
<p>The issue is in python's detection of code blocks, I think. Using (, ), [[, ]], {, or } as movements all pretty much do the same thing, bringing you to the start (above or on the def line) or end (after the last line of the function) of the function. And there is no way, as far as I know, to easily tell vim "select everything for this indentation block." In the above example, I'd like to be on in 'i' of the if line, type di} and have it delete the entire if block (to the end of this particular function).</p>
<p>I'm sure it should be possible to tell vim to operate on an indentation basis for such movements (well, maybe not that particular movement, but some user defined action). Any thoughts on how to accomplish this?</p>
| 36 | 2009-05-22T02:25:37Z | 32,072,543 | <p>To address your final paragraph, the following script defines a new "indent" text-object that you can perform actions on. For instance, <kbd>d</kbd><kbd>i</kbd><kbd>i</kbd> deletes everything indented at the same level as the line the cursor is on.</p>
<p>See the plugin's documentation for more info: <a href="http://www.vim.org/scripts/script.php?script_id=3037" rel="nofollow">http://www.vim.org/scripts/script.php?script_id=3037</a></p>
| 0 | 2015-08-18T12:32:14Z | [
"python",
"vim",
"editing"
] |
More efficient movements editing python files in vim | 896,145 | <p>Given a python file with the following repeated endlessly:</p>
<pre><code>def myFunction(a, b, c):
if a:
print b
elif c:
print 'hello'
</code></pre>
<p>I'd like to move around and edit this file using familiar vim movements. For instance, using (, ), [[, ]], {, } or deleting/yanking/changing text using commands like di}.</p>
<p>In other languages (like C++, Java, C#, etc) you've got curly brackets abound, so using a movement like di} can easily find a matching curly brace and act on that block. And in fact if I am on the 'b' character on the above text and do a di) in vim, it successfully deletes the text between the two parens.</p>
<p>The issue is in python's detection of code blocks, I think. Using (, ), [[, ]], {, or } as movements all pretty much do the same thing, bringing you to the start (above or on the def line) or end (after the last line of the function) of the function. And there is no way, as far as I know, to easily tell vim "select everything for this indentation block." In the above example, I'd like to be on in 'i' of the if line, type di} and have it delete the entire if block (to the end of this particular function).</p>
<p>I'm sure it should be possible to tell vim to operate on an indentation basis for such movements (well, maybe not that particular movement, but some user defined action). Any thoughts on how to accomplish this?</p>
| 36 | 2009-05-22T02:25:37Z | 34,286,586 | <h2><a href="https://github.com/alfredodeza/chapa.vim" rel="nofollow">chapa.vim</a></h2>
<p>A multi-language vim plugin to move (or visually select) the next/previous class, method or function; out of the box support for python and javascript.</p>
<pre class="lang-none prettyprint-override"><code>" Function Movement
nmap <buffer> fnf <Plug>ChapaNextFunction
nmap <buffer> fpf <Plug>ChapaPreviousFunction
" Class Movement
nmap <buffer> fnc <Plug>ChapaNextClass
nmap <buffer> fpc <Plug>ChapaPreviousClass
" Method Movement
nmap <buffer> fnm <Plug>ChapaNextMethod
nmap <buffer> fpm <Plug>ChapaPreviousMethod
</code></pre>
| 0 | 2015-12-15T10:21:42Z | [
"python",
"vim",
"editing"
] |
How to show hidden autofield in django formset | 896,153 | <p>A Django autofield when displayed using a formset is hidden by default. What would be the best way to show it?</p>
<p>At the moment, the model is declared as,</p>
<pre><code>class MyModel:
locid = models.AutoField(primary_key=True)
...
</code></pre>
<p>When this is rendered using Django formsets, </p>
<pre><code>class MyModelForm(ModelForm):
class Meta:
model = MyModel
fields = ('locid', 'name')
</code></pre>
<p>it shows up on the page as,</p>
<pre><code><input id="id_form-0-locid" type="hidden" value="707" name="form-0-locid"/>
</code></pre>
<p>Thanks.</p>
<p><hr /></p>
<p><strong>Edit</strong></p>
<p>I create the formset like this -</p>
<pre><code>LocFormSet = modelformset_factory(MyModel)
pformset = LocFormSet(request.POST, request.FILES, queryset=MyModel.objects.order_by('name'))
</code></pre>
<p><hr /></p>
<p><strong>Second Edit</strong></p>
<p>Looks like I'm not using the custom form class I defined there, so the question needs slight modification..</p>
<p><em>How would I create a formset from a custom form (which will show a hidden field), as well as use a custom queryset?</em></p>
<p>At the moment, I can either inherit from a BaseModelFormSet class and use a custom query set, or I can use the ModelForm class to add a custom field to a <strong>form</strong>. Is there a way to do both with a formset?</p>
<p><hr /></p>
<p><strong>Third Edit</strong></p>
<p>I'm now using,</p>
<pre><code>class MyModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
locid = forms.IntegerField(min_value = 1, required=True)
self.fields['locid'].widget.attrs["type"] = 'visible'
self.queryset = MyModel.objects.order_by('name')
class Meta:
model = MyModel
fields = ('locid', 'name')
LocFormSet = modelformset_factory(MyModel, form = MyModelForm)
pformset = LocFormSet()
</code></pre>
<p>But this still doesn't </p>
<ul>
<li>Show locid</li>
<li>Use the custom query that was specified.</li>
</ul>
| 2 | 2009-05-22T02:29:31Z | 896,160 | <p>Try changing the default field type:</p>
<pre><code>from django import forms
class MyModelForm(ModelForm):
locid = forms.IntegerField(min_value=1, required=True)
class Meta:
model = MyModel
fields = ('locid', 'name')
</code></pre>
<p><strong>EDIT:</strong> Tested and works...</p>
| 2 | 2009-05-22T02:34:17Z | [
"python",
"django",
"formset"
] |
How to show hidden autofield in django formset | 896,153 | <p>A Django autofield when displayed using a formset is hidden by default. What would be the best way to show it?</p>
<p>At the moment, the model is declared as,</p>
<pre><code>class MyModel:
locid = models.AutoField(primary_key=True)
...
</code></pre>
<p>When this is rendered using Django formsets, </p>
<pre><code>class MyModelForm(ModelForm):
class Meta:
model = MyModel
fields = ('locid', 'name')
</code></pre>
<p>it shows up on the page as,</p>
<pre><code><input id="id_form-0-locid" type="hidden" value="707" name="form-0-locid"/>
</code></pre>
<p>Thanks.</p>
<p><hr /></p>
<p><strong>Edit</strong></p>
<p>I create the formset like this -</p>
<pre><code>LocFormSet = modelformset_factory(MyModel)
pformset = LocFormSet(request.POST, request.FILES, queryset=MyModel.objects.order_by('name'))
</code></pre>
<p><hr /></p>
<p><strong>Second Edit</strong></p>
<p>Looks like I'm not using the custom form class I defined there, so the question needs slight modification..</p>
<p><em>How would I create a formset from a custom form (which will show a hidden field), as well as use a custom queryset?</em></p>
<p>At the moment, I can either inherit from a BaseModelFormSet class and use a custom query set, or I can use the ModelForm class to add a custom field to a <strong>form</strong>. Is there a way to do both with a formset?</p>
<p><hr /></p>
<p><strong>Third Edit</strong></p>
<p>I'm now using,</p>
<pre><code>class MyModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
locid = forms.IntegerField(min_value = 1, required=True)
self.fields['locid'].widget.attrs["type"] = 'visible'
self.queryset = MyModel.objects.order_by('name')
class Meta:
model = MyModel
fields = ('locid', 'name')
LocFormSet = modelformset_factory(MyModel, form = MyModelForm)
pformset = LocFormSet()
</code></pre>
<p>But this still doesn't </p>
<ul>
<li>Show locid</li>
<li>Use the custom query that was specified.</li>
</ul>
| 2 | 2009-05-22T02:29:31Z | 896,973 | <p>As you say, you are not using the custom form you have defined. This is because you aren't passing it in anywhere, so Django can't know about it.</p>
<p>The solution is simple - just pass the custom form class into modelformset_factory:</p>
<pre><code>LocFormSet = modelformset_factory(MyModel, form=MyModelForm)
</code></pre>
<p><b>Edit</b> in response to update 3:</p>
<p>Firstly, you have the redefinition for locid in the wrong place - it needs to be at the class level, not inside the <code>__init__</code>.</p>
<p>Secondly, putting the queryset inside the <em>form</em> won't do anything at all - forms don't know about querysets. You should go back to what you were doing before, passing it in as a parameter when you instantiate the formset. (Alternatively, you could define a custom <em>formset</em>, but that seems like overkill.)</p>
<pre><code>class MyModelForm(ModelForm):
locid = forms.IntegerField(min_value=1, required=True)
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
self.fields['locid'].widget.attrs["type"] = 'visible'
class Meta:
model = MyModel
fields = ('locid', 'name')
LocFormSet = modelformset_factory(MyModel, form = MyModelForm)
pformset = LocFormSet(request.POST, request.FILES,
queryset=MyModel.objects.order_by('name')))
</code></pre>
| 1 | 2009-05-22T08:59:29Z | [
"python",
"django",
"formset"
] |
How to show hidden autofield in django formset | 896,153 | <p>A Django autofield when displayed using a formset is hidden by default. What would be the best way to show it?</p>
<p>At the moment, the model is declared as,</p>
<pre><code>class MyModel:
locid = models.AutoField(primary_key=True)
...
</code></pre>
<p>When this is rendered using Django formsets, </p>
<pre><code>class MyModelForm(ModelForm):
class Meta:
model = MyModel
fields = ('locid', 'name')
</code></pre>
<p>it shows up on the page as,</p>
<pre><code><input id="id_form-0-locid" type="hidden" value="707" name="form-0-locid"/>
</code></pre>
<p>Thanks.</p>
<p><hr /></p>
<p><strong>Edit</strong></p>
<p>I create the formset like this -</p>
<pre><code>LocFormSet = modelformset_factory(MyModel)
pformset = LocFormSet(request.POST, request.FILES, queryset=MyModel.objects.order_by('name'))
</code></pre>
<p><hr /></p>
<p><strong>Second Edit</strong></p>
<p>Looks like I'm not using the custom form class I defined there, so the question needs slight modification..</p>
<p><em>How would I create a formset from a custom form (which will show a hidden field), as well as use a custom queryset?</em></p>
<p>At the moment, I can either inherit from a BaseModelFormSet class and use a custom query set, or I can use the ModelForm class to add a custom field to a <strong>form</strong>. Is there a way to do both with a formset?</p>
<p><hr /></p>
<p><strong>Third Edit</strong></p>
<p>I'm now using,</p>
<pre><code>class MyModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
locid = forms.IntegerField(min_value = 1, required=True)
self.fields['locid'].widget.attrs["type"] = 'visible'
self.queryset = MyModel.objects.order_by('name')
class Meta:
model = MyModel
fields = ('locid', 'name')
LocFormSet = modelformset_factory(MyModel, form = MyModelForm)
pformset = LocFormSet()
</code></pre>
<p>But this still doesn't </p>
<ul>
<li>Show locid</li>
<li>Use the custom query that was specified.</li>
</ul>
| 2 | 2009-05-22T02:29:31Z | 902,854 | <p>Okay, none of the approaches above worked for me. I solved this issue from the template side, finally.</p>
<ul>
<li><p>There is a ticket filed (<a href="http://code.djangoproject.com/ticket/10427" rel="nofollow">http://code.djangoproject.com/ticket/10427</a>), which adds a "value" option to a template variable for a form. For instance, it allows,</p>
<p>{{form.locid.value}}</p></li>
</ul>
<p>to be shown. This is available as a patch, which can be installed in the SVN version of django using "patch -p0 file.patch"</p>
<ul>
<li><p>Remember, the {{form.locid.value}} variable will be used <strong>in conjunction</strong> with the invisible form - otherwise, the submit and save operations for the formset will crash.</p></li>
<li><p>This is <em>Not</em> the same as {{form.locid.data}} - as is explained in the ticket referred to above.</p></li>
</ul>
| 0 | 2009-05-24T01:25:51Z | [
"python",
"django",
"formset"
] |
How to show hidden autofield in django formset | 896,153 | <p>A Django autofield when displayed using a formset is hidden by default. What would be the best way to show it?</p>
<p>At the moment, the model is declared as,</p>
<pre><code>class MyModel:
locid = models.AutoField(primary_key=True)
...
</code></pre>
<p>When this is rendered using Django formsets, </p>
<pre><code>class MyModelForm(ModelForm):
class Meta:
model = MyModel
fields = ('locid', 'name')
</code></pre>
<p>it shows up on the page as,</p>
<pre><code><input id="id_form-0-locid" type="hidden" value="707" name="form-0-locid"/>
</code></pre>
<p>Thanks.</p>
<p><hr /></p>
<p><strong>Edit</strong></p>
<p>I create the formset like this -</p>
<pre><code>LocFormSet = modelformset_factory(MyModel)
pformset = LocFormSet(request.POST, request.FILES, queryset=MyModel.objects.order_by('name'))
</code></pre>
<p><hr /></p>
<p><strong>Second Edit</strong></p>
<p>Looks like I'm not using the custom form class I defined there, so the question needs slight modification..</p>
<p><em>How would I create a formset from a custom form (which will show a hidden field), as well as use a custom queryset?</em></p>
<p>At the moment, I can either inherit from a BaseModelFormSet class and use a custom query set, or I can use the ModelForm class to add a custom field to a <strong>form</strong>. Is there a way to do both with a formset?</p>
<p><hr /></p>
<p><strong>Third Edit</strong></p>
<p>I'm now using,</p>
<pre><code>class MyModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
locid = forms.IntegerField(min_value = 1, required=True)
self.fields['locid'].widget.attrs["type"] = 'visible'
self.queryset = MyModel.objects.order_by('name')
class Meta:
model = MyModel
fields = ('locid', 'name')
LocFormSet = modelformset_factory(MyModel, form = MyModelForm)
pformset = LocFormSet()
</code></pre>
<p>But this still doesn't </p>
<ul>
<li>Show locid</li>
<li>Use the custom query that was specified.</li>
</ul>
| 2 | 2009-05-22T02:29:31Z | 1,266,682 | <p>The reason that the autofield is hidden, is that both BaseModelFormSet and BaseInlineFormSet override that field in add_field. The way to fix it is to create your own formset and override add_field without calling super. Also you don't have to explicitly define the primary key.</p>
<p>you have to pass the formset to modelformset_factory:</p>
<pre><code> LocFormSet = modelformset_factory(MyModel,
formset=VisiblePrimaryKeyFormSet)
</code></pre>
<p>This is in the formset class:</p>
<pre><code>from django.forms.models import BaseInlineFormSet, BaseModelFormSet, IntegerField
from django.forms.formsets import BaseFormSet
class VisiblePrimaryKeyFormset(BaseModelFormSet):
def add_fields(self, form, index):
self._pk_field = pk = self.model._meta.pk
if form.is_bound:
pk_value = form.instance.pk
else:
try:
pk_value = self.get_queryset()[index].pk
except IndexError:
pk_value = None
form.fields[self._pk_field.name] = IntegerField( initial=pk_value,
required=True) #or any other field you would like to display the pk in
BaseFormSet.add_fields(self, form, index) # call baseformset which does not modify your primary key field
</code></pre>
| 0 | 2009-08-12T14:51:02Z | [
"python",
"django",
"formset"
] |
Django -- how to use templatetags filter with multiple arguments | 896,166 | <p>I have a few values that I would like to pass into a filter and get a URL out of it.</p>
<p>In my template I have:</p>
<pre><code>{% if names %}
{% for name in names %}
<a href='{{name|slugify|add_args:"custid=name.id, sortid=2"}}'>{{name}}</a>
{%if not forloop.last %} | {% endif %}
{% endfor %}
{% endif %}
</code></pre>
<p>In my templatetags I have:</p>
<pre><code>@register.filter
def add_args(value, args):
argz = value.strip() + '-' + 'ARGS'
arglist = args.split(',')
for arg in arglist:
keyval = arg.split('=')
argz.join(keyval[0] + 'ZZ' + keyval[1])
argz.join('QQ')
return argz
</code></pre>
<p>The output URL should look like:</p>
<pre><code>http://foo.org/john-smith-ARGScustidZZ11QQsortidZZ2
</code></pre>
<p>Where ARGS is the start of the arguments, ZZ is '=' and QQ is an '&' equivalent.</p>
<p>First of all: This would work, but I get the custid=name.id coming in the add_args(), where I want to have custid=11 to come in. How pass in the id as an id and not text.</p>
<p>Also, is there a way to just send in an array of key=>value like in PHP.
In PHP I would build an array, let say:</p>
<pre><code>arglist = array('custid' => $nameid, 'sortid' => $sortid );
</code></pre>
<p>Then I would pass the arglist as an argument to <code>add_args()</code> and in <code>add_args()</code> I would do</p>
<pre><code>foreach( arglist as $key => $value)
$argstr .= $key . 'ZZ' . $value . 'QQ'.
</code></pre>
<p>Does anyone have a better way of making this work?</p>
<p>Note: if I have to pass all arguments as a string and split them up in the filter I don't mind. I just don't know how to pass the name.id as its value ...</p>
| 2 | 2009-05-22T02:37:17Z | 896,301 | <p>You're calling <code>argz.join</code> a couple times and never assigning the results to anything: maybe you're operating under the misconception that the <code>join</code> method of a string has some mysterious side effect, but it doesn't -- it just returns a new string, and if you don't do anything with that new string, <em>poof</em>, it's gone. Is that at least part of your problem...?</p>
| 3 | 2009-05-22T04:08:59Z | [
"python",
"django",
"filter",
"django-templates",
"tags"
] |
Django -- how to use templatetags filter with multiple arguments | 896,166 | <p>I have a few values that I would like to pass into a filter and get a URL out of it.</p>
<p>In my template I have:</p>
<pre><code>{% if names %}
{% for name in names %}
<a href='{{name|slugify|add_args:"custid=name.id, sortid=2"}}'>{{name}}</a>
{%if not forloop.last %} | {% endif %}
{% endfor %}
{% endif %}
</code></pre>
<p>In my templatetags I have:</p>
<pre><code>@register.filter
def add_args(value, args):
argz = value.strip() + '-' + 'ARGS'
arglist = args.split(',')
for arg in arglist:
keyval = arg.split('=')
argz.join(keyval[0] + 'ZZ' + keyval[1])
argz.join('QQ')
return argz
</code></pre>
<p>The output URL should look like:</p>
<pre><code>http://foo.org/john-smith-ARGScustidZZ11QQsortidZZ2
</code></pre>
<p>Where ARGS is the start of the arguments, ZZ is '=' and QQ is an '&' equivalent.</p>
<p>First of all: This would work, but I get the custid=name.id coming in the add_args(), where I want to have custid=11 to come in. How pass in the id as an id and not text.</p>
<p>Also, is there a way to just send in an array of key=>value like in PHP.
In PHP I would build an array, let say:</p>
<pre><code>arglist = array('custid' => $nameid, 'sortid' => $sortid );
</code></pre>
<p>Then I would pass the arglist as an argument to <code>add_args()</code> and in <code>add_args()</code> I would do</p>
<pre><code>foreach( arglist as $key => $value)
$argstr .= $key . 'ZZ' . $value . 'QQ'.
</code></pre>
<p>Does anyone have a better way of making this work?</p>
<p>Note: if I have to pass all arguments as a string and split them up in the filter I don't mind. I just don't know how to pass the name.id as its value ...</p>
| 2 | 2009-05-22T02:37:17Z | 896,755 | <p>You can't pass <code>name.id</code> to your filter. Filter arguments can be asingle value or a single literal. Python/Django doesn't attempt any "smart" variable replacement like PHP.</p>
<p>I suggest you to create a tag for this task:</p>
<pre><code><a href='{% add_args "custid" name.id "sortid" "2" %}{{name|slugify}}{% end_add_args %}'>{{name}}</a>
</code></pre>
<p>This way you can know which argument is a literal value and which should be taken fron context etc... Docs are quite clear about this, take a look at the <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#passing-template-variables-to-the-tag" rel="nofollow">example</a>.</p>
<p>Also if this <code>name</code> is any way related to a model, say we want to get to the permalink, adding a method that returns the URL with the proper arguments might be the tidiest solution.</p>
<p>Overall, I would refrain putting too much logic into templates. Django is not PHP.</p>
| 4 | 2009-05-22T07:47:51Z | [
"python",
"django",
"filter",
"django-templates",
"tags"
] |
Django -- how to use templatetags filter with multiple arguments | 896,166 | <p>I have a few values that I would like to pass into a filter and get a URL out of it.</p>
<p>In my template I have:</p>
<pre><code>{% if names %}
{% for name in names %}
<a href='{{name|slugify|add_args:"custid=name.id, sortid=2"}}'>{{name}}</a>
{%if not forloop.last %} | {% endif %}
{% endfor %}
{% endif %}
</code></pre>
<p>In my templatetags I have:</p>
<pre><code>@register.filter
def add_args(value, args):
argz = value.strip() + '-' + 'ARGS'
arglist = args.split(',')
for arg in arglist:
keyval = arg.split('=')
argz.join(keyval[0] + 'ZZ' + keyval[1])
argz.join('QQ')
return argz
</code></pre>
<p>The output URL should look like:</p>
<pre><code>http://foo.org/john-smith-ARGScustidZZ11QQsortidZZ2
</code></pre>
<p>Where ARGS is the start of the arguments, ZZ is '=' and QQ is an '&' equivalent.</p>
<p>First of all: This would work, but I get the custid=name.id coming in the add_args(), where I want to have custid=11 to come in. How pass in the id as an id and not text.</p>
<p>Also, is there a way to just send in an array of key=>value like in PHP.
In PHP I would build an array, let say:</p>
<pre><code>arglist = array('custid' => $nameid, 'sortid' => $sortid );
</code></pre>
<p>Then I would pass the arglist as an argument to <code>add_args()</code> and in <code>add_args()</code> I would do</p>
<pre><code>foreach( arglist as $key => $value)
$argstr .= $key . 'ZZ' . $value . 'QQ'.
</code></pre>
<p>Does anyone have a better way of making this work?</p>
<p>Note: if I have to pass all arguments as a string and split them up in the filter I don't mind. I just don't know how to pass the name.id as its value ...</p>
| 2 | 2009-05-22T02:37:17Z | 911,750 | <p>This "smart" stuff logic should not be in the template.
Build your end-of-urls in your view and then pass them to template:</p>
<pre><code>def the_view(request):
url_stuff = "custid=%s, sortid, ...." % (name.id, 2 ...)
return render_to_response('template.html',
{'url_stuff':url_stuff,},
context_instance = RequestContext(request))
</code></pre>
<p>In template.html:</p>
<pre><code> ....
<a href='{{url_stuff}}'>{{name}}</a>
....
</code></pre>
<p>If you need a url for a whole bunch of objects consider using <a href="http://docs.djangoproject.com/en/dev/ref/models/instances/#get-absolute-url">get_absolute_url</a> on the model.</p>
| 6 | 2009-05-26T17:08:24Z | [
"python",
"django",
"filter",
"django-templates",
"tags"
] |
Any python library to access quickbooks? | 896,193 | <p>I want to integrate my mobile POS system with quickbooks (I need customers, sellers, inventory & post orders & invoices).</p>
<p>I have not not been able to find a python library for this.</p>
| 5 | 2009-05-22T02:53:52Z | 34,371,049 | <p>I think it might be useful to someone</p>
<p>First, you have to automize a POS</p>
<p><a href="https://github.com/maxolasersquad/orthosie" rel="nofollow">Orthosie Point of sale system written in Python</a></p>
<p><a href="https://code.google.com/p/wxpos/" rel="nofollow">Wxpos Python cross platform point of sale software</a> (Unfortunately, it is now closed, but there has read only access, good for research purposes also)</p>
<p>Second, you have to integrate POS collected data with the quickbooks</p>
<p><a href="https://github.com/sidecars/python-quickbooks" rel="nofollow">A Python library for accessing the Quickbooks API</a></p>
<blockquote>
<p>A Python library for accessing the Quickbooks API. Complete rework of quickbooks-python.</p>
</blockquote>
| 0 | 2015-12-19T12:58:53Z | [
"python",
"api",
"quickbooks"
] |
How to change default django User model to fit my needs? | 896,421 | <p>The default Django's <code>User</code> model has some fields, and validation rules, that I don't really need. I want to make registration as simple as possible, i.e. require either email or username, or phone number - all those being unique, hence good as user identifiers. </p>
<p>I also don't like default character set for user name that is validated in Django user model. I'd like to allow any character there - why not?</p>
<p>I used user-profile django application before to add a profile to user - but this time I'd rather make the class mimimal. But I still want to use the <code>User</code> class, as it gives me an easy way to have parts of site restricted only for users logged in. </p>
<p>How do I do it? </p>
| 10 | 2009-05-22T05:01:09Z | 896,788 | <p>The Django User model is structured very sensibly. You really don't want to allow arbitrary characters in a username, for instance, and there are ways to achieve <a href="http://www.djangosnippets.org/snippets/74/" rel="nofollow">email address login</a>, without hacking changes to the base model.</p>
<p>To simply store additional information around a user account, Django supports the notion of user profiles. While you don't need to rely on the built in support to handle this, it is a convention that is commonly followed and it will allow you to play nice with the reusable Django apps that are floating around in the ether. For more information, see <a href="https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model" rel="nofollow">here</a>.</p>
<p>If you want to actually modify the core User model but also "play nice" with reusable apps that rely on it, you're opening a bit of a Pandora's Box. Developers make base assumptions about how the core library is structured, so any changes may cause unexpected breakage. Nonetheless, you can monkeypatch changes to the base model, or branch a copy of Django locally. I would discourage the latter, and only recommend the former if you know what you're doing.</p>
| 7 | 2009-05-22T07:59:39Z | [
"python",
"django",
"django-models",
"user"
] |
How to change default django User model to fit my needs? | 896,421 | <p>The default Django's <code>User</code> model has some fields, and validation rules, that I don't really need. I want to make registration as simple as possible, i.e. require either email or username, or phone number - all those being unique, hence good as user identifiers. </p>
<p>I also don't like default character set for user name that is validated in Django user model. I'd like to allow any character there - why not?</p>
<p>I used user-profile django application before to add a profile to user - but this time I'd rather make the class mimimal. But I still want to use the <code>User</code> class, as it gives me an easy way to have parts of site restricted only for users logged in. </p>
<p>How do I do it? </p>
| 10 | 2009-05-22T05:01:09Z | 897,928 | <p><strong>I misread the question. Hope this post is helpful to anyone else.</strong></p>
<pre><code>#in models.py
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User)
#other fields here
def __str__(self):
return "%s's profile" % self.user
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
#in settings.py
AUTH_PROFILE_MODULE = 'YOURAPP.UserProfile'
</code></pre>
<p>This will create a userprofile each time a user is saved if it is created.
You can then use</p>
<pre><code> user.get_profile().whatever
</code></pre>
<p>Here is some more info from the docs</p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users">http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users</a></p>
| 7 | 2009-05-22T13:47:00Z | [
"python",
"django",
"django-models",
"user"
] |
How to change default django User model to fit my needs? | 896,421 | <p>The default Django's <code>User</code> model has some fields, and validation rules, that I don't really need. I want to make registration as simple as possible, i.e. require either email or username, or phone number - all those being unique, hence good as user identifiers. </p>
<p>I also don't like default character set for user name that is validated in Django user model. I'd like to allow any character there - why not?</p>
<p>I used user-profile django application before to add a profile to user - but this time I'd rather make the class mimimal. But I still want to use the <code>User</code> class, as it gives me an easy way to have parts of site restricted only for users logged in. </p>
<p>How do I do it? </p>
| 10 | 2009-05-22T05:01:09Z | 898,052 | <p>You face a bit of a dilemma which really has two solutions if you're committed to avoiding the profile-based customization already pointed out.</p>
<ol>
<li>Change the <code>User</code> model itself, per Daniel's suggestions</li>
<li>Write a <code>CustomUser</code> class, subclassing <code>User</code> or copying its functionality.</li>
</ol>
<p>The latter suggestion means that you would have to implement some things that <code>User</code> does automatically manually, but I wonder whether that's as bad as it sounds, especially if you're at the beginning of your project. All you'd have to do is rewrite a middle-ware class and some decorators.</p>
<p>Of course, I don't think this buys you anything that 1 won't get you, except that your project shouldn't break if you <code>svn update</code> your django. It may avoid some of the compatibility problems with other apps, but my guess is most problems will exist either way.</p>
| 0 | 2009-05-22T14:09:53Z | [
"python",
"django",
"django-models",
"user"
] |
How to change default django User model to fit my needs? | 896,421 | <p>The default Django's <code>User</code> model has some fields, and validation rules, that I don't really need. I want to make registration as simple as possible, i.e. require either email or username, or phone number - all those being unique, hence good as user identifiers. </p>
<p>I also don't like default character set for user name that is validated in Django user model. I'd like to allow any character there - why not?</p>
<p>I used user-profile django application before to add a profile to user - but this time I'd rather make the class mimimal. But I still want to use the <code>User</code> class, as it gives me an easy way to have parts of site restricted only for users logged in. </p>
<p>How do I do it? </p>
| 10 | 2009-05-22T05:01:09Z | 898,313 | <p>Rather than modify the User class directly or do subclassing, you can also just repurpose the existing fields. </p>
<p>For one site I used the "first_name" field as the "publicly displayed name" of a user and stuff a slugified version of that into the "username" field (for use in URLs). I wrote a custom auth backend to allow people to log in using their "public name" or their email address, and I enforce the uniqueness of both of those at registration time. This plays nicely with other reusable apps and doesn't introduce extra tables or queries.</p>
<p>For another site I didn't want usernames at all, just unique emails. In order to satisfy Django's need for a unique username, I just hashed the email address and used that as the username (you have to base64-encode the hash to squeeze it under 30 characters). Custom auth backend to allow login with email.</p>
<p>If backwards-compatibility weren't an issue, there are a lot of improvements I'd love to see made to django.contrib.auth and the User model to make them more flexible. But there's quite a lot you can do inside the current constraints with a little creativity.</p>
| 8 | 2009-05-22T14:59:04Z | [
"python",
"django",
"django-models",
"user"
] |
How to change default django User model to fit my needs? | 896,421 | <p>The default Django's <code>User</code> model has some fields, and validation rules, that I don't really need. I want to make registration as simple as possible, i.e. require either email or username, or phone number - all those being unique, hence good as user identifiers. </p>
<p>I also don't like default character set for user name that is validated in Django user model. I'd like to allow any character there - why not?</p>
<p>I used user-profile django application before to add a profile to user - but this time I'd rather make the class mimimal. But I still want to use the <code>User</code> class, as it gives me an easy way to have parts of site restricted only for users logged in. </p>
<p>How do I do it? </p>
| 10 | 2009-05-22T05:01:09Z | 3,902,915 | <p>There are anumber of ways to do this, but here's what I'd do: I'd allow a user to enter an email, username (which must contain at least one letter and no <code>@</code> symbols) or mobile number. Then, when I validate it:</p>
<ol>
<li>Check for the presence of <code>@</code>. If so, set it as the user's email, hash it appropriately and set it as their username as well.</li>
<li>Check to see if it's only numbers, dashes and <code>+</code>. Then, strip the appropriate characters and store it as both mobile number and username (if you're storing the mobile number in another model for SMS purposes or something).</li>
<li>If it's not either, just set it as username.</li>
</ol>
<p>I'd also validate the user/phone/email field similarly on login and look in the appropriate place so that if, say, a user signs up with their mobile number and then changes their username (for some other purpose), they can still sign in with their mobile number.</p>
| 0 | 2010-10-11T00:58:28Z | [
"python",
"django",
"django-models",
"user"
] |
Passing Variables to Django Comment Views | 896,532 | <p>Alright, I know I've asked similar questions, but I feel this is hopefully a bit different. I'm integrating django.comments into my application, and the more I play with it, the more I realize it may not even be worth my while at the end of the day. That aside, I've managed to add Captcha to my comments, and I've learned that customizing the form is a terrible idea (hiding that honeypot is stupidly difficult, and from what I can tell requires JS to hide. Pity.). That's alright though, I've managed to work with it. However, the templates for the comments (preview and posted) are frustrating.</p>
<p>When a user is sent to the preview or posted templates, I'd like my sidebar's that have dynamic data to still be functional, however they're not. Do I have to override/rewrite the comments views to push data to these views? At that point it seems like I'm rewriting a major chunk of the comment system anyway, and it'd almost be beneficial to just write my own in that case. I'm more than willing to do that, and totally understand that I'm not entitled to a perfect comments system from Django. I just want to make sure I'm thinking right, and that if I want more than what I get from the comment views, that rewriting them is my only path.</p>
<p>Surely someone's found a healthier way though, so I thought I'd poll the audience. Any thoughts? If you need more info, just lemme know!</p>
| -3 | 2009-05-22T05:57:04Z | 896,983 | <p>Dynamic data in sidebars is what template tags are for.</p>
<p>There's absolutely no need to muck around with the built-in views - just define the tags add them to your templates.</p>
| 3 | 2009-05-22T09:02:29Z | [
"python",
"django",
"django-comments"
] |
Passing Variables to Django Comment Views | 896,532 | <p>Alright, I know I've asked similar questions, but I feel this is hopefully a bit different. I'm integrating django.comments into my application, and the more I play with it, the more I realize it may not even be worth my while at the end of the day. That aside, I've managed to add Captcha to my comments, and I've learned that customizing the form is a terrible idea (hiding that honeypot is stupidly difficult, and from what I can tell requires JS to hide. Pity.). That's alright though, I've managed to work with it. However, the templates for the comments (preview and posted) are frustrating.</p>
<p>When a user is sent to the preview or posted templates, I'd like my sidebar's that have dynamic data to still be functional, however they're not. Do I have to override/rewrite the comments views to push data to these views? At that point it seems like I'm rewriting a major chunk of the comment system anyway, and it'd almost be beneficial to just write my own in that case. I'm more than willing to do that, and totally understand that I'm not entitled to a perfect comments system from Django. I just want to make sure I'm thinking right, and that if I want more than what I get from the comment views, that rewriting them is my only path.</p>
<p>Surely someone's found a healthier way though, so I thought I'd poll the audience. Any thoughts? If you need more info, just lemme know!</p>
| -3 | 2009-05-22T05:57:04Z | 900,503 | <p>I user template tags as well. Templates in Django are truly for displaying data only.
I think Django believes in separation between the Designers and the Developers. So, they are enforcing the idea of templates should be simple enough for web designer to work with. (the photoshop guys)</p>
<p>So, as long as you don't need complected functionality, just pass the info to a filter and have it do the data manipulation and return the final string that you need.</p>
| 0 | 2009-05-23T00:13:38Z | [
"python",
"django",
"django-comments"
] |
How to convert a Pyglet image to a PIL image? | 896,548 | <p>i want to convert a Pyglet.AbstractImage object to an PIL image for further manipulation
here are my codes</p>
<pre><code>from pyglet import image
from PIL import Image
pic = image.load('pic.jpg')
data = pic.get_data('RGB', pic.pitch)
im = Image.fromstring('RGB', (pic.width, pic.height), data)
im.show()
</code></pre>
<p>but the image shown went wrong.
so how to convert an image from pyglet to PIL properly?</p>
| 1 | 2009-05-22T06:07:26Z | 896,554 | <p>This is an open <a href="http://code.google.com/p/pyglet/wiki/ReleaseSchedule" rel="nofollow">wishlist</a> item:</p>
<blockquote>
<p>AbstractImage to/from PIL image. </p>
</blockquote>
| 0 | 2009-05-22T06:10:05Z | [
"python",
"image",
"python-imaging-library",
"pyglet"
] |
How to convert a Pyglet image to a PIL image? | 896,548 | <p>i want to convert a Pyglet.AbstractImage object to an PIL image for further manipulation
here are my codes</p>
<pre><code>from pyglet import image
from PIL import Image
pic = image.load('pic.jpg')
data = pic.get_data('RGB', pic.pitch)
im = Image.fromstring('RGB', (pic.width, pic.height), data)
im.show()
</code></pre>
<p>but the image shown went wrong.
so how to convert an image from pyglet to PIL properly?</p>
| 1 | 2009-05-22T06:07:26Z | 896,756 | <p>I think I find the solution</p>
<p>the pitch in Pyglet.AbstractImage instance is not compatible with PIL
I found in pyglet 1.1 there is a codec function to encode the Pyglet image to PIL
here is the <a href="http://pyglet.googlecode.com/svn/trunk/pyglet/image/codecs/pil.py" rel="nofollow">link</a> to the source</p>
<p>so the code above should be modified to this</p>
<pre><code>from pyglet import image
from PIL import Image
pic = image.load('pic.jpg')
pitch = -(pic.width * len('RGB'))
data = pic.get_data('RGB', pitch) # using the new pitch
im = Image.fromstring('RGB', (pic.width, pic.height), data)
im.show()
</code></pre>
<p>I'm using a 461x288 image in this case and find that pic.pitch is -1384</p>
<p>but the new pitch is -1383</p>
| 2 | 2009-05-22T07:47:56Z | [
"python",
"image",
"python-imaging-library",
"pyglet"
] |
Display all file names from a specific folder | 896,595 | <p>Like there is a folder say XYZ , whcih contain files with diffrent diffrent format
let say .txt file, excel file, .py file etc.
i want to display in the output all file name using Python programming</p>
| 0 | 2009-05-22T06:32:42Z | 896,613 | <pre><code>import glob
glob.glob('XYZ/*')
</code></pre>
<p><a href="http://docs.python.org/library/glob.html" rel="nofollow">See the documentation for more</a></p>
| 3 | 2009-05-22T06:37:44Z | [
"python",
"directory",
"ls"
] |
Display all file names from a specific folder | 896,595 | <p>Like there is a folder say XYZ , whcih contain files with diffrent diffrent format
let say .txt file, excel file, .py file etc.
i want to display in the output all file name using Python programming</p>
| 0 | 2009-05-22T06:32:42Z | 896,802 | <p>Here is an example that might also help show some of the handy basics of python -- dicts <code>{}</code> , lists <code>[]</code> , little string techniques (<code>split</code>), a module like <code>os</code>, etc.:</p>
<pre><code>bvm@bvm:~/example$ ls
deal.xls five.xls france.py guido.py make.py thing.mp3 work2.doc
example.py four.xls fun.mp3 letter.doc thing2.xlsx what.docx work45.doc
bvm@bvm:~/example$ python
>>> import os
>>> files = {}
>>> for item in os.listdir('.'):
... try:
... files[item.split('.')[1]].append(item)
... except KeyError:
... files[item.split('.')[1]] = [item]
...
>>> files
{'xlsx': ['thing2.xlsx'], 'docx': ['what.docx'], 'doc': ['letter.doc',
'work45.doc', 'work2.doc'], 'py': ['example.py', 'guido.py', 'make.py',
'france.py'], 'mp3': ['thing.mp3', 'fun.mp3'], 'xls': ['five.xls',
'deal.xls', 'four.xls']}
>>> files['doc']
['letter.doc', 'work45.doc', 'work2.doc']
>>> files['py']
['example.py', 'guido.py', 'make.py', 'france.py']
</code></pre>
<p>For your update question, you might try something like:</p>
<pre><code>>>> for item in enumerate(os.listdir('.')):
... print item
...
(0, 'thing.mp3')
(1, 'fun.mp3')
(2, 'example.py')
(3, 'letter.doc')
(4, 'five.xls')
(5, 'guido.py')
(6, 'what.docx')
(7, 'work45.doc')
(8, 'deal.xls')
(9, 'four.xls')
(10, 'make.py')
(11, 'thing2.xlsx')
(12, 'france.py')
(13, 'work2.doc')
>>>
</code></pre>
| 2 | 2009-05-22T08:05:53Z | [
"python",
"directory",
"ls"
] |
Display all file names from a specific folder | 896,595 | <p>Like there is a folder say XYZ , whcih contain files with diffrent diffrent format
let say .txt file, excel file, .py file etc.
i want to display in the output all file name using Python programming</p>
| 0 | 2009-05-22T06:32:42Z | 897,024 | <pre><code>import os
XYZ = '.'
for item in enumerate(sorted(os.listdir(XYZ))):
print item
</code></pre>
| 1 | 2009-05-22T09:17:06Z | [
"python",
"directory",
"ls"
] |
Checking folder/file ntfs permissions using python | 896,638 | <p>As the question title might suggest, I would very much like to know of the way to check the ntfs permissions of the given file or folder (hint: those are the ones you see in the "security" tab). Basically, what I need is to take a path to a file or directory (on a local machine, or, preferrably, on a share on a remote machine) and get the list of users/groups and the corresponding permissions for this file/folder. Ultimately, the application is going to traverse a directory tree, reading permissions for each object and processing them accordingly.</p>
<p>Now, I can think of a number of ways to do that:</p>
<ul>
<li>parse cacls.exe output -- easily done, BUT, unless im missing something, cacls.exe only gives the permissions in the form of R|W|C|F (read/write/change/full), which is insufficient (I need to get the permissions like "List folder contents", extended permissions too)</li>
<li>xcacls.exe or xcacls.vbs output -- yes, they give me all the permissions I need, but they work dreadfully slow, it takes xcacls.vbs about ONE SECOND to get permissions on a local system file. Such speed is unacceptable</li>
<li>win32security (it wraps around winapi, right?) -- I am sure it can be handled like this, but I'd rather not reinvent the wheel</li>
</ul>
<p>Is there anything else I am missing here?</p>
| 6 | 2009-05-22T06:48:03Z | 897,963 | <p>Unless you fancy rolling your own, win32security is the way to go. There's the beginnings of an example here:</p>
<p><a href="http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html">http://timgolden.me.uk/python/win32_how_do_i/get-the-owner-of-a-file.html</a></p>
<p>If you want to live slightly dangerously (!) my in-progress winsys package is designed to do exactly what you're after. You can get an MSI of the dev version here:</p>
<p><a href="http://timgolden.me.uk/python/downloads/WinSys-0.4.win32-py2.6.msi">http://timgolden.me.uk/python/downloads/WinSys-0.4.win32-py2.6.msi</a></p>
<p>or you can just checkout the svn trunk:</p>
<p>svn co <a href="http://winsys.googlecode.com/svn/trunk">http://winsys.googlecode.com/svn/trunk</a> winsys</p>
<p>To do what you describe (guessing slightly at the exact requirements) you could do this:</p>
<pre><code>import codecs
from winsys import fs
base = "c:/temp"
with codecs.open ("permissions.log", "wb", encoding="utf8") as log:
for f in fs.flat (base):
log.write ("\n" + f.filepath.relative_to (base) + "\n")
for ace in f.security ().dacl:
access_flags = fs.FILE_ACCESS.names_from_value (ace.access)
log.write (u" %s => %s\n" % (ace.trustee, ", ".join (access_flags)))
</code></pre>
<p>TJG</p>
| 11 | 2009-05-22T13:56:50Z | [
"python",
"winapi",
"permissions",
"acl",
"ntfs"
] |
Creating modelformset from a modelform | 896,848 | <p>I have a model MyModel which contains a PK - locid, that is an AutoField.</p>
<p>I want to construct a model formset from this, with some caveats:</p>
<ul>
<li>The queryset for the formset should be a custom one (say, order_by('field')) rather than all()</li>
<li>Since locid for MyModel is an AutoField and thus hidden by default, I want to be able to show it to the user.</li>
</ul>
<p>I'm not sure how to do this. I've tried multiple approaches, </p>
<pre><code>MyModelFormSet = modelformset_factory(MyModel, fields=('locid', 'name', 'dupof'))
</code></pre>
<p>The above gives me the 3 fields, but locid is hidden.</p>
<pre><code>class MyModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
self.fields['locid'].widget.attrs["type"] = 'visible'
locid = forms.IntegerField(min_value = 1, required=True)
class Meta:
model = MyModel
fields = ('locid', 'name', 'dupof')
</code></pre>
<p>The above gives me a ManyToMany error.</p>
<p>Has anyone done something like this before?</p>
<p><hr /></p>
<p>Edit <strong>2</strong></p>
<p>I can now use a custom query when I instantiate the formset - but I still need to show the locid field to the user, because the id is important for the application's use. How would I do this? <em>Is there a way to override the default behavior of hiding a PK if its an autofield?</em></p>
| 0 | 2009-05-22T08:22:12Z | 897,383 | <p>It makes no sense to show an autofield to the user, as it's an autoincremented primary key -- the user can not change it and it will not be available before saving the record to the database (where the DBMS selectes the next available id).</p>
<p>This is how you set a custom queryset for a formset:</p>
<pre><code>from django.forms.models import BaseModelFormSet
class OrderedFormSet(BaseModelFormSet):
def __init__(self, *args, **kwargs):
self.queryset = MyModel.objects.order_by("field")
super(OrderedFormSet, self).__init__(*args, **kwargs)
</code></pre>
<p>and then you use that formset in the factory function:</p>
<pre><code>MyModelFormSet = modelformset_factory(MyModel, formset=OrderedFormSet)
</code></pre>
| 2 | 2009-05-22T11:16:38Z | [
"python",
"django",
"formset",
"modelform"
] |
Creating modelformset from a modelform | 896,848 | <p>I have a model MyModel which contains a PK - locid, that is an AutoField.</p>
<p>I want to construct a model formset from this, with some caveats:</p>
<ul>
<li>The queryset for the formset should be a custom one (say, order_by('field')) rather than all()</li>
<li>Since locid for MyModel is an AutoField and thus hidden by default, I want to be able to show it to the user.</li>
</ul>
<p>I'm not sure how to do this. I've tried multiple approaches, </p>
<pre><code>MyModelFormSet = modelformset_factory(MyModel, fields=('locid', 'name', 'dupof'))
</code></pre>
<p>The above gives me the 3 fields, but locid is hidden.</p>
<pre><code>class MyModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
self.fields['locid'].widget.attrs["type"] = 'visible'
locid = forms.IntegerField(min_value = 1, required=True)
class Meta:
model = MyModel
fields = ('locid', 'name', 'dupof')
</code></pre>
<p>The above gives me a ManyToMany error.</p>
<p>Has anyone done something like this before?</p>
<p><hr /></p>
<p>Edit <strong>2</strong></p>
<p>I can now use a custom query when I instantiate the formset - but I still need to show the locid field to the user, because the id is important for the application's use. How would I do this? <em>Is there a way to override the default behavior of hiding a PK if its an autofield?</em></p>
| 0 | 2009-05-22T08:22:12Z | 902,872 | <p>If you like cheap workarounds, why not mangle the <code>locid</code> into the <code>__unicode__</code> method? The user is guaranteed to see it, and no special knowledge of django-admin is required.</p>
<p>But, to be fair, all my answers to django-admin related questions tend along the lines of "don't strain to hard to make django-admin into an all-purpose CRUD interface".</p>
| 0 | 2009-05-24T01:38:21Z | [
"python",
"django",
"formset",
"modelform"
] |
Creating modelformset from a modelform | 896,848 | <p>I have a model MyModel which contains a PK - locid, that is an AutoField.</p>
<p>I want to construct a model formset from this, with some caveats:</p>
<ul>
<li>The queryset for the formset should be a custom one (say, order_by('field')) rather than all()</li>
<li>Since locid for MyModel is an AutoField and thus hidden by default, I want to be able to show it to the user.</li>
</ul>
<p>I'm not sure how to do this. I've tried multiple approaches, </p>
<pre><code>MyModelFormSet = modelformset_factory(MyModel, fields=('locid', 'name', 'dupof'))
</code></pre>
<p>The above gives me the 3 fields, but locid is hidden.</p>
<pre><code>class MyModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
self.fields['locid'].widget.attrs["type"] = 'visible'
locid = forms.IntegerField(min_value = 1, required=True)
class Meta:
model = MyModel
fields = ('locid', 'name', 'dupof')
</code></pre>
<p>The above gives me a ManyToMany error.</p>
<p>Has anyone done something like this before?</p>
<p><hr /></p>
<p>Edit <strong>2</strong></p>
<p>I can now use a custom query when I instantiate the formset - but I still need to show the locid field to the user, because the id is important for the application's use. How would I do this? <em>Is there a way to override the default behavior of hiding a PK if its an autofield?</em></p>
| 0 | 2009-05-22T08:22:12Z | 912,892 | <p>I ended up using a template side variable to do this, as I mentioned here:</p>
<p><a href="http://stackoverflow.com/questions/896153/how-to-show-hidden-autofield-in-django-formset">http://stackoverflow.com/questions/896153/how-to-show-hidden-autofield-in-django-formset</a></p>
| 1 | 2009-05-26T21:35:34Z | [
"python",
"django",
"formset",
"modelform"
] |
Running multiple processes and capturing the output in python with pygtk | 896,874 | <p>I'd like to write a simple application that runs multiple programs and displays their output in multiple terminal (style) windows. In addition, I want to be able to read the stdout/stderr of these processes and search for keywords in the output.</p>
<p>I've tried implementing this two ways in python, the first using subprocess.Popen and the second using vte (python-vte).</p>
<p>I've only gotten Popen to work w/ polling. I have to constantly check to see if the processes have data to be read, read the data, and then send it to my TextArea. It's been recommended to use gobject.io_add_watch() instead, but whenever I try that my program hangs on the second call to io_add_watch--it's like it can only handle one file descriptor at a time.</p>
<p>vte works great but I haven't found a reliable way to capture the output. You can get a callback when the cursor moves and then screen scrape w/ get_text(), but I've already run into cases where these programs I'm viewing generate an obscene about of tty in one go and then it's off the screen. There doesn't appear to be a callback that contains new text to be added to the window.</p>
<p>Any ideas?</p>
| 1 | 2009-05-22T08:29:23Z | 897,075 | <p>I did something similar to this using the <a href="http://docs.python.org/library/subprocess.html#popen-objects" rel="nofollow">subprocess.Popen</a>. For each process I actually ended up redirecting the stdout and stderr to a temporary file, then periodically checking the file for updates and dumping the output into a <a href="http://www.pygtk.org/docs/pygtk/class-gtktextview.html" rel="nofollow">TextView</a>. </p>
<p>The reason for not using a pipe to the process was that the processes themselves were volatile and prone to segfaults. When that happened I sometimes lost data between the last read and the segfault (which was the most needed data to determine the cause of the segfault).</p>
<p>As it turned out, sometimes I'd want to save the output from a specific process, so this method worked well for me.</p>
| 1 | 2009-05-22T09:33:18Z | [
"python"
] |
Running multiple processes and capturing the output in python with pygtk | 896,874 | <p>I'd like to write a simple application that runs multiple programs and displays their output in multiple terminal (style) windows. In addition, I want to be able to read the stdout/stderr of these processes and search for keywords in the output.</p>
<p>I've tried implementing this two ways in python, the first using subprocess.Popen and the second using vte (python-vte).</p>
<p>I've only gotten Popen to work w/ polling. I have to constantly check to see if the processes have data to be read, read the data, and then send it to my TextArea. It's been recommended to use gobject.io_add_watch() instead, but whenever I try that my program hangs on the second call to io_add_watch--it's like it can only handle one file descriptor at a time.</p>
<p>vte works great but I haven't found a reliable way to capture the output. You can get a callback when the cursor moves and then screen scrape w/ get_text(), but I've already run into cases where these programs I'm viewing generate an obscene about of tty in one go and then it's off the screen. There doesn't appear to be a callback that contains new text to be added to the window.</p>
<p>Any ideas?</p>
| 1 | 2009-05-22T08:29:23Z | 897,094 | <p>If you go with igkuk's suggestion, I got <a href="http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python">some good advice on watching files for changes</a> in a related question. That worked pretty well for me (I was watching a log file for changes).</p>
| 1 | 2009-05-22T09:39:28Z | [
"python"
] |
Running multiple processes and capturing the output in python with pygtk | 896,874 | <p>I'd like to write a simple application that runs multiple programs and displays their output in multiple terminal (style) windows. In addition, I want to be able to read the stdout/stderr of these processes and search for keywords in the output.</p>
<p>I've tried implementing this two ways in python, the first using subprocess.Popen and the second using vte (python-vte).</p>
<p>I've only gotten Popen to work w/ polling. I have to constantly check to see if the processes have data to be read, read the data, and then send it to my TextArea. It's been recommended to use gobject.io_add_watch() instead, but whenever I try that my program hangs on the second call to io_add_watch--it's like it can only handle one file descriptor at a time.</p>
<p>vte works great but I haven't found a reliable way to capture the output. You can get a callback when the cursor moves and then screen scrape w/ get_text(), but I've already run into cases where these programs I'm viewing generate an obscene about of tty in one go and then it's off the screen. There doesn't appear to be a callback that contains new text to be added to the window.</p>
<p>Any ideas?</p>
| 1 | 2009-05-22T08:29:23Z | 897,209 | <p>You want to use <a href="http://docs.python.org/library/select.html" rel="nofollow">select</a> to monitor the pipes from your subprocesses. It's better than polling.</p>
| 0 | 2009-05-22T10:15:39Z | [
"python"
] |
A good way to escape quotes in a database query string? | 897,020 | <p>I've tried all manner of Python modules and they either escape too much or in the wrong way.
What's the best way you've found to escape quotes (", ') in Python?</p>
| 25 | 2009-05-22T09:16:28Z | 897,061 | <p>If it's part of a Database query you should be able to use a <a href="http://python.projects.postgresql.org/docs/0.8/driver.html#parameterized-statements">Parameterized SQL Statement</a>.</p>
<p>As well as escaping your quotes, this will deal with all special characters and will protect you from <a href="http://stackoverflow.com/questions/681583/sql-injection-on-insert">SQL injection attacks</a>.</p>
| 23 | 2009-05-22T09:30:32Z | [
"python",
"database",
"escaping",
"sql-injection"
] |
A good way to escape quotes in a database query string? | 897,020 | <p>I've tried all manner of Python modules and they either escape too much or in the wrong way.
What's the best way you've found to escape quotes (", ') in Python?</p>
| 25 | 2009-05-22T09:16:28Z | 2,429,209 | <p>For a solution to a more generic problem, I have a program where I needed to store <em>any</em> set of characters in a flat file, tab delimited. Obviously, having tabs in the 'set' was causing problems.</p>
<p>Instead of output_f.write(str), I used output_f.write(repr(str)), which solved my problem.
It is slower to read, as I need to eval() the input when I read it, but overall, it makes the code cleaner because I don't need to check for fringe cases anymore.</p>
| 0 | 2010-03-11T22:28:36Z | [
"python",
"database",
"escaping",
"sql-injection"
] |
A good way to escape quotes in a database query string? | 897,020 | <p>I've tried all manner of Python modules and they either escape too much or in the wrong way.
What's the best way you've found to escape quotes (", ') in Python?</p>
| 25 | 2009-05-22T09:16:28Z | 2,429,285 | <p>If you're using psycopg2 that has a method for escaping strings: <strong><code>psycopg2.extensions.adapt()</code></strong> See <a href="http://stackoverflow.com/questions/309945/how-to-quote-a-string-value-explicitly-python-db-api-psycopg2">http://stackoverflow.com/questions/309945/how-to-quote-a-string-value-explicitly-python-db-api-psycopg2</a> for the full answer</p>
| 2 | 2010-03-11T22:40:43Z | [
"python",
"database",
"escaping",
"sql-injection"
] |
A good way to escape quotes in a database query string? | 897,020 | <p>I've tried all manner of Python modules and they either escape too much or in the wrong way.
What's the best way you've found to escape quotes (", ') in Python?</p>
| 25 | 2009-05-22T09:16:28Z | 9,028,006 | <p>Triple-double quotes are best for escaping:</p>
<pre>string = """This will span across 'single quotes', "double quotes",
and literal EOLs all in the same string."""</pre>
| 1 | 2012-01-27T01:44:37Z | [
"python",
"database",
"escaping",
"sql-injection"
] |
A good way to escape quotes in a database query string? | 897,020 | <p>I've tried all manner of Python modules and they either escape too much or in the wrong way.
What's the best way you've found to escape quotes (", ') in Python?</p>
| 25 | 2009-05-22T09:16:28Z | 13,676,745 | <p>The easy and standard way to escape strings, and convert other objects to programmatic form, is to use the build in repr() function. It converts an object into the representation you would need to enter it with manual code.</p>
<p>E.g.:</p>
<pre><code>s = "I'm happy I am \"here\" now"
print repr(s)
>> 'I\'m happy I am "here" now'
</code></pre>
<p>No weird hacks, it's built in and it just works for most purposes.</p>
| 5 | 2012-12-03T03:27:26Z | [
"python",
"database",
"escaping",
"sql-injection"
] |
A good way to escape quotes in a database query string? | 897,020 | <p>I've tried all manner of Python modules and they either escape too much or in the wrong way.
What's the best way you've found to escape quotes (", ') in Python?</p>
| 25 | 2009-05-22T09:16:28Z | 14,930,615 | <p>Use <code>json.dumps</code>.</p>
<pre><code>>>> import json
>>> print json.dumps('a"bc')
"a\"bc"
</code></pre>
| 19 | 2013-02-18T06:25:16Z | [
"python",
"database",
"escaping",
"sql-injection"
] |
A good way to escape quotes in a database query string? | 897,020 | <p>I've tried all manner of Python modules and they either escape too much or in the wrong way.
What's the best way you've found to escape quotes (", ') in Python?</p>
| 25 | 2009-05-22T09:16:28Z | 37,897,034 | <p>Reply for old thread, but the best way still missing here..</p>
<p>If using psycopg2, it's execute -method has buildin escaping.</p>
<pre><code>cursor.execute("SELECT column FROM table WHERE column=%s AND column2=%s", (value1, value2))
</code></pre>
<p>Note, that you are giving two arguments to execute method (string and tuple), instead of using Python's % operator to modify string. </p>
<p>Answer stolen from here: <a href="http://stackoverflow.com/questions/3823735/psycopg2-equivalent-of-mysqldb-escape-string">psycopg2 equivalent of mysqldb.escape_string?</a></p>
| 1 | 2016-06-18T12:36:48Z | [
"python",
"database",
"escaping",
"sql-injection"
] |
Python cgi FieldStorage slow, alternatives? | 897,206 | <p>I have a python cgi script that receives files uploaded via a http post. The files can be large (300+ Mb). The thing is, cgi.FieldStorage() is incredibly slow for getting the file (a 300Mb file took 6 minutes to be "received"). Doing the same by just reading the stdin took around 15 seconds. The problem with the latter is, i would have to parse the data myself if there are multiple fields that are posted.</p>
<p>Are there any faster alternatives to FieldStorage()?</p>
| 3 | 2009-05-22T10:15:13Z | 897,218 | <p>"[I] would have to parse the data myself"</p>
<p>Why? CGI has a <a href="http://docs.python.org/library/cgi.html#cgi.parse" rel="nofollow">parser</a> you can call explicitly.</p>
<p>Read the uploaded stream and save it in a local disk file. </p>
<p>For blazing speed, use a StringIO in-memory file. Just be aware of the amount of memory the upload will take.</p>
<p>Use <code>cgi.parse(mylocalfile)</code>.</p>
| 2 | 2009-05-22T10:20:42Z | [
"python",
"cgi"
] |
What is the idiomatic way of invoking a list of functions in Python? | 897,362 | <p>I have a list of callback functions that I need to invoke when an event is fired.
Is this idiomatic python? </p>
<pre><code>def first_callback(m):
print 'first ' + m
def second_callback(m):
print 'second ' + m
lst = [first_callback, second_callback]
map(lambda x: x("event_info"),lst) #is this how you do it?
</code></pre>
| 4 | 2009-05-22T11:09:53Z | 897,373 | <p>Use <code>map</code> only for functions without side effects (like <code>print</code>). That is, use it only for functions that just return something. In this case a regular loop is more idiomatic:</p>
<pre><code>for f in lst:
f("event_info")
</code></pre>
<p><strong>Edit</strong>: also, as of Python 3.0, <a href="http://docs.python.org/3.0/library/functions.html#map" rel="nofollow"><code>map</code></a> returns an iterator instead of a list. Hence in Python 3.0 the code given in the question will not call <em>any</em> function, unless all elements in the generator are evaluated explicitly (e.g. by encapsulating the call to <code>map</code> inside <a href="http://docs.python.org/3.0/library/functions.html#list" rel="nofollow"><code>list</code></a>). Luckily the <a href="http://docs.python.org/library/2to3.html" rel="nofollow">2to3</a> tool will warn about this:</p>
<p>File <code>map.py</code>:</p>
<pre><code>map(lambda x: x, range(10))
</code></pre>
<p><code>2to3-3.0 map.py</code> output:</p>
<pre><code>RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
--- map.py (original)
+++ map.py (refactored)
@@ -1,1 +1,1 @@
-map(lambda x: x, range(10))
+list(map(lambda x: x, list(range(10))))
RefactoringTool: Files that need to be modified:
RefactoringTool: map.py
RefactoringTool: Warnings/messages while refactoring:
RefactoringTool: ### In file map.py ###
RefactoringTool: Line 1: You should use a for loop here
</code></pre>
| 17 | 2009-05-22T11:14:00Z | [
"python"
] |
What is the idiomatic way of invoking a list of functions in Python? | 897,362 | <p>I have a list of callback functions that I need to invoke when an event is fired.
Is this idiomatic python? </p>
<pre><code>def first_callback(m):
print 'first ' + m
def second_callback(m):
print 'second ' + m
lst = [first_callback, second_callback]
map(lambda x: x("event_info"),lst) #is this how you do it?
</code></pre>
| 4 | 2009-05-22T11:09:53Z | 897,379 | <p>You could also write a list comprehension:</p>
<pre><code>[f("event_info") for f in lst]
</code></pre>
<p>However, it does have the side-effect of returning a list of results.</p>
| 3 | 2009-05-22T11:15:11Z | [
"python"
] |
What is the idiomatic way of invoking a list of functions in Python? | 897,362 | <p>I have a list of callback functions that I need to invoke when an event is fired.
Is this idiomatic python? </p>
<pre><code>def first_callback(m):
print 'first ' + m
def second_callback(m):
print 'second ' + m
lst = [first_callback, second_callback]
map(lambda x: x("event_info"),lst) #is this how you do it?
</code></pre>
| 4 | 2009-05-22T11:09:53Z | 1,813,292 | <p>If you have dynamically created list of functions simple for is good:</p>
<p>for function in list_of_functions:
function(your_argument_here)</p>
<p>But if you use OOP and some classes should know that some event happens (generally changes) consider introducing Observer design pattern:
<a href="http://en.wikipedia.org/wiki/Observer%5Fpattern" rel="nofollow">http://en.wikipedia.org/wiki/Observer%5Fpattern</a>,</p>
<p>Introducing pattern means refactoring working code to that pattern (and stopping when code look good even if not whole patter was introduced) read more in "Refactoring to patterns" Kerievsky.</p>
| 0 | 2009-11-28T18:26:31Z | [
"python"
] |
What is the idiomatic way of invoking a list of functions in Python? | 897,362 | <p>I have a list of callback functions that I need to invoke when an event is fired.
Is this idiomatic python? </p>
<pre><code>def first_callback(m):
print 'first ' + m
def second_callback(m):
print 'second ' + m
lst = [first_callback, second_callback]
map(lambda x: x("event_info"),lst) #is this how you do it?
</code></pre>
| 4 | 2009-05-22T11:09:53Z | 1,814,326 | <p>I have to ask if this is truly the OP's intent. When I hear "invoke a list of functions", I assume that just looping over the list of functions and calling each one is so obvious, that there must be more to the question. For instance, given these two string manipulators:</p>
<pre><code>def reverse(s):
return s[::-1]
import random
def randomcase(s):
return ''.join(random.choice((str.upper, str.lower))(c) for c in s)
manips = [reverse, randomcase]
s = "Now is the time for all good men to come to."
# boring loop through list of manips
for fn in manips:
print fn(s)
# more interesting chain through list of manips
s_out = s
for fn in manips:
s_out = fn(s_out)
print s_out
</code></pre>
<p>The first loop prints:</p>
<pre><code>.ot emoc ot nem doog lla rof emit eht si woN
NOW IS THe tIMe for aLL good meN TO COme To.
</code></pre>
<p>The second chains the output of the first function to the input of the next, printing:</p>
<pre><code>.oT EMoC OT NeM DOog lla RoF emit EHt SI won
</code></pre>
<p>This second method allows you to compose more complex functions out of several simple ones.</p>
| 0 | 2009-11-29T01:10:55Z | [
"python"
] |
Regular Expression Sub Problems | 897,480 | <p>Okay so i have a semi weridish problem with re.sub.</p>
<p>Take the following code:</p>
<pre><code>import re
str_to_be_subbed = r'somefile.exe -i <INPUT>'
some_str = r'C:\foobar'
s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed)
print s
</code></pre>
<p>I would think it would give me:</p>
<pre><code>somefile.exe -i C:\\foobar
</code></pre>
<p>But instead it gives me:</p>
<pre><code>somefile.exe -i C:âoobar
</code></pre>
<p>I know \f is an escape char, but even if i try to do it this way, which should escape the special characthers. Even if i do this:</p>
<pre><code>print r'%s' % s
</code></pre>
<p>It still gives me this:</p>
<pre><code>somefile.exe -i C:âoobar
</code></pre>
<p>Why does it do this? And whats the best way to avoid this?</p>
<p>Ninja Edit:</p>
<p>If i look at the value of s it is:</p>
<pre><code>'somefile.exe -i C:\x0coobar'
</code></pre>
<p>Why did \f turn into \x0. Ugh.</p>
<p>Edit:</p>
<p>One more question, if i modify the code to this:</p>
<pre><code>import re
import os
str_to_be_subbed = r'somefile.exe -i <INPUT>'
some_str = os.path.abspath(r'C:\foobar')
some_str
s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed)
print s
</code></pre>
<p>Gives me:</p>
<pre><code>>>> import re
>>> import os
>>> str_to_be_subbed = r'somefile.exe -i <INPUT>'
>>> some_str = os.path.abspath(r'C:\foobar')
>>> some_str
'C:\\foobar'
>>> s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed)
>>> print s
somefile.exe -i C:âoobar
</code></pre>
<p>Now why is that. Since os.path.abspath escapes the \'s. Why does re.sub still mess up?</p>
<p>Also this is a really small example, of this little problem that just cropped up randomly in an oldish application. I can't really go and change this to string.replace because of how its setup without spending a whole day.</p>
<p>I am just really curious as to why it is doing this. For the above problem.</p>
| 3 | 2009-05-22T11:53:15Z | 897,492 | <p><code>\f</code> is the <em>form feed</em> character. Escape it and it works:</p>
<pre><code>some_str = r'C:\\foobar'
</code></pre>
<p>Another solution:</p>
<pre><code>s = re.sub(r'<INPUT>', some_str.encode("string_escape"), str_to_be_subbed)
</code></pre>
| 3 | 2009-05-22T11:58:35Z | [
"python",
"regex"
] |
Regular Expression Sub Problems | 897,480 | <p>Okay so i have a semi weridish problem with re.sub.</p>
<p>Take the following code:</p>
<pre><code>import re
str_to_be_subbed = r'somefile.exe -i <INPUT>'
some_str = r'C:\foobar'
s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed)
print s
</code></pre>
<p>I would think it would give me:</p>
<pre><code>somefile.exe -i C:\\foobar
</code></pre>
<p>But instead it gives me:</p>
<pre><code>somefile.exe -i C:âoobar
</code></pre>
<p>I know \f is an escape char, but even if i try to do it this way, which should escape the special characthers. Even if i do this:</p>
<pre><code>print r'%s' % s
</code></pre>
<p>It still gives me this:</p>
<pre><code>somefile.exe -i C:âoobar
</code></pre>
<p>Why does it do this? And whats the best way to avoid this?</p>
<p>Ninja Edit:</p>
<p>If i look at the value of s it is:</p>
<pre><code>'somefile.exe -i C:\x0coobar'
</code></pre>
<p>Why did \f turn into \x0. Ugh.</p>
<p>Edit:</p>
<p>One more question, if i modify the code to this:</p>
<pre><code>import re
import os
str_to_be_subbed = r'somefile.exe -i <INPUT>'
some_str = os.path.abspath(r'C:\foobar')
some_str
s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed)
print s
</code></pre>
<p>Gives me:</p>
<pre><code>>>> import re
>>> import os
>>> str_to_be_subbed = r'somefile.exe -i <INPUT>'
>>> some_str = os.path.abspath(r'C:\foobar')
>>> some_str
'C:\\foobar'
>>> s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed)
>>> print s
somefile.exe -i C:âoobar
</code></pre>
<p>Now why is that. Since os.path.abspath escapes the \'s. Why does re.sub still mess up?</p>
<p>Also this is a really small example, of this little problem that just cropped up randomly in an oldish application. I can't really go and change this to string.replace because of how its setup without spending a whole day.</p>
<p>I am just really curious as to why it is doing this. For the above problem.</p>
| 3 | 2009-05-22T11:53:15Z | 897,496 | <p>Don't use regular expressions:</p>
<pre><code>print str_to_be_subbed.replace("<INPUT>",some_str)
</code></pre>
<p>As the <a href="http://docs.python.org/library/re.html#re.sub" rel="nofollow">documentation</a> says:</p>
<blockquote>
<p>repl can be a string or a function; if
it is a string, any backslash escapes
in it are processed.</p>
</blockquote>
| 3 | 2009-05-22T11:58:57Z | [
"python",
"regex"
] |
Regular Expression Sub Problems | 897,480 | <p>Okay so i have a semi weridish problem with re.sub.</p>
<p>Take the following code:</p>
<pre><code>import re
str_to_be_subbed = r'somefile.exe -i <INPUT>'
some_str = r'C:\foobar'
s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed)
print s
</code></pre>
<p>I would think it would give me:</p>
<pre><code>somefile.exe -i C:\\foobar
</code></pre>
<p>But instead it gives me:</p>
<pre><code>somefile.exe -i C:âoobar
</code></pre>
<p>I know \f is an escape char, but even if i try to do it this way, which should escape the special characthers. Even if i do this:</p>
<pre><code>print r'%s' % s
</code></pre>
<p>It still gives me this:</p>
<pre><code>somefile.exe -i C:âoobar
</code></pre>
<p>Why does it do this? And whats the best way to avoid this?</p>
<p>Ninja Edit:</p>
<p>If i look at the value of s it is:</p>
<pre><code>'somefile.exe -i C:\x0coobar'
</code></pre>
<p>Why did \f turn into \x0. Ugh.</p>
<p>Edit:</p>
<p>One more question, if i modify the code to this:</p>
<pre><code>import re
import os
str_to_be_subbed = r'somefile.exe -i <INPUT>'
some_str = os.path.abspath(r'C:\foobar')
some_str
s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed)
print s
</code></pre>
<p>Gives me:</p>
<pre><code>>>> import re
>>> import os
>>> str_to_be_subbed = r'somefile.exe -i <INPUT>'
>>> some_str = os.path.abspath(r'C:\foobar')
>>> some_str
'C:\\foobar'
>>> s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed)
>>> print s
somefile.exe -i C:âoobar
</code></pre>
<p>Now why is that. Since os.path.abspath escapes the \'s. Why does re.sub still mess up?</p>
<p>Also this is a really small example, of this little problem that just cropped up randomly in an oldish application. I can't really go and change this to string.replace because of how its setup without spending a whole day.</p>
<p>I am just really curious as to why it is doing this. For the above problem.</p>
| 3 | 2009-05-22T11:53:15Z | 897,513 | <p>Your example doesn't need regexps, use <a href="http://docs.python.org/library/stdtypes.html#str.replace" rel="nofollow"><code>str.replace()</code></a>:</p>
<pre><code>>>> str_to_be_subbed.replace('<INPUT>',some_str)
'somefile.exe -i C:\\foobar'
>>>
</code></pre>
| 0 | 2009-05-22T12:03:14Z | [
"python",
"regex"
] |
Regular Expression Sub Problems | 897,480 | <p>Okay so i have a semi weridish problem with re.sub.</p>
<p>Take the following code:</p>
<pre><code>import re
str_to_be_subbed = r'somefile.exe -i <INPUT>'
some_str = r'C:\foobar'
s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed)
print s
</code></pre>
<p>I would think it would give me:</p>
<pre><code>somefile.exe -i C:\\foobar
</code></pre>
<p>But instead it gives me:</p>
<pre><code>somefile.exe -i C:âoobar
</code></pre>
<p>I know \f is an escape char, but even if i try to do it this way, which should escape the special characthers. Even if i do this:</p>
<pre><code>print r'%s' % s
</code></pre>
<p>It still gives me this:</p>
<pre><code>somefile.exe -i C:âoobar
</code></pre>
<p>Why does it do this? And whats the best way to avoid this?</p>
<p>Ninja Edit:</p>
<p>If i look at the value of s it is:</p>
<pre><code>'somefile.exe -i C:\x0coobar'
</code></pre>
<p>Why did \f turn into \x0. Ugh.</p>
<p>Edit:</p>
<p>One more question, if i modify the code to this:</p>
<pre><code>import re
import os
str_to_be_subbed = r'somefile.exe -i <INPUT>'
some_str = os.path.abspath(r'C:\foobar')
some_str
s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed)
print s
</code></pre>
<p>Gives me:</p>
<pre><code>>>> import re
>>> import os
>>> str_to_be_subbed = r'somefile.exe -i <INPUT>'
>>> some_str = os.path.abspath(r'C:\foobar')
>>> some_str
'C:\\foobar'
>>> s = re.sub(r'\<INPUT\>', some_str, str_to_be_subbed)
>>> print s
somefile.exe -i C:âoobar
</code></pre>
<p>Now why is that. Since os.path.abspath escapes the \'s. Why does re.sub still mess up?</p>
<p>Also this is a really small example, of this little problem that just cropped up randomly in an oldish application. I can't really go and change this to string.replace because of how its setup without spending a whole day.</p>
<p>I am just really curious as to why it is doing this. For the above problem.</p>
| 3 | 2009-05-22T11:53:15Z | 14,576,905 | <p>Python docs saying...</p>
<p>re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isnât found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes such as \j are left alone</p>
<p>This is why it gives 'C:âoobar'.</p>
<p>but if we give it a function as the second argument, it doesn't convert any backslash escapes.</p>
<p>So try following..</p>
<pre><code>>>>import re
>>>str_to_be_subbed = r'somefile.exe -i <INPUT>'
>>>some_str = r'C:\foobar'
>>>s = re.sub(r'\<INPUT\>', lambda _:some_str, str_to_be_subbed)
>>>print s
somefile.exe -i c:\foobar
</code></pre>
| 2 | 2013-01-29T06:27:07Z | [
"python",
"regex"
] |
How do I refer to a class method outside a function body in Python? | 897,739 | <p>I want to do a one time callback registration within Observer. I don't want to do the registration inside init or other function. I don't know if there is a class level equivalent for init</p>
<pre><code> class Observer:
@classmethod
def on_new_user_registration(new_user):
#body of handler...
# first I try
NewUserRegistered().subscribe \
(Observer.on_new_user_registration) #gives NameError for Observer
#so I try
NewUserRegistered().subscribe(on_new_user_registration) #says not callable
#neither does this work
NewUserRegistered().subscribe(__metaclass__.on_new_user_registration)
class BaseEvent(object):
_subscriptions = {}
def __init__(self, event_info = None):
self.info = event_info
def fire(self):
for callback in self._subscriptions[event_type]:
callback(event_info)
def subscribe(self, callback):
if not callable(callback):
raise Exception(str(callback) + 'is not callable')
existing = self._subscriptions.get(self.__class__, None)
if not existing:
existing = set()
self._subscriptions[self.__class__] = existing
existing.add(callback)
class NewUserRegistered(BaseEvent):
pass
</code></pre>
| 1 | 2009-05-22T13:06:20Z | 897,830 | <p>I've come to accept that python isn't very intuitive when it comes to functional programming within class definitions. See <a href="http://stackoverflow.com/questions/707090/decorators-and-in-class">this question</a>. The problem with the first method is that Observer doesn't exist as a namespace until the class has been built. The problem with the second is that you've made a class method that doesn't really do what it's supposed to until after the namespace has been created. (I have no idea why you're trying the third.) In both case neither of these things occurs until after the class definition of Observer has been populated.</p>
<p>This might sound like a sad constraint, but it's really not so bad. Just register <em>after</em> the class definition. Once you realize that it's not bad style to perform certain initialization routines on classes in the body of the module but outside the body of the class, python becomes a lot friendlier. Try:
class Observer:</p>
<pre><code># Define the other classes first
class Observer:
@classmethod
def on_new_user_registration(new_user):
#body of handler...
NewUserRegistered().subscribe(Observer.on_new_user_registration)
</code></pre>
<p>Because of the way modules work in python, you are guaranteed that this registration will be performed once and only once (barring process forking and maybe some other irrelevant boundary cases) wherever Observer is imported.</p>
| 1 | 2009-05-22T13:23:50Z | [
"python"
] |
How do I refer to a class method outside a function body in Python? | 897,739 | <p>I want to do a one time callback registration within Observer. I don't want to do the registration inside init or other function. I don't know if there is a class level equivalent for init</p>
<pre><code> class Observer:
@classmethod
def on_new_user_registration(new_user):
#body of handler...
# first I try
NewUserRegistered().subscribe \
(Observer.on_new_user_registration) #gives NameError for Observer
#so I try
NewUserRegistered().subscribe(on_new_user_registration) #says not callable
#neither does this work
NewUserRegistered().subscribe(__metaclass__.on_new_user_registration)
class BaseEvent(object):
_subscriptions = {}
def __init__(self, event_info = None):
self.info = event_info
def fire(self):
for callback in self._subscriptions[event_type]:
callback(event_info)
def subscribe(self, callback):
if not callable(callback):
raise Exception(str(callback) + 'is not callable')
existing = self._subscriptions.get(self.__class__, None)
if not existing:
existing = set()
self._subscriptions[self.__class__] = existing
existing.add(callback)
class NewUserRegistered(BaseEvent):
pass
</code></pre>
| 1 | 2009-05-22T13:06:20Z | 897,840 | <p>oops. sorry about that.
All I had to do was to move the subscription outside the class definition</p>
<pre><code>class Observer:
@classmethod
def on_new_user_registration(new_user):
#body of handler...
#after end of class
NewUserRegistered().subscribe(Observer.on_new_user_registration)
</code></pre>
<p>Guess it is a side-effect of too much Java that one doesn't immediately think of this.</p>
| 0 | 2009-05-22T13:25:06Z | [
"python"
] |
How do I refer to a class method outside a function body in Python? | 897,739 | <p>I want to do a one time callback registration within Observer. I don't want to do the registration inside init or other function. I don't know if there is a class level equivalent for init</p>
<pre><code> class Observer:
@classmethod
def on_new_user_registration(new_user):
#body of handler...
# first I try
NewUserRegistered().subscribe \
(Observer.on_new_user_registration) #gives NameError for Observer
#so I try
NewUserRegistered().subscribe(on_new_user_registration) #says not callable
#neither does this work
NewUserRegistered().subscribe(__metaclass__.on_new_user_registration)
class BaseEvent(object):
_subscriptions = {}
def __init__(self, event_info = None):
self.info = event_info
def fire(self):
for callback in self._subscriptions[event_type]:
callback(event_info)
def subscribe(self, callback):
if not callable(callback):
raise Exception(str(callback) + 'is not callable')
existing = self._subscriptions.get(self.__class__, None)
if not existing:
existing = set()
self._subscriptions[self.__class__] = existing
existing.add(callback)
class NewUserRegistered(BaseEvent):
pass
</code></pre>
| 1 | 2009-05-22T13:06:20Z | 897,852 | <p>What you're doing should work:</p>
<pre><code>>>> class foo:
... @classmethod
... def func(cls):
... print 'func called!'
...
>>> foo.func()
func called!
>>> class foo:
... @classmethod
... def func(cls):
... print 'func called!'
... foo.func()
...
func called!
</code></pre>
<p>One thing to note though, class methods take a cls argument instead of a self argument. Thus, your class definition should look like this:</p>
<pre><code>class Observer:
@classmethod
def on_new_user_registration(cls, new_user):
#body of handler...
</code></pre>
| 0 | 2009-05-22T13:27:09Z | [
"python"
] |
How do I refer to a class method outside a function body in Python? | 897,739 | <p>I want to do a one time callback registration within Observer. I don't want to do the registration inside init or other function. I don't know if there is a class level equivalent for init</p>
<pre><code> class Observer:
@classmethod
def on_new_user_registration(new_user):
#body of handler...
# first I try
NewUserRegistered().subscribe \
(Observer.on_new_user_registration) #gives NameError for Observer
#so I try
NewUserRegistered().subscribe(on_new_user_registration) #says not callable
#neither does this work
NewUserRegistered().subscribe(__metaclass__.on_new_user_registration)
class BaseEvent(object):
_subscriptions = {}
def __init__(self, event_info = None):
self.info = event_info
def fire(self):
for callback in self._subscriptions[event_type]:
callback(event_info)
def subscribe(self, callback):
if not callable(callback):
raise Exception(str(callback) + 'is not callable')
existing = self._subscriptions.get(self.__class__, None)
if not existing:
existing = set()
self._subscriptions[self.__class__] = existing
existing.add(callback)
class NewUserRegistered(BaseEvent):
pass
</code></pre>
| 1 | 2009-05-22T13:06:20Z | 898,517 | <p>I suggest to cut down on the number of classes -- remember that Python isn't Java. Every time you use <code>@classmethod</code> or <code>@staticmethod</code> you should stop and think about it since these keywords are quite rare in Python.</p>
<p>Doing it like this works:</p>
<pre><code>class BaseEvent(object):
def __init__(self, event_info=None):
self._subscriptions = set()
self.info = event_info
def fire(self, data):
for callback in self._subscriptions:
callback(self.info, data)
def subscribe(self, callback):
if not callable(callback):
raise ValueError("%r is not callable" % callback)
self._subscriptions.add(callback)
return callback
new_user = BaseEvent()
@new_user.subscribe
def on_new_user_registration(info, username):
print "new user: %s" % username
new_user.fire("Martin")
</code></pre>
<p>If you want an Observer class, then you can do it like this:</p>
<p>class Observer:</p>
<pre><code>@staticmethod
@new_user.subscribe
def on_new_user_registration(info, username):
print "new user: %s" % username
</code></pre>
<p>But note that the static method does not have access to the protocol instance, so this is probably not very useful. You can not subscribe a method bound to an object instance like this since the object wont exist when the class definition is executed.</p>
<p>But you can of course do this:</p>
<pre><code>class Observer:
def on_new_user_registration(self, info, username):
print "new user: %s" % username
o = Observer()
new_user.subscribe(o.on_new_user_registration)
</code></pre>
<p>where we use the bound <code>o.on_new_user_registration</code> as argument to subscribe.</p>
| 2 | 2009-05-22T15:36:08Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.