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 |
|---|---|---|---|---|---|---|---|---|---|
Something wrong with output from list in Python
| 743,248
|
<p>I want a Python program to import a list of words from a text file and print out the content of the text file as two lists. The data in the text file is on this form: </p>
<pre><code>A Alfa
B Betta
C Charlie
</code></pre>
<p>I want a Python program to print out one list with A,B,C and one with Alfa, Betta, Charlie.</p>
<p>This is what I've written:</p>
<pre><code>english2german = open('english2german.txt', 'r')
englist = []
gerlist = []
for i, line in enumerate(english2german):
englist[i:], gerlist[i:] = line.split()
</code></pre>
<p>This is making two lists, but will only print out the first letter in each word.
How can I make my code to print out the whole word?</p>
| 2
|
2009-04-13T07:16:48Z
| 744,098
|
<p>Slightly meta-answer(?) to <a href="http://stackoverflow.com/questions/743248/something-wrong-with-output-from-list-in-python/743313#743313">Autoplectic's</a> suggestion of using <code>zip()</code></p>
<p>With 3 lines in the input file (from the supplied data in the question):</p>
<p>The <code>zip()</code> method takes an average of <code>0.404729390144</code> seconds, compared to <code>0.341339087486</code> with the simple for loop constructing two lists (the code from <a href="http://stackoverflow.com/questions/743248/something-wrong-with-output-from-list-in-python/743268#743268">mipadi's</a> currently accepted answer).</p>
<p>With 10,000 lines in the input file (random generated 3-12 character words. I reduced the <code>timeit.repeat()</code> values to 100 times, repeated twice):</p>
<p><code>zip()</code> took an average of <code>1.43965339661</code> seconds, compared to <code>1.52318406105</code> with the for loop.</p>
<p>Both benchmarks were done using Python version 2.5.1</p>
<p>Hardly a huge difference.. Given how much more readable the simple for loop is, I would recommend using it.. The <code>zip</code> code might be a bit quicker with large files, but the difference is about 0.083 seconds with 10,000 lines..</p>
<p>Benchmarking code:</p>
<pre><code>import timeit
# http://stackoverflow.com/questions/743248/something-wrong-with-output-from-list-in-python/743313#743313
code_zip = """english2german = open('english2german.txt')
eng, ger = zip(*( line.split() for line in english2german ))
"""
# http://stackoverflow.com/questions/743248/something-wrong-with-output-from-list-in-python/743268#743268
code_for = """english2german = open("english2german.txt")
englist = []
gerlist = []
for line in english2german:
(e, g) = line.split()
englist.append(e)
gerlist.append(g)
"""
for code in [code_zip, code_for]:
t = timeit.Timer(stmt = code)
try:
times = t.repeat(10, 10000)
except:
t.print_exc()
else:
print "Code:"
print code
print "Time:"
print times
print "Average:"
print sum(times) / len(times)
print "-" * 20
</code></pre>
| 1
|
2009-04-13T14:37:42Z
|
[
"python",
"list",
"text"
] |
how to convert string representation bytes back to bytes?
| 743,374
|
<p>I am using SUDS to talk with a web service written by C#. The service recieves a url, crawls its web page, then return its content as byte[].</p>
<p>its type in SOAP is:</p>
<pre><code><s:element minOccurs="0" maxOccurs="1" name="rawByte" type="s:base64Binary" />
</code></pre>
<p>sample client codes:</p>
<pre><code>>>> from suds.client import Client
>>> url = "http://WSServer/Service1.asmx?wsdl"
>>> client = Client(url)
>>> page = client.service.GetURLContent("http://www.google.co.uk")
>>> print page
(CrawlResult){
crawStatus = "SUCC"
rawByte = "PGh0bWw+PGhlYWQ+PG1ldGEgaHR0cC1lcXVpdj0iY29udGVudC10eXBlIiBjb2 ... "
</code></pre>
<p>the problem is how to convert the rawByte from string to bytes, then explain it as text with encoding (like "ascii").</p>
<p>I am not clear with that.</p>
<p>Thanks,
Daniel.</p>
| 1
|
2009-04-13T08:42:41Z
| 743,381
|
<p>As the SOAP element says, the bytes are <a href="http://en.wikipedia.org/wiki/Base64" rel="nofollow">base64-encoded</a>.</p>
<p>To decode, use the python module
<a href="http://docs.python.org/library/base64.html" rel="nofollow"><code>base64</code></a>.</p>
| 3
|
2009-04-13T08:47:05Z
|
[
"python",
"web-services"
] |
how to convert string representation bytes back to bytes?
| 743,374
|
<p>I am using SUDS to talk with a web service written by C#. The service recieves a url, crawls its web page, then return its content as byte[].</p>
<p>its type in SOAP is:</p>
<pre><code><s:element minOccurs="0" maxOccurs="1" name="rawByte" type="s:base64Binary" />
</code></pre>
<p>sample client codes:</p>
<pre><code>>>> from suds.client import Client
>>> url = "http://WSServer/Service1.asmx?wsdl"
>>> client = Client(url)
>>> page = client.service.GetURLContent("http://www.google.co.uk")
>>> print page
(CrawlResult){
crawStatus = "SUCC"
rawByte = "PGh0bWw+PGhlYWQ+PG1ldGEgaHR0cC1lcXVpdj0iY29udGVudC10eXBlIiBjb2 ... "
</code></pre>
<p>the problem is how to convert the rawByte from string to bytes, then explain it as text with encoding (like "ascii").</p>
<p>I am not clear with that.</p>
<p>Thanks,
Daniel.</p>
| 1
|
2009-04-13T08:42:41Z
| 743,410
|
<p>I need to convert it back to string with the binascii module, like:</p>
<pre><code>>>> btxt = binascii.a2b_base64(page.rawByte)
</code></pre>
<p>then btxt can be treated as a normal string.</p>
| 2
|
2009-04-13T09:07:06Z
|
[
"python",
"web-services"
] |
Split string into a list in Python
| 743,806
|
<p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word in words:
# print the word
print(word)
</code></pre>
| 217
|
2009-04-13T12:48:44Z
| 743,807
|
<p>Splits the string in <code>text</code> on delimiter: <code>" "</code>.</p>
<pre><code>words = text.split()
</code></pre>
<p>Split the string in <code>text</code> on delimiter: <code>","</code>.</p>
<pre><code>words = text.split(",")
</code></pre>
<p>The words variable will be a list datatype and contain a list of words from <code>text</code> split on the delimiter.</p>
| 196
|
2009-04-13T12:50:21Z
|
[
"python",
"list",
"split",
"text-segmentation"
] |
Split string into a list in Python
| 743,806
|
<p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word in words:
# print the word
print(word)
</code></pre>
| 217
|
2009-04-13T12:48:44Z
| 743,823
|
<pre><code>text.split()
</code></pre>
<p>This should be enough to store each word in a list. <code>words</code> is already a list of the words from the sentence, so there is no need for the loop.</p>
<p>Second, it might be a typo, but you have your loop a little messed up. If you really did want to use append, it would be:</p>
<pre><code>words.append(word)
</code></pre>
<p>not </p>
<pre><code>word.append(words)
</code></pre>
| 178
|
2009-04-13T12:54:16Z
|
[
"python",
"list",
"split",
"text-segmentation"
] |
Split string into a list in Python
| 743,806
|
<p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word in words:
# print the word
print(word)
</code></pre>
| 217
|
2009-04-13T12:48:44Z
| 743,824
|
<p><a href="https://docs.python.org/2/library/stdtypes.html#str.split">str.split()</a></p>
<blockquote>
<p>Return a <strong>list of the words</strong> in the string, using sep as the delimiter
... If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. </p>
</blockquote>
<pre><code>>>> line="a sentence with a few words"
>>> line.split()
['a', 'sentence', 'with', 'a', 'few', 'words']
>>>
</code></pre>
| 47
|
2009-04-13T12:54:58Z
|
[
"python",
"list",
"split",
"text-segmentation"
] |
Split string into a list in Python
| 743,806
|
<p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word in words:
# print the word
print(word)
</code></pre>
| 217
|
2009-04-13T12:48:44Z
| 743,865
|
<p>I think you are confused because of a typo. </p>
<p>Replace <code>print(words)</code> with <code>print(word)</code> inside your loop to have every word printed on a different line</p>
| 1
|
2009-04-13T13:17:13Z
|
[
"python",
"list",
"split",
"text-segmentation"
] |
Split string into a list in Python
| 743,806
|
<p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word in words:
# print the word
print(word)
</code></pre>
| 217
|
2009-04-13T12:48:44Z
| 743,922
|
<blockquote>
<p>I want my python function to split a sentence (input) and store each word in a list</p>
</blockquote>
<p>The <code>str().split()</code> method does this, it takes a string, splits it into a list:</p>
<pre><code>>>> the_string = "this is a sentence"
>>> words = the_string.split(" ")
>>> print(words)
['this', 'is', 'a', 'sentence']
>>> type(words)
<type 'list'> # or <class 'list'> in Python 3.0
</code></pre>
<p>The problem you're having is because of a typo, you wrote <code>print(words)</code> instead of <code>print(word)</code>:</p>
<p>Renaming the <code>word</code> variable to <code>current_word</code>, this is what you had:</p>
<pre><code>def split_line(text):
words = text.split()
for current_word in words:
print(words)
</code></pre>
<p>..when you should have done:</p>
<pre><code>def split_line(text):
words = text.split()
for current_word in words:
print(current_word)
</code></pre>
<p>If for some reason you want to manually construct a list in the for loop, you would use the list <code>append()</code> method, perhaps because you want to lower-case all words (for example):</p>
<pre><code>my_list = [] # make empty list
for current_word in words:
my_list.append(current_word.lower())
</code></pre>
<p>Or more a bit neater, using a <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list-comprehension</a>:</p>
<pre><code>my_list = [current_word.lower() for current_word in words]
</code></pre>
| 9
|
2009-04-13T13:46:06Z
|
[
"python",
"list",
"split",
"text-segmentation"
] |
Split string into a list in Python
| 743,806
|
<p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word in words:
# print the word
print(word)
</code></pre>
| 217
|
2009-04-13T12:48:44Z
| 744,046
|
<p>Depending on what you plan to do with your sentence-as-a-list, you may want to look at the <a href="http://www.nltk.org/">Natural Language Took Kit</a>. It deals heavily with text processing and evaluation. You can also use it to solve your problem:</p>
<pre><code>import nltk
words = nltk.word_tokenize(raw_sentence)
</code></pre>
<p>This has the added benefit of splitting out punctuation.</p>
<p>Example:</p>
<pre><code>>>> import nltk
>>> s = "The fox's foot grazed the sleeping dog, waking it."
>>> words = nltk.word_tokenize(s)
>>> words
['The', 'fox', "'s", 'foot', 'grazed', 'the', 'sleeping', 'dog', ',',
'waking', 'it', '.']
</code></pre>
<p>This allows you to filter out any punctuation you don't want and use only words. </p>
<p>Please note that the other solutions using <code>string.split()</code> are better if you don't plan on doing any complex manipulation of the sentance.</p>
| 35
|
2009-04-13T14:24:18Z
|
[
"python",
"list",
"split",
"text-segmentation"
] |
Split string into a list in Python
| 743,806
|
<p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word in words:
# print the word
print(word)
</code></pre>
| 217
|
2009-04-13T12:48:44Z
| 17,951,315
|
<p>How about this algorithm? Split text on whitespace, then trim punctuation. This carefully removes punctuation from the edge of words, without harming apostrophes inside words such as <code>we're</code>.</p>
<pre><code>>>> text
"'Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad.'"
>>> text.split()
["'Oh,", 'you', "can't", 'help', "that,'", 'said', 'the', 'Cat:', "'we're", 'all', 'mad', 'here.', "I'm", 'mad.', "You're", "mad.'"]
>>> import string
>>> [word.strip(string.punctuation) for word in text.split()]
['Oh', 'you', "can't", 'help', 'that', 'said', 'the', 'Cat', "we're", 'all', 'mad', 'here', "I'm", 'mad', "You're", 'mad']
</code></pre>
| 16
|
2013-07-30T15:32:43Z
|
[
"python",
"list",
"split",
"text-segmentation"
] |
Split string into a list in Python
| 743,806
|
<p>I want my python function to split a sentence (input) and store each word in a list. The code that I've written so far splits the sentence, but does not store the words as a list. How do I do that?</p>
<pre><code>def split_line(text):
# split the text
words = text.split()
# for each word in the line:
for word in words:
# print the word
print(word)
</code></pre>
| 217
|
2009-04-13T12:48:44Z
| 20,270,958
|
<p><a href="https://docs.python.org/library/shlex.html" rel="nofollow">shlex</a> has a <a href="https://docs.python.org/library/shlex.html#shlex.split" rel="nofollow"><code>.split()</code></a> function. It differs from <code>str.split()</code> in that it does not preserve quotes and treats a quoted phrase as a single word:</p>
<pre><code>>>> import shlex
>>> shlex.split("sudo echo 'foo && bar'")
['sudo', 'echo', 'foo && bar']
</code></pre>
| 6
|
2013-11-28T16:33:44Z
|
[
"python",
"list",
"split",
"text-segmentation"
] |
I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters
| 744,127
|
<p>For example,
The function could be something like def RandABCD(n, .25, .34, .25, .25):</p>
<p>Where n is the length of the string to be generated and the following numbers are the desired probabilities of A, B, C, D.</p>
<p>I would imagine this is quite simple, however i am having trouble creating a working program. Any help would be greatly appreciated. </p>
| 2
|
2009-04-13T14:48:24Z
| 744,170
|
<p>The random class is quite powerful in python. You can generate a list with the characters desired at the appropriate weights and then use random.choice to obtain a selection. </p>
<p>First, make sure you do an import random.</p>
<p>For example, let's say you wanted a truly random string from A,B,C, or D.
1. Generate a list with the characters
li = ['A','B','C','D']</p>
<ol>
<li>Then obtain values from it using random.choice
output = "".join([random.choice(li) for i in range(0, n)])</li>
</ol>
<p>You could easily make that a function with n as a parameter.</p>
<p>In the above case, you have an equal chance of getting A,B,C, or D. </p>
<p>You can use duplicate entries in the list to give characters higher probabilities. So, for example, let's say you wanted a 50% chance of A and 25% chances of B and C respectively. You could have an array like this:</p>
<p>li = ['A','A','B','C']</p>
<p>And so on.</p>
<p>It would not be hard to parameterize the characters coming in with desired weights, to model that I'd use a dictionary. </p>
<p>characterbasis = {'A':25, 'B':25, 'C':25, 'D':25}</p>
<p>Make that the first parameter, and the second being the length of the string and use the above code to generate your string.</p>
| 2
|
2009-04-13T15:00:50Z
|
[
"python",
"random"
] |
I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters
| 744,127
|
<p>For example,
The function could be something like def RandABCD(n, .25, .34, .25, .25):</p>
<p>Where n is the length of the string to be generated and the following numbers are the desired probabilities of A, B, C, D.</p>
<p>I would imagine this is quite simple, however i am having trouble creating a working program. Any help would be greatly appreciated. </p>
| 2
|
2009-04-13T14:48:24Z
| 744,201
|
<p>For four letters, here's something quick off the top of my head:</p>
<pre><code>from random import random
def randABCD(n, pA, pB, pC, pD):
# assumes pA + pB + pC + pD == 1
cA = pA
cB = cA + pB
cC = cB + pC
def choose():
r = random()
if r < cA:
return 'A'
elif r < cB:
return 'B'
elif r < cC:
return 'C'
else:
return 'D'
return ''.join([choose() for i in xrange(n)])
</code></pre>
<p>I have no doubt that this can be made much cleaner/shorter, I'm just in a bit of a hurry right now.</p>
<p>The reason I wouldn't be content with David in Dakota's answer of using a list of duplicate characters is that depending on your probabilities, it may not be possible to create a list with duplicates in the right numbers to simulate the probabilities you want. (Well, I guess it might always be possible, but you might wind up needing a huge list - what if your probabilities were 0.11235442079, 0.4072777384, 0.2297927874, 0.25057505341?)</p>
<p><em>EDIT</em>: here's a much cleaner generic version that works with any number of letters with any weights:</p>
<pre><code>from bisect import bisect
from random import uniform
def rand_string(n, content):
''' Creates a string of letters (or substrings) chosen independently
with specified probabilities. content is a dictionary mapping
a substring to its "weight" which is proportional to its probability,
and n is the desired number of elements in the string.
This does not assume the sum of the weights is 1.'''
l, cdf = zip(*[(l, w) for l, w in content.iteritems()])
cdf = list(cdf)
for i in xrange(1, len(cdf)):
cdf[i] += cdf[i - 1]
return ''.join([l[bisect(cdf, uniform(0, cdf[-1]))] for i in xrange(n)])
</code></pre>
| 2
|
2009-04-13T15:11:11Z
|
[
"python",
"random"
] |
I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters
| 744,127
|
<p>For example,
The function could be something like def RandABCD(n, .25, .34, .25, .25):</p>
<p>Where n is the length of the string to be generated and the following numbers are the desired probabilities of A, B, C, D.</p>
<p>I would imagine this is quite simple, however i am having trouble creating a working program. Any help would be greatly appreciated. </p>
| 2
|
2009-04-13T14:48:24Z
| 744,222
|
<p>Here is a rough idea of what might suit you</p>
<pre><code>import random as r
def distributed_choice(probs):
r= r.random()
cum = 0.0
for pair in probs:
if (r < cum + pair[1]):
return pair[0]
cum += pair[1]
</code></pre>
<p>The parameter <code>probs</code> takes a list of pairs of the form (object, probability). It is assumed that the sum of probabilities is 1 (otherwise, its trivial to normalize).</p>
<p>To use it just execute:</p>
<pre><code>''.join([distributed_choice(probs)]*4)
</code></pre>
| 0
|
2009-04-13T15:16:33Z
|
[
"python",
"random"
] |
I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters
| 744,127
|
<p>For example,
The function could be something like def RandABCD(n, .25, .34, .25, .25):</p>
<p>Where n is the length of the string to be generated and the following numbers are the desired probabilities of A, B, C, D.</p>
<p>I would imagine this is quite simple, however i am having trouble creating a working program. Any help would be greatly appreciated. </p>
| 2
|
2009-04-13T14:48:24Z
| 744,233
|
<p>Here's the code to select a single weighted value. You should be able to take it from here. It uses <a href="http://docs.python.org/library/bisect.html#bisect.bisect" rel="nofollow">bisect</a> and <a href="http://docs.python.org/library/random.html#random.random" rel="nofollow">random</a> to accomplish the work.</p>
<pre><code>from bisect import bisect
from random import random
def WeightedABCD(*weights):
chars = 'ABCD'
breakpoints = [sum(weights[:x+1]) for x in range(4)]
return chars[bisect(breakpoints, random())]
</code></pre>
<p>Call it like this: <code>WeightedABCD(.25, .34, .25, .25)</code>.</p>
<p><strong>EDIT: Here is a version that works even if the weights don't add up to 1.0:</strong></p>
<pre><code>from bisect import bisect_left
from random import uniform
def WeightedABCD(*weights):
chars = 'ABCD'
breakpoints = [sum(weights[:x+1]) for x in range(4)]
return chars[bisect_left(breakpoints, uniform(0.0,breakpoints[-1]))]
</code></pre>
| 4
|
2009-04-13T15:20:34Z
|
[
"python",
"random"
] |
I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters
| 744,127
|
<p>For example,
The function could be something like def RandABCD(n, .25, .34, .25, .25):</p>
<p>Where n is the length of the string to be generated and the following numbers are the desired probabilities of A, B, C, D.</p>
<p>I would imagine this is quite simple, however i am having trouble creating a working program. Any help would be greatly appreciated. </p>
| 2
|
2009-04-13T14:48:24Z
| 744,240
|
<p>Hmm, something like:</p>
<pre><code>import random
class RandomDistribution:
def __init__(self, kv):
self.entries = kv.keys()
self.where = []
cnt = 0
for x in self.entries:
self.where.append(cnt)
cnt += kv[x]
self.where.append(cnt)
def find(self, key):
l, r = 0, len(self.where)-1
while l+1 < r:
m = (l+r)/2
if self.where[m] <= key:
l=m
else:
r=m
return self.entries[l]
def randomselect(self):
return self.find(random.random()*self.where[-1])
rd = RandomDistribution( {"foo": 5.5, "bar": 3.14, "baz": 2.8 } )
for x in range(1000):
print rd.randomselect()
</code></pre>
<p>should get you most of the way...</p>
| 0
|
2009-04-13T15:21:31Z
|
[
"python",
"random"
] |
I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters
| 744,127
|
<p>For example,
The function could be something like def RandABCD(n, .25, .34, .25, .25):</p>
<p>Where n is the length of the string to be generated and the following numbers are the desired probabilities of A, B, C, D.</p>
<p>I would imagine this is quite simple, however i am having trouble creating a working program. Any help would be greatly appreciated. </p>
| 2
|
2009-04-13T14:48:24Z
| 747,392
|
<p>Thank you all for your help, I was able to figure something out, mostly with this info.
For my particular need, I did something like this:</p>
<pre><code>import random
#Create a function to randomize a given string
def makerandom(seq):
return ''.join(random.sample(seq, len(seq)))
def randomDNA(n, probA=0.25, probC=0.25, probG=0.25, probT=0.25):
notrandom=''
A=int(n*probA)
C=int(n*probC)
T=int(n*probT)
G=int(n*probG)
#The remainder part here is used to make sure all n are used, as one cannot
#have half an A for example.
remainder=''
for i in range(0, n-(A+G+C+T)):
ramainder+=random.choice("ATGC")
notrandom=notrandom+ 'A'*A+ 'C'*C+ 'G'*G+ 'T'*T + remainder
return makerandom(notrandom)
</code></pre>
| 0
|
2009-04-14T12:50:06Z
|
[
"python",
"random"
] |
Reading Huge File in Python
| 744,256
|
<p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more efficient Python foo to get this down to a reasonable efficiency of a couple of seconds at most.</p>
<pre><code># list contains a sorted list of the keys we need to lookup
# there is a sentinel at the end of list to simplify the code
# we use pointer to iterate through the list of keys
for line in fin:
line = map(int, line.split())
while line[0] == list[pointer].key:
list[pointer].value = line[1]
pointer += 1
while line[0] > list[pointer].key:
pointer += 1
if pointer >= len(list) - 1:
break # end of list; -1 is due to sentinel
</code></pre>
<p>Coded binary search + seek solution (thanks kigurai!):</p>
<pre><code>entries = 24935502 # number of entries
width = 18 # fixed width of an entry in the file padded with spaces
# at the end of each line
for i, search in enumerate(list): # list contains the list of search keys
left, right = 0, entries-1
key = None
while key != search and left <= right:
mid = (left + right) / 2
fin.seek(mid * width)
key, value = map(int, fin.readline().split())
if search > key:
left = mid + 1
else:
right = mid - 1
if key != search:
value = None # for when search key is not found
search.result = value # store the result of the search
</code></pre>
| 12
|
2009-04-13T15:28:04Z
| 744,269
|
<p>I would use memory-maping: <a href="http://docs.python.org/library/mmap.html" rel="nofollow">http://docs.python.org/library/mmap.html</a>.<br />
This way you can use the file as if it's stored in memory, but the OS decides which pages should actually be read from the file.</p>
| 3
|
2009-04-13T15:32:40Z
|
[
"python",
"performance",
"file-io",
"large-files"
] |
Reading Huge File in Python
| 744,256
|
<p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more efficient Python foo to get this down to a reasonable efficiency of a couple of seconds at most.</p>
<pre><code># list contains a sorted list of the keys we need to lookup
# there is a sentinel at the end of list to simplify the code
# we use pointer to iterate through the list of keys
for line in fin:
line = map(int, line.split())
while line[0] == list[pointer].key:
list[pointer].value = line[1]
pointer += 1
while line[0] > list[pointer].key:
pointer += 1
if pointer >= len(list) - 1:
break # end of list; -1 is due to sentinel
</code></pre>
<p>Coded binary search + seek solution (thanks kigurai!):</p>
<pre><code>entries = 24935502 # number of entries
width = 18 # fixed width of an entry in the file padded with spaces
# at the end of each line
for i, search in enumerate(list): # list contains the list of search keys
left, right = 0, entries-1
key = None
while key != search and left <= right:
mid = (left + right) / 2
fin.seek(mid * width)
key, value = map(int, fin.readline().split())
if search > key:
left = mid + 1
else:
right = mid - 1
if key != search:
value = None # for when search key is not found
search.result = value # store the result of the search
</code></pre>
| 12
|
2009-04-13T15:28:04Z
| 744,272
|
<p>It's not clear what "list[pointer]" is all about. Consider this, however.</p>
<pre><code>from collections import defaultdict
keyValues= defaultdict(list)
targetKeys= # some list of keys
for line in fin:
key, value = map( int, line.split())
if key in targetKeys:
keyValues[key].append( value )
</code></pre>
| 4
|
2009-04-13T15:33:48Z
|
[
"python",
"performance",
"file-io",
"large-files"
] |
Reading Huge File in Python
| 744,256
|
<p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more efficient Python foo to get this down to a reasonable efficiency of a couple of seconds at most.</p>
<pre><code># list contains a sorted list of the keys we need to lookup
# there is a sentinel at the end of list to simplify the code
# we use pointer to iterate through the list of keys
for line in fin:
line = map(int, line.split())
while line[0] == list[pointer].key:
list[pointer].value = line[1]
pointer += 1
while line[0] > list[pointer].key:
pointer += 1
if pointer >= len(list) - 1:
break # end of list; -1 is due to sentinel
</code></pre>
<p>Coded binary search + seek solution (thanks kigurai!):</p>
<pre><code>entries = 24935502 # number of entries
width = 18 # fixed width of an entry in the file padded with spaces
# at the end of each line
for i, search in enumerate(list): # list contains the list of search keys
left, right = 0, entries-1
key = None
while key != search and left <= right:
mid = (left + right) / 2
fin.seek(mid * width)
key, value = map(int, fin.readline().split())
if search > key:
left = mid + 1
else:
right = mid - 1
if key != search:
value = None # for when search key is not found
search.result = value # store the result of the search
</code></pre>
| 12
|
2009-04-13T15:28:04Z
| 744,284
|
<p>If you only need 200 of 50 million lines, then reading all of it into memory is a waste. I would sort the list of search keys and then apply binary search to the file using seek() or something similar. This way you would not read the entire file to memory which I think should speed things up.</p>
| 11
|
2009-04-13T15:37:33Z
|
[
"python",
"performance",
"file-io",
"large-files"
] |
Reading Huge File in Python
| 744,256
|
<p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more efficient Python foo to get this down to a reasonable efficiency of a couple of seconds at most.</p>
<pre><code># list contains a sorted list of the keys we need to lookup
# there is a sentinel at the end of list to simplify the code
# we use pointer to iterate through the list of keys
for line in fin:
line = map(int, line.split())
while line[0] == list[pointer].key:
list[pointer].value = line[1]
pointer += 1
while line[0] > list[pointer].key:
pointer += 1
if pointer >= len(list) - 1:
break # end of list; -1 is due to sentinel
</code></pre>
<p>Coded binary search + seek solution (thanks kigurai!):</p>
<pre><code>entries = 24935502 # number of entries
width = 18 # fixed width of an entry in the file padded with spaces
# at the end of each line
for i, search in enumerate(list): # list contains the list of search keys
left, right = 0, entries-1
key = None
while key != search and left <= right:
mid = (left + right) / 2
fin.seek(mid * width)
key, value = map(int, fin.readline().split())
if search > key:
left = mid + 1
else:
right = mid - 1
if key != search:
value = None # for when search key is not found
search.result = value # store the result of the search
</code></pre>
| 12
|
2009-04-13T15:28:04Z
| 744,296
|
<p>One possible optimization is to do a bit of buffering using the <code>sizehint</code> option in <a href="http://docs.python.org/library/stdtypes.html#file.readlines" rel="nofollow">file.readlines(..)</a>. This allows you to load multiple lines in memory totaling to approximately <code>sizehint</code> bytes.</p>
| 0
|
2009-04-13T15:40:51Z
|
[
"python",
"performance",
"file-io",
"large-files"
] |
Reading Huge File in Python
| 744,256
|
<p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more efficient Python foo to get this down to a reasonable efficiency of a couple of seconds at most.</p>
<pre><code># list contains a sorted list of the keys we need to lookup
# there is a sentinel at the end of list to simplify the code
# we use pointer to iterate through the list of keys
for line in fin:
line = map(int, line.split())
while line[0] == list[pointer].key:
list[pointer].value = line[1]
pointer += 1
while line[0] > list[pointer].key:
pointer += 1
if pointer >= len(list) - 1:
break # end of list; -1 is due to sentinel
</code></pre>
<p>Coded binary search + seek solution (thanks kigurai!):</p>
<pre><code>entries = 24935502 # number of entries
width = 18 # fixed width of an entry in the file padded with spaces
# at the end of each line
for i, search in enumerate(list): # list contains the list of search keys
left, right = 0, entries-1
key = None
while key != search and left <= right:
mid = (left + right) / 2
fin.seek(mid * width)
key, value = map(int, fin.readline().split())
if search > key:
left = mid + 1
else:
right = mid - 1
if key != search:
value = None # for when search key is not found
search.result = value # store the result of the search
</code></pre>
| 12
|
2009-04-13T15:28:04Z
| 744,309
|
<p>Slight optimization of S.Lotts answer:</p>
<pre><code>from collections import defaultdict
keyValues= defaultdict(list)
targetKeys= # some list of keys as strings
for line in fin:
key, value = line.split()
if key in targetKeys:
keyValues[key].append( value )
</code></pre>
<p>Since we're using a dictionary rather than a list, the keys don't have to be numbers. This saves the map() operation and a string to integer conversion for each line. If you want the keys to be numbers, do the conversion a the end, when you only have to do it once for each key, rather than for each of 50 million lines.</p>
| 7
|
2009-04-13T15:46:13Z
|
[
"python",
"performance",
"file-io",
"large-files"
] |
Reading Huge File in Python
| 744,256
|
<p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more efficient Python foo to get this down to a reasonable efficiency of a couple of seconds at most.</p>
<pre><code># list contains a sorted list of the keys we need to lookup
# there is a sentinel at the end of list to simplify the code
# we use pointer to iterate through the list of keys
for line in fin:
line = map(int, line.split())
while line[0] == list[pointer].key:
list[pointer].value = line[1]
pointer += 1
while line[0] > list[pointer].key:
pointer += 1
if pointer >= len(list) - 1:
break # end of list; -1 is due to sentinel
</code></pre>
<p>Coded binary search + seek solution (thanks kigurai!):</p>
<pre><code>entries = 24935502 # number of entries
width = 18 # fixed width of an entry in the file padded with spaces
# at the end of each line
for i, search in enumerate(list): # list contains the list of search keys
left, right = 0, entries-1
key = None
while key != search and left <= right:
mid = (left + right) / 2
fin.seek(mid * width)
key, value = map(int, fin.readline().split())
if search > key:
left = mid + 1
else:
right = mid - 1
if key != search:
value = None # for when search key is not found
search.result = value # store the result of the search
</code></pre>
| 12
|
2009-04-13T15:28:04Z
| 744,332
|
<p>If you have any control over the format of the file, the "sort and binary search" responses are correct. The detail is that this only works with records of a fixed size and offset (well, I should say it only works easily with fixed length records).</p>
<p>With fixed length records, you can easily seek() around the sorted file to find your keys.</p>
| 2
|
2009-04-13T15:53:55Z
|
[
"python",
"performance",
"file-io",
"large-files"
] |
Reading Huge File in Python
| 744,256
|
<p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more efficient Python foo to get this down to a reasonable efficiency of a couple of seconds at most.</p>
<pre><code># list contains a sorted list of the keys we need to lookup
# there is a sentinel at the end of list to simplify the code
# we use pointer to iterate through the list of keys
for line in fin:
line = map(int, line.split())
while line[0] == list[pointer].key:
list[pointer].value = line[1]
pointer += 1
while line[0] > list[pointer].key:
pointer += 1
if pointer >= len(list) - 1:
break # end of list; -1 is due to sentinel
</code></pre>
<p>Coded binary search + seek solution (thanks kigurai!):</p>
<pre><code>entries = 24935502 # number of entries
width = 18 # fixed width of an entry in the file padded with spaces
# at the end of each line
for i, search in enumerate(list): # list contains the list of search keys
left, right = 0, entries-1
key = None
while key != search and left <= right:
mid = (left + right) / 2
fin.seek(mid * width)
key, value = map(int, fin.readline().split())
if search > key:
left = mid + 1
else:
right = mid - 1
if key != search:
value = None # for when search key is not found
search.result = value # store the result of the search
</code></pre>
| 12
|
2009-04-13T15:28:04Z
| 744,342
|
<p>You need to implement binary search using seek()</p>
| 0
|
2009-04-13T15:56:12Z
|
[
"python",
"performance",
"file-io",
"large-files"
] |
Reading Huge File in Python
| 744,256
|
<p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more efficient Python foo to get this down to a reasonable efficiency of a couple of seconds at most.</p>
<pre><code># list contains a sorted list of the keys we need to lookup
# there is a sentinel at the end of list to simplify the code
# we use pointer to iterate through the list of keys
for line in fin:
line = map(int, line.split())
while line[0] == list[pointer].key:
list[pointer].value = line[1]
pointer += 1
while line[0] > list[pointer].key:
pointer += 1
if pointer >= len(list) - 1:
break # end of list; -1 is due to sentinel
</code></pre>
<p>Coded binary search + seek solution (thanks kigurai!):</p>
<pre><code>entries = 24935502 # number of entries
width = 18 # fixed width of an entry in the file padded with spaces
# at the end of each line
for i, search in enumerate(list): # list contains the list of search keys
left, right = 0, entries-1
key = None
while key != search and left <= right:
mid = (left + right) / 2
fin.seek(mid * width)
key, value = map(int, fin.readline().split())
if search > key:
left = mid + 1
else:
right = mid - 1
if key != search:
value = None # for when search key is not found
search.result = value # store the result of the search
</code></pre>
| 12
|
2009-04-13T15:28:04Z
| 744,487
|
<p>Here is a recursive binary search on the text file</p>
<pre><code>import os, stat
class IntegerKeyTextFile(object):
def __init__(self, filename):
self.filename = filename
self.f = open(self.filename, 'r')
self.getStatinfo()
def getStatinfo(self):
self.statinfo = os.stat(self.filename)
self.size = self.statinfo[stat.ST_SIZE]
def parse(self, line):
key, value = line.split()
k = int(key)
v = int(value)
return (k,v)
def __getitem__(self, key):
return self.findKey(key)
def findKey(self, keyToFind, startpoint=0, endpoint=None):
"Recursively search a text file"
if endpoint is None:
endpoint = self.size
currentpoint = (startpoint + endpoint) // 2
while True:
self.f.seek(currentpoint)
if currentpoint <> 0:
# may not start at a line break! Discard.
baddata = self.f.readline()
linestart = self.f.tell()
keyatpoint = self.f.readline()
if not keyatpoint:
# read returned empty - end of file
raise KeyError('key %d not found'%(keyToFind,))
k,v = self.parse(keyatpoint)
if k == keyToFind:
print 'key found at ', linestart, ' with value ', v
return v
if endpoint == startpoint:
raise KeyError('key %d not found'%(keyToFind,))
if k > keyToFind:
return self.findKey(keyToFind, startpoint, currentpoint)
else:
return self.findKey(keyToFind, currentpoint, endpoint)
</code></pre>
<p>A sample text file created in jEdit seems to work: </p>
<pre><code>>>> i = integertext.IntegerKeyTextFile('c:\\sampledata.txt')
>>> i[1]
key found at 0 with value 345
345
</code></pre>
<p>It could definitely be improved by caching found keys and using the cache to determine future starting seek points.</p>
| 2
|
2009-04-13T16:35:18Z
|
[
"python",
"performance",
"file-io",
"large-files"
] |
email whitelist/blacklist in python/django
| 744,308
|
<p>I am writing a django app that keeps track of which email addresses are allowed to post content to a user's account. The user can whitelist and blacklist addresses as they like.</p>
<p>Any addresses that aren't specified can either be handled per message or just default to whitelist or blacklist (again user specified).</p>
<p>Here are the django models I wrote... do you think is a good way to do it? or should I add a whitelist and blacklist field to each user's profile model?</p>
<pre><code>class knownEmail(models.Model):
# The user who set this address' permission, NOT
# the user who the address belongs to...
relatedUser = models.ManyToManyField(User)
email = models.EmailField()
class whiteList(knownEmail):
pass
class blackList(knownEmail):
pass
</code></pre>
<p>Then I could do something like:</p>
<pre><code>def checkPermission(user, emailAddress):
"Check if 'emailAddress' is allowed to post content to 'user's profile"
if whiteList.objects.filter(relatedUser=user, email=emailAddress):
return True
elif blackList.objects.filter(relatedUser=user, email=emailAddress):
return False
else:
return None
</code></pre>
<p>Is there a better way?</p>
| 1
|
2009-04-13T15:46:11Z
| 744,334
|
<p>[Please start All Class Names With Upper Case Letters.]</p>
<p>Your code doesn't make use of your class distinction very well. </p>
<p>Specifically, your classes don't have any different behavior. Since both classes have all the same methods, it isn't clear <em>why</em> these are two different classes in the first place. If they have different methods, then your solution is good.</p>
<p>If, however, they don't have different methods, you might want to look at providing a customized <a href="http://docs.djangoproject.com/en/dev/topics/db/managers/#managers" rel="nofollow">manager</a> for each of the two subsets of <code>KnownEmail</code></p>
<pre><code>class WhiteList( models.Manager ):
def get_query_set( self ):
return super( WhiteList, self ).get_query_set().filter( status='W' )
class BlackList( models.Manager )
def get_query_set( self ):
return super( BlackList, self ).get_query_set().filter( status='B' )
class KnownEmail( models.Model ):
relatedUser = models.ForeignKey(User)
email = models.EmailField()
status = models.CharField( max_length=1, choices=LIST_CHOICES )
objects = models.Manager() # default manager shows all lists
whiteList= WhiteList() # KnownEmail.whiteList.all() is whitelist subset
blackList= BlackList() # KnownEmail.blackList.all() is blackList subset
</code></pre>
| 3
|
2009-04-13T15:54:41Z
|
[
"python",
"django",
"email",
"whitelist",
"blacklist"
] |
email whitelist/blacklist in python/django
| 744,308
|
<p>I am writing a django app that keeps track of which email addresses are allowed to post content to a user's account. The user can whitelist and blacklist addresses as they like.</p>
<p>Any addresses that aren't specified can either be handled per message or just default to whitelist or blacklist (again user specified).</p>
<p>Here are the django models I wrote... do you think is a good way to do it? or should I add a whitelist and blacklist field to each user's profile model?</p>
<pre><code>class knownEmail(models.Model):
# The user who set this address' permission, NOT
# the user who the address belongs to...
relatedUser = models.ManyToManyField(User)
email = models.EmailField()
class whiteList(knownEmail):
pass
class blackList(knownEmail):
pass
</code></pre>
<p>Then I could do something like:</p>
<pre><code>def checkPermission(user, emailAddress):
"Check if 'emailAddress' is allowed to post content to 'user's profile"
if whiteList.objects.filter(relatedUser=user, email=emailAddress):
return True
elif blackList.objects.filter(relatedUser=user, email=emailAddress):
return False
else:
return None
</code></pre>
<p>Is there a better way?</p>
| 1
|
2009-04-13T15:46:11Z
| 745,599
|
<p>I would restructure it so both lists were contained in one model.</p>
<pre><code>class PermissionList(models.Model):
setter = models.ManyToManyField(User)
email = models.EmailField(unique=True) #don't want conflicting results
permission = models.BooleanField()
</code></pre>
<p>Then, your lists would just be:</p>
<pre><code># whitelist
PermissionList.objects.filter(permission=True)
# blacklist
PermissionList.objects.filter(permission=False)
</code></pre>
<p>To check a particular user, you just add a couple functions to the model:</p>
<pre><code>class PermissionList(...):
...
@classmethod
def is_on_whitelist(email):
return PermissionList.objects.filter(email=email, permission=True).count() > 0
@classmethod
def is_on_blacklist(email):
return PermissionList.objects.filter(email=email, permission=False).count() > 0
@classmethod
def has_permission(email):
if PermissionList.is_on_whitelist(email):
return True
if PermissionList.is_on_blacklist(email):
return False
return None
</code></pre>
<p>Having everything in one place is a lot simpler, and you can make more interesting queries with less work.</p>
| 5
|
2009-04-13T22:17:36Z
|
[
"python",
"django",
"email",
"whitelist",
"blacklist"
] |
email whitelist/blacklist in python/django
| 744,308
|
<p>I am writing a django app that keeps track of which email addresses are allowed to post content to a user's account. The user can whitelist and blacklist addresses as they like.</p>
<p>Any addresses that aren't specified can either be handled per message or just default to whitelist or blacklist (again user specified).</p>
<p>Here are the django models I wrote... do you think is a good way to do it? or should I add a whitelist and blacklist field to each user's profile model?</p>
<pre><code>class knownEmail(models.Model):
# The user who set this address' permission, NOT
# the user who the address belongs to...
relatedUser = models.ManyToManyField(User)
email = models.EmailField()
class whiteList(knownEmail):
pass
class blackList(knownEmail):
pass
</code></pre>
<p>Then I could do something like:</p>
<pre><code>def checkPermission(user, emailAddress):
"Check if 'emailAddress' is allowed to post content to 'user's profile"
if whiteList.objects.filter(relatedUser=user, email=emailAddress):
return True
elif blackList.objects.filter(relatedUser=user, email=emailAddress):
return False
else:
return None
</code></pre>
<p>Is there a better way?</p>
| 1
|
2009-04-13T15:46:11Z
| 28,287,010
|
<p>This class compares an email address with a blacklist of email domains. If you preffer you can download this module using <a href="https://pypi.python.org/pypi?:action=display&name=django-email-blacklist&version=1.0.1" rel="nofollow">pip install django-email-blacklist</a>.</p>
<pre><code>from django.conf import settings
import re
class DisposableEmailChecker():
"""
Check if an email is from a disposable
email service
"""
def __init__(self):
self.emails = [line.strip() for line in open(settings.DISPOSABLE_EMAIL_DOMAINS)]
def chunk(self, l, n):
return (l[i:i + n] for i in range(0, len(l), n))
def is_disposable(self, email):
for email_group in self.chunk(self.emails, 20):
regex = "(.*" + ")|(.*".join(email_group) + ")"
if re.match(regex, email):
return True
return False
</code></pre>
| 0
|
2015-02-02T21:22:17Z
|
[
"python",
"django",
"email",
"whitelist",
"blacklist"
] |
Imports in python are static, any solution?
| 744,325
|
<p>foo.py :</p>
<pre><code>i = 10
def fi():
global i
i = 99
</code></pre>
<p>bar.py :</p>
<pre><code>import foo
from foo import i
print i, foo.i
foo.fi()
print i, foo.i
</code></pre>
<p>This is problematic. Why does <code>i</code> not change when <code>foo.i</code> changes?</p>
| 4
|
2009-04-13T15:52:59Z
| 744,343
|
<p>You could call a function instead of referencing a global variable. </p>
| 0
|
2009-04-13T15:56:22Z
|
[
"python"
] |
Imports in python are static, any solution?
| 744,325
|
<p>foo.py :</p>
<pre><code>i = 10
def fi():
global i
i = 99
</code></pre>
<p>bar.py :</p>
<pre><code>import foo
from foo import i
print i, foo.i
foo.fi()
print i, foo.i
</code></pre>
<p>This is problematic. Why does <code>i</code> not change when <code>foo.i</code> changes?</p>
| 4
|
2009-04-13T15:52:59Z
| 744,369
|
<p>What Ross is saying is to restucture foo like so:</p>
<pre><code>_i = 10
def getI():
return _i
def fi():
global _i
_i = 99
</code></pre>
<p>Then you will see it works the way you want:</p>
<pre><code>>>> import foo
>>> print foo.getI()
10
>>> foo.fi()
>>> print foo.getI()
99
</code></pre>
<p>It is also 'better' in the sense that you avoid exporting a global, but still provide read access to it.</p>
| 8
|
2009-04-13T16:05:56Z
|
[
"python"
] |
Imports in python are static, any solution?
| 744,325
|
<p>foo.py :</p>
<pre><code>i = 10
def fi():
global i
i = 99
</code></pre>
<p>bar.py :</p>
<pre><code>import foo
from foo import i
print i, foo.i
foo.fi()
print i, foo.i
</code></pre>
<p>This is problematic. Why does <code>i</code> not change when <code>foo.i</code> changes?</p>
| 4
|
2009-04-13T15:52:59Z
| 744,407
|
<p>What <code>import</code> does in <code>bar.py</code> is set up an identifier called <code>i</code> in the <code>bar.py</code> module namespace that points to the same address as the identifier called <code>i</code> in the <code>foo.py</code> module namespace.</p>
<p>This is an important distinction... <code>bar.i</code> is not pointing to <code>foo.i</code>, but rather to the same space in memory where the object <code>10</code> is held that <code>foo.i</code> happens to point to at the same time. In python, the variable names are not the memory space... they are the identifier that points to a memory space. When you import in bar, you are setting up a local namespace identifier.</p>
<p>Your code behaves as expected until <code>foo.fi()</code> is called, when the identifier <code>i</code> in the foo.py namespace is changed to point to the literal 99, which is an object in memory obviously at a different place than 10. Now the module-level namespace dict for <code>foo</code> has <code>i</code> identifying a different object in memory than the identifier <code>i</code> in bar.py.</p>
<p>Shane and rossfabricant have good suggestions on how to adjust your modules to achieve what you want.</p>
| 7
|
2009-04-13T16:15:33Z
|
[
"python"
] |
Imports in python are static, any solution?
| 744,325
|
<p>foo.py :</p>
<pre><code>i = 10
def fi():
global i
i = 99
</code></pre>
<p>bar.py :</p>
<pre><code>import foo
from foo import i
print i, foo.i
foo.fi()
print i, foo.i
</code></pre>
<p>This is problematic. Why does <code>i</code> not change when <code>foo.i</code> changes?</p>
| 4
|
2009-04-13T15:52:59Z
| 744,615
|
<p><code>i</code> inside <code>foo.py</code> is a <strong>different</strong> <code>i</code> from the one in <code>bar.py</code>. When in <code>bar.py</code> you do:</p>
<pre><code>from foo import i
</code></pre>
<p>That creates a new <code>i</code> in <code>bar.py</code> that <em>refers to the same object</em> as the <code>i</code> in <code>foo.py</code>.</p>
<p>Your problem is: When you call <code>foo.fi()</code> and it does that:</p>
<pre><code>i = 99
</code></pre>
<p>That assignment makes <code>foo.py</code>'s <code>i</code> point to another integer object (<code>99</code>). Integer objects are immutable themselves (thankfully) so it only changes what <code>foo.py</code>'s <code>i</code> is pointing to. Not <code>bar.py</code>'s <code>i</code>. <code>bar.py</code>'s <code>i</code> still points to the old object it was pointing before. (the integer immutable object <code>10</code>)</p>
<p>You can test what I am talking about by placing the following command in <code>bar.py</code>:</p>
<pre><code>print foo.i
</code></pre>
<p>it should print <code>99</code>.</p>
| 3
|
2009-04-13T17:10:17Z
|
[
"python"
] |
Circular (or cyclic) imports in Python
| 744,373
|
<p>What will happen if two modules import each other?</p>
<p>To generalize the problem, what about the cyclic imports in Python?</p>
| 197
|
2009-04-13T16:07:07Z
| 744,403
|
<p>There was a really good discussion on this over at <a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/1d80a1c6db2b867c">comp.lang.python</a> last year. It answers your question pretty thoroughly.</p>
<blockquote>
<p>Imports are pretty straightforward really. Just remember the following:</p>
<p>'import' and 'from xxx import yyy' are executable statements. They execute
when the running program reaches that line.</p>
<p>If a module is not in sys.modules, then an import creates the new module
entry in sys.modules and then executes the code in the module. It does not
return control to the calling module until the execution has completed.</p>
<p>If a module does exist in sys.modules then an import simply returns that
module whether or not it has completed executing. That is the reason why
cyclic imports may return modules which appear to be partly empty.</p>
<p>Finally, the executing script runs in a module named __main__, importing
the script under its own name will create a new module unrelated to
__main__.</p>
<p>Take that lot together and you shouldn't get any surprises when importing
modules. </p>
</blockquote>
| 183
|
2009-04-13T16:15:00Z
|
[
"python",
"circular-dependency",
"cyclic-reference"
] |
Circular (or cyclic) imports in Python
| 744,373
|
<p>What will happen if two modules import each other?</p>
<p>To generalize the problem, what about the cyclic imports in Python?</p>
| 197
|
2009-04-13T16:07:07Z
| 744,410
|
<p>Cyclic imports terminate, but you need to be careful not to use the cyclically-imported modules during module initialization.</p>
<p>Consider the following files:</p>
<p>a.py:</p>
<pre><code>print "a in"
import sys
print "b imported: %s" % ("b" in sys.modules, )
import b
print "a out"
</code></pre>
<p>b.py:</p>
<pre><code>print "b in"
import a
print "b out"
x = 3
</code></pre>
<p>If you execute a.py, you'll get the following:</p>
<pre><code>$ python a.py
a in
b imported: False
b in
a in
b imported: True
a out
b out
a out
</code></pre>
<p>On the second import of b.py (in the second <code>a in</code>), the Python interpreter does not import <code>b</code> again, because it already exists in the module dict.</p>
<p>If you try to access <code>b.x</code> from <code>a</code> during module initialization, you will get an <code>AttributeError</code>.</p>
<p>Append the following line to <code>a.py</code>:</p>
<pre><code>print b.x
</code></pre>
<p>Then, the output is:</p>
<pre><code>$ python a.py
a in
b imported: False
b in
a in
b imported: True
a out
Traceback (most recent call last):
File "a.py", line 4, in <module>
import b
File "/home/shlomme/tmp/x/b.py", line 2, in <module>
import a
File "/home/shlomme/tmp/x/a.py", line 7, in <module>
print b.x
AttributeError: 'module' object has no attribute 'x'
</code></pre>
<p>This is because modules are executed on import and at the time <code>b.x</code> is accessed, the line <code>x = 3</code> has not be executed yet, which will only happen after <code>b out</code>.</p>
| 63
|
2009-04-13T16:16:23Z
|
[
"python",
"circular-dependency",
"cyclic-reference"
] |
Circular (or cyclic) imports in Python
| 744,373
|
<p>What will happen if two modules import each other?</p>
<p>To generalize the problem, what about the cyclic imports in Python?</p>
| 197
|
2009-04-13T16:07:07Z
| 746,067
|
<p>If you do <code>import foo</code> inside <code>bar</code> and <code>import bar</code> inside <code>foo</code>, it will work fine. By the time anything actually runs, both modules will be fully loaded and will have references to each other.</p>
<p>The problem is when instead you do <code>from foo import abc</code> and <code>from bar import xyz</code>. Because now each module requires the other module to already be imported (so that the name we are importing exists) before it can be imported.</p>
| 155
|
2009-04-14T02:03:43Z
|
[
"python",
"circular-dependency",
"cyclic-reference"
] |
Circular (or cyclic) imports in Python
| 744,373
|
<p>What will happen if two modules import each other?</p>
<p>To generalize the problem, what about the cyclic imports in Python?</p>
| 197
|
2009-04-13T16:07:07Z
| 746,655
|
<p>I got an example here that struck me!</p>
<p><strong>foo.py</strong></p>
<pre><code>import bar
class gX(object):
g = 10
</code></pre>
<p><strong>bar.py</strong></p>
<pre><code>from foo import gX
o = gX()
</code></pre>
<p><strong>main.py</strong></p>
<pre><code>import foo
import bar
print "all done"
</code></pre>
<p><strong>At the command line:</strong> $ python main.py</p>
<pre><code>Traceback (most recent call last):
File "m.py", line 1, in <module>
import foo
File "/home/xolve/foo.py", line 1, in <module>
import bar
File "/home/xolve/bar.py", line 1, in <module>
from foo import gX
ImportError: cannot import name gX
</code></pre>
| 3
|
2009-04-14T07:30:51Z
|
[
"python",
"circular-dependency",
"cyclic-reference"
] |
Circular (or cyclic) imports in Python
| 744,373
|
<p>What will happen if two modules import each other?</p>
<p>To generalize the problem, what about the cyclic imports in Python?</p>
| 197
|
2009-04-13T16:07:07Z
| 28,356,950
|
<p>Ok, I think I have a pretty cool solution.
Let's say you have file <code>a</code> and file <code>b</code>.
You have a <code>def</code> or a <code>class</code> in file <code>b</code> that you want to use in module <code>a</code>, but you have something else, either a <code>def</code>, <code>class</code>, or variable from file <code>a</code> that you need in your definition or class in file <code>b</code>.
What you can do is, at the bottom of file <code>a</code>, after calling the function or class in file <code>a</code> that is needed in file <code>b</code>, but before calling the function or class from file <code>b</code> that you need for file <code>a</code>, say <code>import b</code>
Then, and here is the <strong>key part</strong>, in all of the definitions or classes in file <code>b</code> that need the <code>def</code> or <code>class</code> from file <code>a</code> (let's call it <code>CLASS</code>), you say <code>from a import CLASS</code></p>
<p>This works because you can import file <code>b</code> without Python executing any of the import statements in file <code>b</code>, and thus you elude any circular imports.</p>
<p>For example:</p>
<h3>File a:</h3>
<pre><code>class A(object):
def __init__(self, name):
self.name = name
CLASS = A("me")
import b
go = B(6)
go.dostuff
</code></pre>
<h3>File b:</h3>
<pre><code>class B(object):
def __init__(self, number):
self.number = number
def dostuff(self):
from a import CLASS
print "Hello " + CLASS.name + ", " + str(number) + " is an interesting number."
</code></pre>
<p>Voila.</p>
| -3
|
2015-02-06T01:07:27Z
|
[
"python",
"circular-dependency",
"cyclic-reference"
] |
Circular (or cyclic) imports in Python
| 744,373
|
<p>What will happen if two modules import each other?</p>
<p>To generalize the problem, what about the cyclic imports in Python?</p>
| 197
|
2009-04-13T16:07:07Z
| 33,547,682
|
<p>As other answers describe this pattern is acceptable in python:</p>
<pre><code>def dostuff(self):
from foo import bar
...
</code></pre>
<p>Which will avoid the execution of the import statement when the file is imported by other modules. Only if there is a logical circular dependency, this will fail.</p>
<p>Most Circular Imports are not actually logical circular imports but rather raise <code>ImportError</code> errors, because of the way <code>import()</code> evaluates top level statements of the entire file when called.</p>
<p><strong>These <code>ImportErrors</code> can almost always be avoided if you positively want your imports on top</strong>:</p>
<p>Consider this circular import:</p>
<h3>App A</h3>
<pre><code># profiles/serializers.py
from images.serializers import SimplifiedImageSerializer
class SimplifiedProfileSerializer(serializers.Serializer):
name = serializers.CharField()
class ProfileSerializer(SimplifiedProfileSerializer):
recent_images = SimplifiedImageSerializer(many=True)
</code></pre>
<h3>App B</h3>
<pre><code># images/serializers.py
from profiles.serializers import SimplifiedProfileSerializer
class SimplifiedImageSerializer(serializers.Serializer):
title = serializers.CharField()
class ImageSerializer(SimplifiedImageSerializer):
profile = SimplifiedProfileSerializer()
</code></pre>
<p>From David Beazleys excellent talk <a href="https://www.youtube.com/watch?v=0oTh1CXRaQ0">Modules and Packages: Live and Let Die! - PyCon 2015</a>, <code>1:54:00</code>, here is a way to deal with circular imports in python:</p>
<pre><code>try:
from images.serializers import SimplifiedImageSerializer
except ImportError:
import sys
SimplifiedImageSerializer = sys.modules[__package__ + '.SimplifiedImageSerializer']
</code></pre>
<p>This tries to import <code>SimplifiedImageSerializer</code> and if <code>ImportError</code> is raised, because it already is imported, it will pull it from the importcache.</p>
<p><em>PS: You have to read this entire post in David Beazley's voice.</em></p>
| 11
|
2015-11-05T14:51:51Z
|
[
"python",
"circular-dependency",
"cyclic-reference"
] |
Django models - how to filter out duplicate values by PK after the fact?
| 744,424
|
<p>I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable. </p>
<p>Is there a quick and easy way to do this? I'm considering using a dict instead of a list with the id as the key.</p>
| 6
|
2009-04-13T16:20:47Z
| 744,439
|
<p>If the order doesn't matter, use a dict.</p>
| 0
|
2009-04-13T16:24:46Z
|
[
"python",
"django",
"data-structures",
"set",
"unique"
] |
Django models - how to filter out duplicate values by PK after the fact?
| 744,424
|
<p>I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable. </p>
<p>Is there a quick and easy way to do this? I'm considering using a dict instead of a list with the id as the key.</p>
| 6
|
2009-04-13T16:20:47Z
| 744,454
|
<blockquote>
<p>Is there a quick and easy way to do this? I'm considering using a dict instead of a list with the id as the key.</p>
</blockquote>
<p>That's exactly what I would do if you were locked into your current structure of making several queries. Then a simply <code>dictionary.values()</code> will return your list back.</p>
<p>If you have a little more flexibility, why not use <code>Q</code> objects? Instead of actually making the queries, store each query in a <code>Q</code> object and use a bitwise or ("|") to execute a single query. This will achieve your goal and save database hits.</p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects">Django Q objects</a></p>
| 6
|
2009-04-13T16:27:26Z
|
[
"python",
"django",
"data-structures",
"set",
"unique"
] |
Django models - how to filter out duplicate values by PK after the fact?
| 744,424
|
<p>I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable. </p>
<p>Is there a quick and easy way to do this? I'm considering using a dict instead of a list with the id as the key.</p>
| 6
|
2009-04-13T16:20:47Z
| 744,586
|
<p>You can use a set if you add the <code>__hash__</code> function to your model definition so that it returns the id (assuming this doesn't interfere with other hash behaviour you may have in your app):</p>
<pre><code>class MyModel(models.Model):
def __hash__(self):
return self.pk
</code></pre>
| 3
|
2009-04-13T16:58:21Z
|
[
"python",
"django",
"data-structures",
"set",
"unique"
] |
Django models - how to filter out duplicate values by PK after the fact?
| 744,424
|
<p>I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable. </p>
<p>Is there a quick and easy way to do this? I'm considering using a dict instead of a list with the id as the key.</p>
| 6
|
2009-04-13T16:20:47Z
| 744,745
|
<p>Remove "duplicates" depends on how you define "duplicated".</p>
<p>If you want EVERY column (except the PK) to match, that's a pain in the neck -- it's a lot of comparing.</p>
<p>If, on the other hand, you have some "natural key" column (or short set of columns) than you can easily query and remove these.</p>
<pre><code>master = MyModel.objects.get( id=theMasterKey )
dups = MyModel.objects.filter( fld1=master.fld1, fld2=master.fld2 )
dups.all().delete()
</code></pre>
<p>If you can identify some shorter set of key fields for duplicate identification, this works pretty well.</p>
<p><hr /></p>
<p><strong>Edit</strong></p>
<p>If the model objects haven't been saved to the database yet, you can make a dictionary on a tuple of these keys.</p>
<pre><code>unique = {}
...
key = (anObject.fld1,anObject.fld2)
if key not in unique:
unique[key]= anObject
</code></pre>
| 0
|
2009-04-13T17:44:12Z
|
[
"python",
"django",
"data-structures",
"set",
"unique"
] |
Django models - how to filter out duplicate values by PK after the fact?
| 744,424
|
<p>I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable. </p>
<p>Is there a quick and easy way to do this? I'm considering using a dict instead of a list with the id as the key.</p>
| 6
|
2009-04-13T16:20:47Z
| 747,611
|
<p>In general it's better to combine all your queries into a single query if possible. Ie.</p>
<pre><code>q = Model.objects.filter(Q(field1=f1)|Q(field2=f2))
</code></pre>
<p>instead of</p>
<pre><code>q1 = Models.object.filter(field1=f1)
q2 = Models.object.filter(field2=f2)
</code></pre>
<p>If the first query is returning duplicated Models then use distinct()</p>
<pre><code>q = Model.objects.filter(Q(field1=f1)|Q(field2=f2)).distinct()
</code></pre>
<p>If your query really is impossible to execute with a single command, then you'll have to resort to using a dict or other technique recommended in the other answers. It might be helpful if you posted the exact query on SO and we could see if it would be possible to combine into a single query. In my experience, most queries can be done with a single queryset.</p>
| 12
|
2009-04-14T13:40:00Z
|
[
"python",
"django",
"data-structures",
"set",
"unique"
] |
Django models - how to filter out duplicate values by PK after the fact?
| 744,424
|
<p>I build a list of Django model objects by making several queries. Then I want to remove any duplicates, (all of these objects are of the same type with an auto_increment int PK), but I can't use set() because they aren't hashable. </p>
<p>Is there a quick and easy way to do this? I'm considering using a dict instead of a list with the id as the key.</p>
| 6
|
2009-04-13T16:20:47Z
| 2,313,391
|
<p>I use this one:</p>
<pre><code>dict(zip(map(lambda x: x.pk,items),items)).values()
</code></pre>
| 0
|
2010-02-22T19:08:06Z
|
[
"python",
"django",
"data-structures",
"set",
"unique"
] |
Getting TTFB (time till first byte) for an HTTP Request
| 744,532
|
<p>Here is a python script that loads a url and captures response time:</p>
<pre><code>import urllib2
import time
opener = urllib2.build_opener()
request = urllib2.Request('http://example.com')
start = time.time()
resp = opener.open(request)
resp.read()
ttlb = time.time() - start
</code></pre>
<p>Since my timer is wrapped around the whole request/response (including read()), this will give me the TTLB (time to last byte).</p>
<p>I would also like to get the TTFB (time to first byte), but am not sure where to start/stop my timing. Is urllib2 granular enough for me to add TTFB timers? If so, where would they go?</p>
| 5
|
2009-04-13T16:44:06Z
| 744,560
|
<p>Using your current <code>open</code> / <code>read</code> pair there's only one other timing point possible - between the two.</p>
<p>The <code>open()</code> call should be responsible for actually sending the HTTP request, and should (AFAIK) return as soon as that has been sent, ready for your application to actually read the response via <code>read()</code>.</p>
<p>Technically it's probably the case that a long server response would make your application block on the call to <code>read()</code>, in which case this isn't TTFB.</p>
<p>However if the amount of data is small then there won't be much difference between TTFB and TTLB anyway. For a large amount of data, just measure how long it takes for <code>read()</code> to return the first smallest possible chunk.</p>
| 2
|
2009-04-13T16:51:11Z
|
[
"python",
"http",
"urllib2"
] |
Getting TTFB (time till first byte) for an HTTP Request
| 744,532
|
<p>Here is a python script that loads a url and captures response time:</p>
<pre><code>import urllib2
import time
opener = urllib2.build_opener()
request = urllib2.Request('http://example.com')
start = time.time()
resp = opener.open(request)
resp.read()
ttlb = time.time() - start
</code></pre>
<p>Since my timer is wrapped around the whole request/response (including read()), this will give me the TTLB (time to last byte).</p>
<p>I would also like to get the TTFB (time to first byte), but am not sure where to start/stop my timing. Is urllib2 granular enough for me to add TTFB timers? If so, where would they go?</p>
| 5
|
2009-04-13T16:44:06Z
| 744,677
|
<p>By default, the implementation of HTTP opening in urllib2 has no callbacks when read is performed. The OOTB opener for the HTTP protocol is <code>urllib2.HTTPHandler</code>, which uses <code>httplib.HTTPResponse</code> to do the actual reading via a socket.</p>
<p>In theory, you could write your own subclasses of HTTPResponse and HTTPHandler, and install it as the default opener into urllib2 using <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">install_opener</a>. This would be non-trivial, but not excruciatingly so if you basically copy and paste the current HTTPResponse implementation from the standard library and tweak the <code>begin()</code> method in there to perform some processing or callback when reading from the socket begins.</p>
| 1
|
2009-04-13T17:27:51Z
|
[
"python",
"http",
"urllib2"
] |
Getting TTFB (time till first byte) for an HTTP Request
| 744,532
|
<p>Here is a python script that loads a url and captures response time:</p>
<pre><code>import urllib2
import time
opener = urllib2.build_opener()
request = urllib2.Request('http://example.com')
start = time.time()
resp = opener.open(request)
resp.read()
ttlb = time.time() - start
</code></pre>
<p>Since my timer is wrapped around the whole request/response (including read()), this will give me the TTLB (time to last byte).</p>
<p>I would also like to get the TTFB (time to first byte), but am not sure where to start/stop my timing. Is urllib2 granular enough for me to add TTFB timers? If so, where would they go?</p>
| 5
|
2009-04-13T16:44:06Z
| 11,030,969
|
<p>To get a good proximity you have to do read(1). And messure the time.</p>
<p>It works pretty well for me.
The ony thing you should keep in mind: python might load more than one byte on the call of read(1). Depending on it's internal buffers. But i think the most tools will behave alike inaccurate.</p>
<pre><code>import urllib2
import time
opener = urllib2.build_opener()
request = urllib2.Request('http://example.com')
start = time.time()
resp = opener.open(request)
# read one byte
resp.read(1)
ttfb = time.time() - start
# read the rest
resp.read()
ttlb = time.time() - start
</code></pre>
| 1
|
2012-06-14T10:12:53Z
|
[
"python",
"http",
"urllib2"
] |
Getting TTFB (time till first byte) for an HTTP Request
| 744,532
|
<p>Here is a python script that loads a url and captures response time:</p>
<pre><code>import urllib2
import time
opener = urllib2.build_opener()
request = urllib2.Request('http://example.com')
start = time.time()
resp = opener.open(request)
resp.read()
ttlb = time.time() - start
</code></pre>
<p>Since my timer is wrapped around the whole request/response (including read()), this will give me the TTLB (time to last byte).</p>
<p>I would also like to get the TTFB (time to first byte), but am not sure where to start/stop my timing. Is urllib2 granular enough for me to add TTFB timers? If so, where would they go?</p>
| 5
|
2009-04-13T16:44:06Z
| 38,915,617
|
<p>you should use <code>pycurl</code>, not <code>urllib2</code></p>
<ol>
<li><p>install <code>pyCurl</code>:<br>
you can use pip / easy_install, or install it from source.</p>
<p>easy_install pyCurl</p>
<p>maybe you should be a superuser. </p></li>
<li><p>usage: </p>
<pre><code>import pycurl
import sys
import json
WEB_SITES = sys.argv[1]
def main():
c = pycurl.Curl()
c.setopt(pycurl.URL, WEB_SITES) #set url
c.setopt(pycurl.FOLLOWLOCATION, 1)
content = c.perform() #execute
dns_time = c.getinfo(pycurl.NAMELOOKUP_TIME) #DNS time
conn_time = c.getinfo(pycurl.CONNECT_TIME) #TCP/IP 3-way handshaking time
starttransfer_time = c.getinfo(pycurl.STARTTRANSFER_TIME) #time-to-first-byte time
total_time = c.getinfo(pycurl.TOTAL_TIME) #last requst time
c.close()
data = json.dumps({'dns_time':dns_time,
'conn_time':conn_time,
'starttransfer_time':starttransfer_time,
'total_time':total_time})
return data
</code></pre>
<p>if <strong>name</strong> == "<strong>main</strong>":<br>
print main()</p></li>
</ol>
| 1
|
2016-08-12T10:21:47Z
|
[
"python",
"http",
"urllib2"
] |
Calling unknown Python functions
| 744,626
|
<p>This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.</p>
<p>How do I call a function from a string, i.e.</p>
<pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
</code></pre>
| 6
|
2009-04-13T17:12:47Z
| 744,632
|
<pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
eval(f+'()')
</code></pre>
<p><em>Edited to add:</em></p>
<p>Yes, eval() generally is a bad idea, but this is what the OP was looking for.</p>
| 2
|
2009-04-13T17:14:58Z
|
[
"python"
] |
Calling unknown Python functions
| 744,626
|
<p>This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.</p>
<p>How do I call a function from a string, i.e.</p>
<pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
</code></pre>
| 6
|
2009-04-13T17:12:47Z
| 744,634
|
<p>how do you not know the name of the function to call? Store the functions instead of the name:</p>
<pre><code>functions_to_call = [int, str, float]
value = 33.5
for function in functions_to_call:
print "calling", function
print "result:", function(value)
</code></pre>
| 15
|
2009-04-13T17:15:39Z
|
[
"python"
] |
Calling unknown Python functions
| 744,626
|
<p>This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.</p>
<p>How do I call a function from a string, i.e.</p>
<pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
</code></pre>
| 6
|
2009-04-13T17:12:47Z
| 744,635
|
<p>See the <a href="http://docs.python.org/library/functions.html" rel="nofollow">eval and compile</a> functions.</p>
<blockquote>
<p>This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the kind argument, eval()âs return value will be None.</p>
</blockquote>
| 1
|
2009-04-13T17:16:03Z
|
[
"python"
] |
Calling unknown Python functions
| 744,626
|
<p>This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.</p>
<p>How do I call a function from a string, i.e.</p>
<pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
</code></pre>
| 6
|
2009-04-13T17:12:47Z
| 744,647
|
<p>Something like that...when i was looking at function pointers in python..</p>
<pre><code>def myfunc(x):
print x
dict = {
"myfunc": myfunc
}
dict["myfunc"]("hello")
func = dict.get("myfunc")
if callable(func):
func(10)
</code></pre>
| 8
|
2009-04-13T17:17:50Z
|
[
"python"
] |
Calling unknown Python functions
| 744,626
|
<p>This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.</p>
<p>How do I call a function from a string, i.e.</p>
<pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
</code></pre>
| 6
|
2009-04-13T17:12:47Z
| 744,686
|
<p>You can use the python builtin locals() to get local declarations, eg:</p>
<pre><code>def f():
print "Hello, world"
def g():
print "Goodbye, world"
for fname in ["f", "g"]:
fn = locals()[fname]
print "Calling %s" % (fname)
fn()
</code></pre>
<p>You can use the "imp" module to load functions from user-specified python files which gives you a bit more flexibility.</p>
<p>Using locals() makes sure you can't call generic python, whereas with eval, you could end up with the user setting your string to something untoward like:</p>
<pre><code>f = 'open("/etc/passwd").readlines'
print eval(f+"()")
</code></pre>
<p>or similar and end up with your programming doing things you don't expect to be possible. Using similar tricks with locals() and dicts in general will just give attackers KeyErrors.</p>
| 19
|
2009-04-13T17:31:15Z
|
[
"python"
] |
Calling unknown Python functions
| 744,626
|
<p>This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.</p>
<p>How do I call a function from a string, i.e.</p>
<pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
</code></pre>
| 6
|
2009-04-13T17:12:47Z
| 744,687
|
<p>Have a look at the getattr function:</p>
<p><a href="http://docs.python.org/library/functions.html?highlight=getattr#getattr" rel="nofollow">http://docs.python.org/library/functions.html?highlight=getattr#getattr</a></p>
<pre><code>import sys
functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
getattr(sys.modules[__name__], f)()
</code></pre>
| 6
|
2009-04-13T17:31:22Z
|
[
"python"
] |
Calling unknown Python functions
| 744,626
|
<p>This was the best name I could come up with for the topic and none of my searches yielded information relevant to the question.</p>
<p>How do I call a function from a string, i.e.</p>
<pre><code>functions_to_call = ["func_1", "func_2", "func_3"]
for f in functions_to_call:
call f
</code></pre>
| 6
|
2009-04-13T17:12:47Z
| 748,002
|
<p>Don't use eval! It's almost never required, functions in python are just attributes like everything else, and are accessible either using <code>getattr</code> on a class, or via <code>locals()</code>:</p>
<pre><code>>>> print locals()
{'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__name__': '__main__',
'func_1': <function func_1 at 0x74bf0>,
'func_2': <function func_2 at 0x74c30>,
'func_3': <function func_3 at 0x74b70>,
}
</code></pre>
<p>Since that's a dictionary, you can get the functions via the dict-keys <code>func_1</code>, <code>func_2</code> and <code>func_3</code>:</p>
<pre><code>>>> f1 = locals()['func_1']
>>> f1
<function func_1 at 0x74bf0>
>>> f1()
one
</code></pre>
<p>So, the solution without resorting to eval:</p>
<pre><code>>>> def func_1():
... print "one"
...
>>> def func_2():
... print "two"
...
>>> def func_3():
... print "three"
...
>>> functions_to_call = ["func_1", "func_2", "func_3"]
>>> for fname in functions_to_call:
... cur_func = locals()[fname]
... cur_func()
...
one
two
three
</code></pre>
| 1
|
2009-04-14T14:56:09Z
|
[
"python"
] |
Google App Engine--Dynamically created templates
| 744,828
|
<p>I'm trying to build an a simple CRUD admin section of my application. Basically, for a given Model, I want to have a template loop through the model's attributes into a simple table (once I do this, I can actually implement the CRUD part). A possible way to accomplish this is to dynamically generate a template with all the necessary template tags specific to that model.</p>
<p>Pseudocode:</p>
<pre><code>def generate_tamplate(model):
template.write("<table border='1'>")
template.write("<tr>")
for attribute in model:
template.write("<td>%s</td>" % attribute)
template.write("</tr>")
template.write("<tr>")
for attribute in model:
template.write("<td>{{ %s.%s }}</td>" % model.attribute)
template.write("</tr>")
template.write("</table>")
</code></pre>
<p>Generating the proper text should not be difficult. I can follow my pseudocode model and do it Python. Two things im wondering:
1) Can I do this instead using Django's templating language? that is, use a template to generate a template
2) Once I generate the text, how can I wrote that to a file that webapp's template loader can access?</p>
<p>I remember a while back seeing something about loading template from the database. Is this possible with GAE?</p>
<p>THANKS!</p>
| 0
|
2009-04-13T18:05:52Z
| 745,809
|
<p>I saw this open source project a while back:
<a href="http://code.google.com/p/gae-django-dbtemplates/" rel="nofollow">http://code.google.com/p/gae-django-dbtemplates/</a></p>
<p>Using a template to generate a template should be fine. Just render the template to a string. Here some code i use so i can stick some xml into memecache</p>
<pre><code>path = os.path.join(os.path.dirname(__file__), 'line_chart.xml')
xml = template.render(path, template_values)
</code></pre>
<p>You can easily do something very similar and stick the result in the datastore.</p>
| 1
|
2009-04-13T23:40:59Z
|
[
"python",
"google-app-engine",
"templates",
"django-templates"
] |
Google App Engine--Dynamically created templates
| 744,828
|
<p>I'm trying to build an a simple CRUD admin section of my application. Basically, for a given Model, I want to have a template loop through the model's attributes into a simple table (once I do this, I can actually implement the CRUD part). A possible way to accomplish this is to dynamically generate a template with all the necessary template tags specific to that model.</p>
<p>Pseudocode:</p>
<pre><code>def generate_tamplate(model):
template.write("<table border='1'>")
template.write("<tr>")
for attribute in model:
template.write("<td>%s</td>" % attribute)
template.write("</tr>")
template.write("<tr>")
for attribute in model:
template.write("<td>{{ %s.%s }}</td>" % model.attribute)
template.write("</tr>")
template.write("</table>")
</code></pre>
<p>Generating the proper text should not be difficult. I can follow my pseudocode model and do it Python. Two things im wondering:
1) Can I do this instead using Django's templating language? that is, use a template to generate a template
2) Once I generate the text, how can I wrote that to a file that webapp's template loader can access?</p>
<p>I remember a while back seeing something about loading template from the database. Is this possible with GAE?</p>
<p>THANKS!</p>
| 0
|
2009-04-13T18:05:52Z
| 747,519
|
<p>Yes, instead of doing <code>template.writes</code>, you can generate the next template - since <code>template.render(...)</code> just returns text. You can then store the text returned and put it into the DataStore, then retrieve it later and call <code>.render(Context(...))</code> on it to return the html you want to generate. </p>
<p>You cannot write the generated template to a file - as AppEngine applications do not have write access to the filesystem, only read access. </p>
<p>If you change your '<code>generate_tamplate</code>' function to use a template, the pseudocode could look like this:</p>
<pre><code>from google.appengine.ext.webapp import template
def generate_tamplate(model):
t = template.render(path_to_template1.html, Context({'model':model}))
DataStoreTemplate(template=t, name=model.name).put()
''' Later, when you want to generate your page for that model '''
def generate_page(model):
t = DataStoreTemplate.all().filter("name =",model.name).get().template
htmlresult = t.render(Context({'model':model}))
return htmlresult
</code></pre>
| 1
|
2009-04-14T13:19:06Z
|
[
"python",
"google-app-engine",
"templates",
"django-templates"
] |
Google App Engine--Dynamically created templates
| 744,828
|
<p>I'm trying to build an a simple CRUD admin section of my application. Basically, for a given Model, I want to have a template loop through the model's attributes into a simple table (once I do this, I can actually implement the CRUD part). A possible way to accomplish this is to dynamically generate a template with all the necessary template tags specific to that model.</p>
<p>Pseudocode:</p>
<pre><code>def generate_tamplate(model):
template.write("<table border='1'>")
template.write("<tr>")
for attribute in model:
template.write("<td>%s</td>" % attribute)
template.write("</tr>")
template.write("<tr>")
for attribute in model:
template.write("<td>{{ %s.%s }}</td>" % model.attribute)
template.write("</tr>")
template.write("</table>")
</code></pre>
<p>Generating the proper text should not be difficult. I can follow my pseudocode model and do it Python. Two things im wondering:
1) Can I do this instead using Django's templating language? that is, use a template to generate a template
2) Once I generate the text, how can I wrote that to a file that webapp's template loader can access?</p>
<p>I remember a while back seeing something about loading template from the database. Is this possible with GAE?</p>
<p>THANKS!</p>
| 0
|
2009-04-13T18:05:52Z
| 872,022
|
<p>Other option, that in my opinion simplifies writing apps for GAE a lot, is using user other templating language, like <a href="http://www.makotemplates.org/" rel="nofollow">Mako</a>, that allows you to embed Python code in the template, thus no fiddling required.
You would pass model data to the template (as simple as <code>template.render(template_file, model=model</code>), and the template would look something like this:</p>
<pre><code><table border='1'>
<tr>
% for attribute in model:
<td>${attribute}</td>
% endfor
</tr>
<tr>
% for attribute in model:
<td>${model.attribute}</td>
% endfor
</tr>
</table>
</code></pre>
<p>I followed <a href="http://blog.pansapiens.com/2008/06/24/mako-templates-in-google-app-engine-seems-to-work-for-me/" rel="nofollow">this googled blog entry</a> to get Mako in my app - it was quite simple and works like a charm.</p>
| 0
|
2009-05-16T09:08:46Z
|
[
"python",
"google-app-engine",
"templates",
"django-templates"
] |
Do Python regular expressions allow embedded options?
| 744,885
|
<p>In particular, I'd like to know if I can specify an embedded option in the pattern string that will enable multiline mode. That is, typically with Python regular expressions multiline mode is enabled like this:</p>
<pre><code>pattern = re.compile(r'foo', re.MULTILINE)
</code></pre>
<p>I'd like a way to get multiline matching by specifying it in the pattern string, rather than using the re.MULTILINE option. You can do this in Java with the embedded (?m) expression. e.g.,</p>
<pre><code>pattern = re.compile(r'(?m)foo')
</code></pre>
<p>Is this possible in Python, or am I required to use the re.M option? And in general, is there a good reference for embedded pattern options in Python?</p>
| 4
|
2009-04-13T18:25:02Z
| 744,895
|
<p>yes.</p>
<p>From the <a href="http://docs.python.org/library/re.html" rel="nofollow">docs</a>:</p>
<blockquote>
<p><strong><code>(?iLmsux)</code></strong> (One or more letters from the set 'i',
'L', 'm', 's', 'u', 'x'.) </p>
<p>The group
matches the empty string; the letters
set the corresponding flags: <a href="http://docs.python.org/library/re.html#re.I" rel="nofollow"><code>re.I</code></a>
(ignore case), <a href="http://docs.python.org/library/re.html#re.L" rel="nofollow"><code>re.L</code></a> (locale
dependent), <a href="http://docs.python.org/library/re.html#re.M" rel="nofollow"><code>re.M</code></a> (multi-line), <a href="http://docs.python.org/library/re.html#re.S" rel="nofollow"><code>re.S</code></a>
(dot matches all), <a href="http://docs.python.org/library/re.html#re.U" rel="nofollow"><code>re.U</code></a> (Unicode
dependent), and <a href="http://docs.python.org/library/re.html#re.X" rel="nofollow"><code>re.X</code></a> (verbose), for
the entire regular expression. (The
flags are described in <a href="http://docs.python.org/library/re.html#contents-of-module-re" rel="nofollow">Module
Contents</a>.)</p>
<p><strong>This is useful if you wish
to include the flags as part of the
regular expression, instead of passing
a flag argument to the <code>compile()</code>
function.</strong></p>
<p>Note that the <code>(?x)</code> flag changes how
the expression is parsed. It should be
used first in the expression string,
or after one or more whitespace
characters. If there are
non-whitespace characters before the
flag, the results are undefined.</p>
</blockquote>
| 6
|
2009-04-13T18:28:37Z
|
[
"python",
"regex"
] |
adding comments to pot files automatically
| 744,894
|
<p>I want to pull certain comments from my py files that give context to translations, rather than manually editing the .pot file basically i want to go from this python file:</p>
<pre><code># For Translators: some useful info about the sentence below
_("Some string blah blah")
</code></pre>
<p>to this pot file:</p>
<pre><code># For Translators: some useful info about the sentence below
#: something.py:1
msgid "Some string blah blah"
msgstr ""
</code></pre>
| 0
|
2009-04-13T18:27:22Z
| 748,267
|
<p>I was going to suggest the <code>compiler</code> module, but it ignores comments:</p>
<p>f.py:</p>
<pre><code># For Translators: some useful info about the sentence below
_("Some string blah blah")
</code></pre>
<p>..and the compiler module:</p>
<pre><code>>>> import compiler
>>> m = compiler.parseFile("f.py")
>>> m
Module(None, Stmt([Discard(CallFunc(Name('_'), [Const('Some string blah blah')], None, None))]))
</code></pre>
<p>The <a href="http://www.python.org/doc/2.5.2/lib/module-compiler.ast.html" rel="nofollow">AST</a> module in Python 2.6 seems to do the same.</p>
<p>Not sure if it's possible, but if you use triple-quoted strings instead..</p>
<pre><code>"""For Translators: some useful info about the sentence below"""
_("Some string blah blah")
</code></pre>
<p>..you can reliably parse the Python file with the compiler module:</p>
<pre><code>>>> m = compiler.parseFile("f.py")
>>> m
Module('For Translators: some useful info about the sentence below', Stmt([Discard(CallFunc(Name('_'), [Const('Some string blah blah')], None, None))]))
</code></pre>
<p>I made an attempt at writing a mode complete script to extract docstrings - it's incomplete, but seems to grab most docstrings: <a href="http://pastie.org/446156" rel="nofollow">http://pastie.org/446156</a> (or on <a href="http://github.com/dbr/so%5Fscripts/tree/0bd66a21695a390cfa45f9ee26d7bed4eac10e5c/parse%5Fpy" rel="nofollow">github.com/dbr/so_scripts</a>)</p>
<p>The other, much simpler, option would be to use regular expressions, for example:</p>
<pre><code>f = """# For Translators: some useful info about the sentence below
_("Some string blah blah")
""".split("\n")
import re
for i, line in enumerate(f):
m = re.findall("\S*# (For Translators: .*)$", line)
if len(m) > 0 and i != len(f):
print "Line Number:", i+1
print "Message:", m
print "Line:", f[i + 1]
</code></pre>
<p>..outputs:</p>
<pre><code>Line Number: 1
Message: ['For Translators: some useful info about the sentence below']
Line: _("Some string blah blah")
</code></pre>
<p>Not sure how the <code>.pot</code> file is generated, so I can't be any help at-all with that part..</p>
| 1
|
2009-04-14T16:00:27Z
|
[
"python",
"localization",
"internationalization"
] |
adding comments to pot files automatically
| 744,894
|
<p>I want to pull certain comments from my py files that give context to translations, rather than manually editing the .pot file basically i want to go from this python file:</p>
<pre><code># For Translators: some useful info about the sentence below
_("Some string blah blah")
</code></pre>
<p>to this pot file:</p>
<pre><code># For Translators: some useful info about the sentence below
#: something.py:1
msgid "Some string blah blah"
msgstr ""
</code></pre>
| 0
|
2009-04-13T18:27:22Z
| 748,543
|
<p>After much pissing about I found the best way to do this:</p>
<pre><code>#. Translators:
# Blah blah blah
_("String")
</code></pre>
<p>Then search for comments with a . like so:</p>
<pre><code>xgettext --language=Python --keyword=_ --add-comments=. --output=test.pot *.py
</code></pre>
| 2
|
2009-04-14T17:15:16Z
|
[
"python",
"localization",
"internationalization"
] |
Python/Django Modeling Question
| 744,921
|
<p>What is the best way to have many children records pointing to one parent record in the same model/table in Django?</p>
<p>Is this implementation correct?:</p>
<pre><code>class TABLE(models.Model):
id = models.AutoField(primary_key=True)
parent = models.ForeignKey("TABLE", unique=False)
</code></pre>
| 1
|
2009-04-13T18:36:36Z
| 744,936
|
<p>Django has a special syntax for ForeignKey for self-joins:</p>
<pre><code>class TABLE(models.Model):
id = models.AutoField(primary_key=True)
parent = models.ForeignKey('self')
</code></pre>
<p><a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey" rel="nofollow">Source</a> (second paragraph)</p>
| 10
|
2009-04-13T18:40:42Z
|
[
"python",
"database",
"django",
"model"
] |
Python/Django Modeling Question
| 744,921
|
<p>What is the best way to have many children records pointing to one parent record in the same model/table in Django?</p>
<p>Is this implementation correct?:</p>
<pre><code>class TABLE(models.Model):
id = models.AutoField(primary_key=True)
parent = models.ForeignKey("TABLE", unique=False)
</code></pre>
| 1
|
2009-04-13T18:36:36Z
| 744,949
|
<p>Two things:</p>
<p>First, you need to allow the possibility of a null value for <code>parent</code>, otherwise your <code>TABLE</code> tree can have no root.</p>
<p>Second, you need to worry about the possibility of "I'm my own grandpa." For a lively discussion, see <a href="http://stackoverflow.com/questions/401118/foreignkey-form-restrictions-in-django">here</a>.</p>
| 2
|
2009-04-13T18:45:15Z
|
[
"python",
"database",
"django",
"model"
] |
Create function through MySQLdb
| 745,538
|
<p>How can I define a multi-statement function or procedure in using the MySQLdb lib in python?</p>
<p>Example:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect(db='service')
c = db.cursor()
c.execute("""DELIMITER //
CREATE FUNCTION trivial_func (radius float)
RETURNS FLOAT
BEGIN
IF radius > 1 THEN
RETURN 0.0;
ELSE
RETURN 1.0;
END IF;
END //
DELIMITER ;""")
</code></pre>
<p>Which creates the following traceback:</p>
<pre><code>Traceback (most recent call last):
File "proof.py", line 21, in <module>
DELIMITER ;""")
File "build/bdist.macosx-10.5-i386/egg/MySQLdb/cursors.py", line 173, in execute
File "build/bdist.macosx-10.5-i386/egg/MySQLdb/connections.py", line 35, in defaulterrorhandler
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER //\nCREATE FUNCTION trivial_func (radius float) \n RETURNS FLOAT\n\n ' at line 1")
</code></pre>
<p>If I copy the same SQL directly into a mysql shell client, it works as expected</p>
| 10
|
2009-04-13T21:54:10Z
| 745,575
|
<p>The <code>DELIMITER</code> command is a MySQL shell client builtin, and it's recognized only by that program (and MySQL Query Browser). It's not necessary to use <code>DELIMITER</code> if you execute SQL statements directly through an API.</p>
<p>The purpose of <code>DELIMITER</code> is to help you avoid ambiguity about the termination of the <code>CREATE FUNCTION</code> statement, when the statement itself can contain semicolon characters. This is important in the shell client, where by default a semicolon terminates an SQL statement. You need to set the statement terminator to some other character in order to submit the body of a function (or trigger or procedure).</p>
<pre><code>CREATE FUNCTION trivial_func (radius float)
RETURNS FLOAT
BEGIN
IF radius > 1 THEN
RETURN 0.0; <-- does this semicolon terminate RETURN or CREATE FUNCTION?
ELSE
RETURN 1.0;
END IF;
END
</code></pre>
<p>Since the API typically allows you to submit one SQL statement at a time, there's no ambiguity -- the interface knows that any semicolons inside the body of your function definition don't terminate the whole <code>CREATE FUNCTION</code> statement. So there's no need to change the statement terminator with <code>DELIMITER</code>.</p>
| 15
|
2009-04-13T22:10:30Z
|
[
"python",
"mysql"
] |
Create function through MySQLdb
| 745,538
|
<p>How can I define a multi-statement function or procedure in using the MySQLdb lib in python?</p>
<p>Example:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect(db='service')
c = db.cursor()
c.execute("""DELIMITER //
CREATE FUNCTION trivial_func (radius float)
RETURNS FLOAT
BEGIN
IF radius > 1 THEN
RETURN 0.0;
ELSE
RETURN 1.0;
END IF;
END //
DELIMITER ;""")
</code></pre>
<p>Which creates the following traceback:</p>
<pre><code>Traceback (most recent call last):
File "proof.py", line 21, in <module>
DELIMITER ;""")
File "build/bdist.macosx-10.5-i386/egg/MySQLdb/cursors.py", line 173, in execute
File "build/bdist.macosx-10.5-i386/egg/MySQLdb/connections.py", line 35, in defaulterrorhandler
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER //\nCREATE FUNCTION trivial_func (radius float) \n RETURNS FLOAT\n\n ' at line 1")
</code></pre>
<p>If I copy the same SQL directly into a mysql shell client, it works as expected</p>
| 10
|
2009-04-13T21:54:10Z
| 16,950,944
|
<p>To add to the answer by Bill Karwin, the following python code sample can be used to properly execute a string where DELIMITER is used, such as a database creation script.</p>
<pre><code>import MySQLdb
db = MySQLdb.connect(db='service')
cursor = db.cursor()
dbString = """DELIMITER //
CREATE FUNCTION trivial_func (radius float)
RETURNS FLOAT
BEGIN
IF radius > 1 THEN
RETURN 0.0;
ELSE
RETURN 1.0;
END IF;
END //
DELIMITER ;"""
# Find special delimiters
delimiters = re.compile('DELIMITER *(\S*)',re.I)
result = delimiters.split(dbString)
# Insert default delimiter and separate delimiters and sql
result.insert(0,';')
delimiter = result[0::2]
section = result[1::2]
# Split queries on delimiters and execute
for i in range(len(delimiter)):
queries = section[i].split(delimiter[i])
for query in queries:
if not query.strip():
continue
cursor.execute(query)
</code></pre>
<p>This will execute one delimited statement at a time, changing delimiters when needed.</p>
| 3
|
2013-06-05T22:27:33Z
|
[
"python",
"mysql"
] |
Create function through MySQLdb
| 745,538
|
<p>How can I define a multi-statement function or procedure in using the MySQLdb lib in python?</p>
<p>Example:</p>
<pre><code>import MySQLdb
db = MySQLdb.connect(db='service')
c = db.cursor()
c.execute("""DELIMITER //
CREATE FUNCTION trivial_func (radius float)
RETURNS FLOAT
BEGIN
IF radius > 1 THEN
RETURN 0.0;
ELSE
RETURN 1.0;
END IF;
END //
DELIMITER ;""")
</code></pre>
<p>Which creates the following traceback:</p>
<pre><code>Traceback (most recent call last):
File "proof.py", line 21, in <module>
DELIMITER ;""")
File "build/bdist.macosx-10.5-i386/egg/MySQLdb/cursors.py", line 173, in execute
File "build/bdist.macosx-10.5-i386/egg/MySQLdb/connections.py", line 35, in defaulterrorhandler
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER //\nCREATE FUNCTION trivial_func (radius float) \n RETURNS FLOAT\n\n ' at line 1")
</code></pre>
<p>If I copy the same SQL directly into a mysql shell client, it works as expected</p>
| 10
|
2009-04-13T21:54:10Z
| 28,368,193
|
<p>Based on the comment from @AaronS. This script will read in an SQL file, split it into discrete SQL commands and cope with whatever delimiters it finds.</p>
<pre><code> queries = []
delimiter = ';'
query = ''
with open('import.sql', 'r') as f:
for line in f.readlines():
line = line.strip()
if line.startswith('DELIMITER'):
delimiter = line[10:]
else:
query += line+'\n'
if line.endswith(delimiter):
# Get rid of the delimiter, remove any blank lines and add this query to our list
queries.append(query.strip().strip(delimiter))
query = ''
for query in queries:
if not query.strip():
continue
cursor.execute(query)
cursor.close()
</code></pre>
| 0
|
2015-02-06T14:39:21Z
|
[
"python",
"mysql"
] |
semantic markup for Python's difflib.HtmlDiff
| 745,600
|
<p>It appears Python's <code>difflib.HtmlDiff</code>, rather than using <code>INS</code> and <code>DEL</code>, uses <code>SPAN</code> elements with custom classes:</p>
<pre><code>python -c 'import difflib; txt1 = "lorem ipsum\ndolor sit amet".splitlines(); txt2 = "lorem foo isum\ndolor amet".splitlines(); d = difflib.HtmlDiff(); print d.make_table(txt1, txt2)'
</code></pre>
<p>Before I go about fixing this myself, has anyone looked into this already?
Is there perhaps a valid reason for not using POSH?
(Google wasn't a big help here... )</p>
| 1
|
2009-04-13T22:17:39Z
| 831,443
|
<p>The python bug tracker is here: <a href="http://bugs.python.org/" rel="nofollow">http://bugs.python.org/</a></p>
<p>There's no open bug on this issue, which I guess is because most people would not care what sort of html it is as long as it works. If it's important to you, file a bug and submit a patch.</p>
| 2
|
2009-05-06T19:56:07Z
|
[
"python",
"diff",
"semantics"
] |
semantic markup for Python's difflib.HtmlDiff
| 745,600
|
<p>It appears Python's <code>difflib.HtmlDiff</code>, rather than using <code>INS</code> and <code>DEL</code>, uses <code>SPAN</code> elements with custom classes:</p>
<pre><code>python -c 'import difflib; txt1 = "lorem ipsum\ndolor sit amet".splitlines(); txt2 = "lorem foo isum\ndolor amet".splitlines(); d = difflib.HtmlDiff(); print d.make_table(txt1, txt2)'
</code></pre>
<p>Before I go about fixing this myself, has anyone looked into this already?
Is there perhaps a valid reason for not using POSH?
(Google wasn't a big help here... )</p>
| 1
|
2009-04-13T22:17:39Z
| 1,976,803
|
<p><a href="http://www.aaronsw.com/2002/diff/" rel="nofollow">This script</a> by Aaron Swartz uses difflib to output <code>ins</code>/<code>del</code>.</p>
| 3
|
2009-12-29T20:34:10Z
|
[
"python",
"diff",
"semantics"
] |
Is Python interpreted (like Javascript or PHP)?
| 745,743
|
<p>Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)?</p>
| 28
|
2009-04-13T23:15:37Z
| 745,745
|
<p>Yes, Python is interpreted, but you can also run them as long-running applications.</p>
| 1
|
2009-04-13T23:16:19Z
|
[
"python"
] |
Is Python interpreted (like Javascript or PHP)?
| 745,743
|
<p>Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)?</p>
| 28
|
2009-04-13T23:15:37Z
| 745,749
|
<p>There's multiple questions here:</p>
<ol>
<li>No, Python is not interpreted. The standard implementation compiles to bytecode, and then executes in a virtual machine. Many modern JavaScript engines also do this.</li>
<li>Regardless of implementation (interpreter, VM, machine code), anything you want can run in the background. You can run shell scripts in the background, if you want.</li>
</ol>
| 47
|
2009-04-13T23:17:31Z
|
[
"python"
] |
Is Python interpreted (like Javascript or PHP)?
| 745,743
|
<p>Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)?</p>
| 28
|
2009-04-13T23:15:37Z
| 745,751
|
<p>Python is an interpreted language but it is the bytecode which is interpreted at run time. There are also many tools out there that can assist you in making your programs run as a windows service / UNIX daemon.</p>
| 2
|
2009-04-13T23:19:12Z
|
[
"python"
] |
Is Python interpreted (like Javascript or PHP)?
| 745,743
|
<p>Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)?</p>
| 28
|
2009-04-13T23:15:37Z
| 745,752
|
<p>Yes, it's interpreted, its main implementation compiles bytecode first and then runs it though (kind of if you took a java source and the JVM compiled it before running it). Still, you can run your application in background. Actually, you can run pretty much anything in background.</p>
| 1
|
2009-04-13T23:20:23Z
|
[
"python"
] |
Is Python interpreted (like Javascript or PHP)?
| 745,743
|
<p>Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)?</p>
| 28
|
2009-04-13T23:15:37Z
| 745,789
|
<p>Technically, Python is compiled to bytecode and then interpreted in a <a href="http://en.wikipedia.org/wiki/Virtual_machine">virtual machine</a>. If the Python compiler is able to write out the bytecode into a .pyc file, it will (usually) do so.</p>
<p>On the other hand, there's no explicit compilation step in Python as there is with Java or C. From the point of view of the developer, it looks like Python is just interpreting the .py file directly. Plus, Python offers an interactive prompt where you can type Python statements and have them executed immediately. So the workflow in Python is much more similar to that of an interpreted language than that of a compiled language. To me (and a lot of other developers, I suppose), that distinction of workflow is more important than whether there's an intermediate bytecode step or not.</p>
| 19
|
2009-04-13T23:30:23Z
|
[
"python"
] |
Is Python interpreted (like Javascript or PHP)?
| 745,743
|
<p>Is Python strictly interpreted at run time, or can it be used to develop programs that run as background applications (like a Java app or C program)?</p>
| 28
|
2009-04-13T23:15:37Z
| 749,218
|
<p>As the varied responses will tell you, the line between interpreted and compiled is no longer as clear as it was when such terms were coined. In fact, it's also something of a mistake to consider <em>languages</em> as being either interpreted or compiled, as different <em>implementations</em> of languages may do different things. These days you can find both <a href="http://root.cern.ch/drupal/content/cint">C interpreters</a> and <a href="https://developer.mozilla.org/en/Rhino_JavaScript_Compiler">Javascript compilers</a>.</p>
<p>Even when looking at an implementation, things still aren't clear-cut. There are layers of interpretation. Here are a few of the gradations between interpreted and compiled:</p>
<ol>
<li><p>Pure interpretation. Pretty much what it says on the tin. Read a line of source and immediately do what it says. This isn't actually done by many production languages - pretty much just things like shell scripts.</p></li>
<li><p><a href="http://en.wikipedia.org/wiki/Tokenisation">Tokenisation</a> + interpretation. A trivial optimisation on the above. Rather than interpret each line from scratch, it's first tokenised (that is, rather than seeing a string like "print 52 + x", it's translated into a stream of tokens (eg. <code>[PRINT_STATEMENT, INTEGER(52), PLUS_SIGN, IDENTIFIER('x')]</code> ) to avoid repeatedly performing that state of interpretation. Many versions of basic worked this way.</p></li>
<li><p><a href="http://en.wikipedia.org/wiki/Bytecode">Bytecode</a> compilation. This is the approach taken by languages like Java and C# (though see below). The code is transformed into instructions for a "virtual machine". These instructions are then interpreted. This is also the approach taken by python (or at least cpython, the most common implementation.) The <a href="http://www.jython.org/Project/">Jython</a> and <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython">Ironpython</a> implementations also take this approach, but compile to the bytecode for the Java and C# virtual machines resepectively.</p></li>
<li><p>Bytecode + <a href="http://en.wikipedia.org/wiki/Just-in-time_compilation">Just in Time compilation</a>. As above, but rather than interpreting the bytecodes, the code that would be performed is compiled from the bytecode at the point of execution, and then run. In some cases, this can actually outperform native compilation, as it is free to perform runtime analysis on the code, and can use specific features of the current processor (while static compilation may need to compile for a lowest common denominator CPU). Later versions of Java, and C# use this approach. <a href="http://psyco.sourceforge.net/">Psyco</a> performs this for python.</p></li>
<li><p>Native machine-code compilation. The code is compiled to the machine code of the target system. You may think we've now completely eliminated interpretation, but even here there are subtleties. Some machine code instructions are not actually directly implemented in hardware, but are in fact implemented via <a href="http://en.wikipedia.org/wiki/Microcode">microcode</a> - even machine code is sometimes interpreted!</p></li>
</ol>
| 64
|
2009-04-14T20:23:11Z
|
[
"python"
] |
How to write ampersand in node attribude?
| 746,602
|
<p>I need to have following attribute value in my XML node:</p>
<pre><code>CommandLine="copy $(TargetPath) ..\..\&#x0D;&#x0A;echo dummy > dummy.txt"
</code></pre>
<p>Actually this is part of a .vcproj file generated in VS2008. <code>&#x0D;&#x0A</code> means line break, as there should be 2 separate commands.</p>
<p>I'm using Python 2.5 with minidom to parse XML - but unfortunately I don't know how to store sequences like <code>&#x0D;</code>, the best thing i can get is <code>&amp#x0D;</code>.</p>
<p>How can I store exactly <code>&#x0D;</code>?</p>
<p>UPD : Exactly speaking i have to store not &, but \r\n sequence in form of 
&#x0A </p>
| 0
|
2009-04-14T06:57:22Z
| 746,618
|
<p>You should try storing the actual characters (ASCII 13 and ASCII 10) in the attribute value, instead of their already-escaped counterparts.</p>
<p><hr /></p>
<p>EDIT: It looks like minidom does not handle newlines in attribute values correctly. </p>
<p>Even though a literal line break in an attribute value is allowed, but it will face normalization upon document parsing, at which point it is converted to a space.</p>
<p>I filed a bug in this regard: <a href="http://bugs.python.org/issue5752" rel="nofollow">http://bugs.python.org/issue5752</a></p>
| 1
|
2009-04-14T07:04:48Z
|
[
"python",
"xml"
] |
How to write ampersand in node attribude?
| 746,602
|
<p>I need to have following attribute value in my XML node:</p>
<pre><code>CommandLine="copy $(TargetPath) ..\..\&#x0D;&#x0A;echo dummy > dummy.txt"
</code></pre>
<p>Actually this is part of a .vcproj file generated in VS2008. <code>&#x0D;&#x0A</code> means line break, as there should be 2 separate commands.</p>
<p>I'm using Python 2.5 with minidom to parse XML - but unfortunately I don't know how to store sequences like <code>&#x0D;</code>, the best thing i can get is <code>&amp#x0D;</code>.</p>
<p>How can I store exactly <code>&#x0D;</code>?</p>
<p>UPD : Exactly speaking i have to store not &, but \r\n sequence in form of 
&#x0A </p>
| 0
|
2009-04-14T06:57:22Z
| 746,621
|
<p>An ampersand is a special character in XML and as such most xml parsers require valid xml in order to function. Let minidom escape the ampersand for you (really it should already be escaped) and then when you need to display the escaped value, unescape it.</p>
| 0
|
2009-04-14T07:06:42Z
|
[
"python",
"xml"
] |
How to write ampersand in node attribude?
| 746,602
|
<p>I need to have following attribute value in my XML node:</p>
<pre><code>CommandLine="copy $(TargetPath) ..\..\&#x0D;&#x0A;echo dummy > dummy.txt"
</code></pre>
<p>Actually this is part of a .vcproj file generated in VS2008. <code>&#x0D;&#x0A</code> means line break, as there should be 2 separate commands.</p>
<p>I'm using Python 2.5 with minidom to parse XML - but unfortunately I don't know how to store sequences like <code>&#x0D;</code>, the best thing i can get is <code>&amp#x0D;</code>.</p>
<p>How can I store exactly <code>&#x0D;</code>?</p>
<p>UPD : Exactly speaking i have to store not &, but \r\n sequence in form of 
&#x0A </p>
| 0
|
2009-04-14T06:57:22Z
| 747,260
|
<blockquote>
<p>I'm using Python 2.5 with minidom to parse XML - but unfortunately I don't know how to store sequences like 
</p>
</blockquote>
<p>Well, you can't specify that you want hex escapes specifically, but according to the DOM LS standard, implementations should change \r\n in attribute values to character references automatically.</p>
<p>Unfortunately, minidom doesn't:</p>
<pre><code>>>> from xml.domâimport minidom
>>> document= minidom.parseString('<a/>')
>>> document.documentElement.setAttribute('a', 'a\r\nb')
>>> document.toxml()
u'<?xml version="1.0" ?><a a="a\r\nb"/>'
</code></pre>
<p>This is a bug in minidom. Try the same in another DOM (eg. <a href="http://www.doxdesk.com/software/py/pxdom.html" rel="nofollow">pxdom</a>):</p>
<pre><code>>>> import pxdom
>>> document= pxdom.parseString('<a/>')
>>> document.documentElement.setAttribute('a', 'a\r\nb')
>>> document.pxdomContent
u'<?xml version="1.0" ?><a a="a&#13;&#10;b"/>'
</code></pre>
| 1
|
2009-04-14T12:16:00Z
|
[
"python",
"xml"
] |
Basic python. Quick question regarding calling a function
| 746,774
|
<p>I've got a basic problem in python, and I would be glad for some help :-)</p>
<p>I have two functions. One that convert a text file to a dictionary. And one that splits a sentence into separate words: </p>
<p>(This is the functiondoc.txt)</p>
<pre><code>def autoparts():
list_of_parts= open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v= line.split()
list1.append(k)
list2.append(v)
dictionary = dict(zip(k, v))
def splittext(text):
words = text.split()
print words
</code></pre>
<p>Now I want to make a program that uses these two functions. </p>
<p>(this is the program.txt)</p>
<pre><code>from functiondoc import *
# A and B are keys in the dict. The values are 'rear_bumper' 'back_seat'
text = 'A B' # Input
# Splits the input into separate strings.
input_ = split_line(text)
</code></pre>
<p>Here's the part I cant get right. I need to use the <code>autoparts</code> function to output the values (<code>rear_bumper back_seat</code>), but I'm not sure how to call that function so it does that. I don't think it's that hard. But I can't figure it out...</p>
<p>Kind Regards,</p>
<p>Th</p>
| 1
|
2009-04-14T08:45:40Z
| 746,783
|
<p>Some quick points:</p>
<ul>
<li>You should not name Python source files ".txt", you should use ".py".</li>
<li>Your indents look wrong, but that might just be Stack Overflow.</li>
<li>You need to call the <code>autoparts()</code> function to set up the dictionary.</li>
<li>The <code>autoparts()</code> function should probably return the dictionary, to make it usable by other code.</li>
<li>When <code>open</code>ing a text file, you should use the <code>t</code> mode specifier. On some platforms, the lower-level I/O code must know that it is reading text, so you need to tell it.</li>
</ul>
| 4
|
2009-04-14T08:50:01Z
|
[
"python"
] |
Basic python. Quick question regarding calling a function
| 746,774
|
<p>I've got a basic problem in python, and I would be glad for some help :-)</p>
<p>I have two functions. One that convert a text file to a dictionary. And one that splits a sentence into separate words: </p>
<p>(This is the functiondoc.txt)</p>
<pre><code>def autoparts():
list_of_parts= open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v= line.split()
list1.append(k)
list2.append(v)
dictionary = dict(zip(k, v))
def splittext(text):
words = text.split()
print words
</code></pre>
<p>Now I want to make a program that uses these two functions. </p>
<p>(this is the program.txt)</p>
<pre><code>from functiondoc import *
# A and B are keys in the dict. The values are 'rear_bumper' 'back_seat'
text = 'A B' # Input
# Splits the input into separate strings.
input_ = split_line(text)
</code></pre>
<p>Here's the part I cant get right. I need to use the <code>autoparts</code> function to output the values (<code>rear_bumper back_seat</code>), but I'm not sure how to call that function so it does that. I don't think it's that hard. But I can't figure it out...</p>
<p>Kind Regards,</p>
<p>Th</p>
| 1
|
2009-04-14T08:45:40Z
| 746,813
|
<p>Don't bother creating the lists first, just go straight to the dictionary:</p>
<pre><code>parts_dict={}
list_of_parts = open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v = line.split()
parts_dict[k] = v
</code></pre>
<p>Also, are these keys unique? Because if not some of the values will get overwritten.</p>
| 1
|
2009-04-14T08:58:36Z
|
[
"python"
] |
Basic python. Quick question regarding calling a function
| 746,774
|
<p>I've got a basic problem in python, and I would be glad for some help :-)</p>
<p>I have two functions. One that convert a text file to a dictionary. And one that splits a sentence into separate words: </p>
<p>(This is the functiondoc.txt)</p>
<pre><code>def autoparts():
list_of_parts= open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v= line.split()
list1.append(k)
list2.append(v)
dictionary = dict(zip(k, v))
def splittext(text):
words = text.split()
print words
</code></pre>
<p>Now I want to make a program that uses these two functions. </p>
<p>(this is the program.txt)</p>
<pre><code>from functiondoc import *
# A and B are keys in the dict. The values are 'rear_bumper' 'back_seat'
text = 'A B' # Input
# Splits the input into separate strings.
input_ = split_line(text)
</code></pre>
<p>Here's the part I cant get right. I need to use the <code>autoparts</code> function to output the values (<code>rear_bumper back_seat</code>), but I'm not sure how to call that function so it does that. I don't think it's that hard. But I can't figure it out...</p>
<p>Kind Regards,</p>
<p>Th</p>
| 1
|
2009-04-14T08:45:40Z
| 746,844
|
<p>In addition to all of the other hints and tips, I think you're missing something crucial: your functions actually need to <em>return</em> something.</p>
<p>When you create <code>autoparts()</code> or <code>splittext()</code>, the idea is that this will be a function that you can call, and it can (and should) give something back.</p>
<p>Once you figure out the output that you want your function to have, you need to put it in a <code>return</code> statement.</p>
<p>For example, if you wanted to <code>splittext</code> to return the list of words, rather than print them, you would need the line <code>return words</code>. If you want your <code>autoparts</code> to return the dictionary you've built, you would use <code>return dictionary</code>.</p>
<p>To be more precise (and to answer your comment/question below): you don't want to "return a function that makes a dictionary"; you want to return the dictionary while inside the function. So, the last line of your function should be <code>return dictionary</code> (inside the function!) See, for example, the (accepted!) solution from dbr, above.</p>
<p>I think you need to go back to the beginning and read a book or website about python in particular and programming in general, since you are slightly rusty on some of the concepts. One good one (others are available, of course) is <a href="http://diveintopython3.ep.io/" rel="nofollow">http://diveintopython3.ep.io/</a></p>
| 2
|
2009-04-14T09:21:19Z
|
[
"python"
] |
Basic python. Quick question regarding calling a function
| 746,774
|
<p>I've got a basic problem in python, and I would be glad for some help :-)</p>
<p>I have two functions. One that convert a text file to a dictionary. And one that splits a sentence into separate words: </p>
<p>(This is the functiondoc.txt)</p>
<pre><code>def autoparts():
list_of_parts= open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v= line.split()
list1.append(k)
list2.append(v)
dictionary = dict(zip(k, v))
def splittext(text):
words = text.split()
print words
</code></pre>
<p>Now I want to make a program that uses these two functions. </p>
<p>(this is the program.txt)</p>
<pre><code>from functiondoc import *
# A and B are keys in the dict. The values are 'rear_bumper' 'back_seat'
text = 'A B' # Input
# Splits the input into separate strings.
input_ = split_line(text)
</code></pre>
<p>Here's the part I cant get right. I need to use the <code>autoparts</code> function to output the values (<code>rear_bumper back_seat</code>), but I'm not sure how to call that function so it does that. I don't think it's that hard. But I can't figure it out...</p>
<p>Kind Regards,</p>
<p>Th</p>
| 1
|
2009-04-14T08:45:40Z
| 746,891
|
<p>There are a lot of problems with what you've written so far, but your question was how to call the auto parts function. Here's how; first, rename your files to functiondocs.py and program.py - they're python so make them python files.</p>
<p>Next, to call the autoparts function, you simply change your main program listing from:</p>
<pre><code>from functiondoc import *
# A and B are keys in the dict. The values are 'rear_bumper' 'back_seat'
text = 'A B' # Input
# Splits the input into separate strings.
input_ = split_line(text)
</code></pre>
<p>to:</p>
<pre><code>from functiondoc import *
# Call the autparts function
autoparts()
</code></pre>
<p>In my opinion, it looks like you're asking us to do a CS homework assignment.. but maybe I'm just cynical ;-)</p>
| 0
|
2009-04-14T09:38:21Z
|
[
"python"
] |
Basic python. Quick question regarding calling a function
| 746,774
|
<p>I've got a basic problem in python, and I would be glad for some help :-)</p>
<p>I have two functions. One that convert a text file to a dictionary. And one that splits a sentence into separate words: </p>
<p>(This is the functiondoc.txt)</p>
<pre><code>def autoparts():
list_of_parts= open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v= line.split()
list1.append(k)
list2.append(v)
dictionary = dict(zip(k, v))
def splittext(text):
words = text.split()
print words
</code></pre>
<p>Now I want to make a program that uses these two functions. </p>
<p>(this is the program.txt)</p>
<pre><code>from functiondoc import *
# A and B are keys in the dict. The values are 'rear_bumper' 'back_seat'
text = 'A B' # Input
# Splits the input into separate strings.
input_ = split_line(text)
</code></pre>
<p>Here's the part I cant get right. I need to use the <code>autoparts</code> function to output the values (<code>rear_bumper back_seat</code>), but I'm not sure how to call that function so it does that. I don't think it's that hard. But I can't figure it out...</p>
<p>Kind Regards,</p>
<p>Th</p>
| 1
|
2009-04-14T08:45:40Z
| 747,451
|
<p>Here's about the simplest way you could do this:</p>
<pre><code>def filetodict(filename):
return dict(line.split() for line in open(filename))
parts = filetodict("list_of_parts.txt")
print parts
</code></pre>
<p>Here's the output:</p>
<pre><code>{'a': 'apple', 'c': 'cheese', 'b': 'bacon', 'e': 'egg', 'd': 'donut'}
</code></pre>
<p>The file contents:</p>
<pre><code>a apple
b bacon
c cheese
d donut
e egg
</code></pre>
| 0
|
2009-04-14T13:06:47Z
|
[
"python"
] |
Basic python. Quick question regarding calling a function
| 746,774
|
<p>I've got a basic problem in python, and I would be glad for some help :-)</p>
<p>I have two functions. One that convert a text file to a dictionary. And one that splits a sentence into separate words: </p>
<p>(This is the functiondoc.txt)</p>
<pre><code>def autoparts():
list_of_parts= open('list_of_parts.txt', 'r')
for line in list_of_parts:
k, v= line.split()
list1.append(k)
list2.append(v)
dictionary = dict(zip(k, v))
def splittext(text):
words = text.split()
print words
</code></pre>
<p>Now I want to make a program that uses these two functions. </p>
<p>(this is the program.txt)</p>
<pre><code>from functiondoc import *
# A and B are keys in the dict. The values are 'rear_bumper' 'back_seat'
text = 'A B' # Input
# Splits the input into separate strings.
input_ = split_line(text)
</code></pre>
<p>Here's the part I cant get right. I need to use the <code>autoparts</code> function to output the values (<code>rear_bumper back_seat</code>), but I'm not sure how to call that function so it does that. I don't think it's that hard. But I can't figure it out...</p>
<p>Kind Regards,</p>
<p>Th</p>
| 1
|
2009-04-14T08:45:40Z
| 747,855
|
<p>As people have pointed out, you need to use the <code>py</code> extension for python source files. Your files would become "functiondoc.py" and "program.py". This will make your <code>import functiondoc</code> work correctly (as long as they are in the same directory)</p>
<p>The biggest problem with the <code>autoparts</code> function is you never returned anything. The other big problem is you used the wrong variable..</p>
<pre><code>for line in list_of_parts:
k, v = line.split()
list1.append(k)
list2.append(v)
# k and v are now the last line split up, *not* the list you've been constructing.
# The following incorrect line:
dictionary = dict(zip(k, v))
# ...should be:
dictionary = dict(zip(list1, list2))
# ..although you shouldn't use zip for this:
</code></pre>
<p>You almost <em>never</em> have to use <code>zip</code>, there are times when it can be useful, but for creating a simple dict, it's incorrect.. Instead of doing..</p>
<pre><code>for line in list_of_parts:
...
dictionary = dict(zip(k, v))
</code></pre>
<p>..simply create an empty dict before the loop, then do mydict[key_variable] = value_variable</p>
<p>For example, how I might have written the function..</p>
<pre><code>def autoparts():
# open() returns a file object, not the contents of the file,
# you need to use .read() or .readlines() to get the actual text
input_file = open('list_of_parts.txt', 'r')
all_lines = input_file.read_lines() # reads files as a list (one index per line)
mydict = {} # initialise a empty dictionary
for line in list_of_parts:
k, v = line.split()
mydict[k] = v
return mydict # you have to explicitly return stuff, or it returns None
</code></pre>
| 3
|
2009-04-14T14:27:04Z
|
[
"python"
] |
Adding a user supplied property (at runtime) to an instance of Expando class in google app engine?
| 746,942
|
<p>By creating datastore models that inherit from the Expando class I can
make my model-entities/instances have dynamic properties. That is
great! But what I want is the names of these dynamic properties to be
determined at runtime. Is that possible?</p>
<p>For example,</p>
<pre><code>class ExpandoTest (db.Expando):
prop1 = db.StringProperty()
prop2 = db.StringProperty()
entity_one = ExpandoTest()
entity_two = ExpandoTest()
# what I do not want
entity_one.prop3 = 'Demo of dynamic property'
# what I want
entity_two.<property_name_as_entered_by_user_at_runtime> = 'This
property name was entered by the user, Great!!'
</code></pre>
<p>Is this possible? If yes, how to do this?
I have already tried some funny ways to do this but did not succeed :P</p>
<p>Thanks in advance.</p>
| 0
|
2009-04-14T09:56:27Z
| 746,978
|
<p>Just found the solution to my own question. It was really simple but as I am a python noob I ended up posting the question that you see above.</p>
<p>For the code sample that I had used, this is what needs to be done: </p>
<pre><code>entity_two.__setattr(some_variable, some_value) #where some_variable is populated by user at runtime :)
</code></pre>
| 0
|
2009-04-14T10:09:51Z
|
[
"python",
"google-app-engine"
] |
Adding a user supplied property (at runtime) to an instance of Expando class in google app engine?
| 746,942
|
<p>By creating datastore models that inherit from the Expando class I can
make my model-entities/instances have dynamic properties. That is
great! But what I want is the names of these dynamic properties to be
determined at runtime. Is that possible?</p>
<p>For example,</p>
<pre><code>class ExpandoTest (db.Expando):
prop1 = db.StringProperty()
prop2 = db.StringProperty()
entity_one = ExpandoTest()
entity_two = ExpandoTest()
# what I do not want
entity_one.prop3 = 'Demo of dynamic property'
# what I want
entity_two.<property_name_as_entered_by_user_at_runtime> = 'This
property name was entered by the user, Great!!'
</code></pre>
<p>Is this possible? If yes, how to do this?
I have already tried some funny ways to do this but did not succeed :P</p>
<p>Thanks in advance.</p>
| 0
|
2009-04-14T09:56:27Z
| 747,028
|
<p>Usually, we use the setattr function directly.</p>
<pre><code>setattr( entity_two, 'some_variable', some_value )
</code></pre>
| 3
|
2009-04-14T10:35:10Z
|
[
"python",
"google-app-engine"
] |
wxPython: Calling an event manually
| 747,781
|
<p>How can I call a specific event manually from my own code?</p>
| 16
|
2009-04-14T14:14:27Z
| 747,805
|
<p>You mean you want to have an event dispatch?</p>
<blockquote>
<p>::wxPostEvent void
wxPostEvent(wxEvtHandler *dest,
wxEvent& event)</p>
<p>In a GUI application, this function
posts event to the specified dest
object using
wxEvtHandler::AddPendingEvent.
Otherwise, it dispatches event
immediately using
wxEvtHandler::ProcessEvent. See the
respective documentation for details
(and caveats).</p>
<p>Include files</p>
<p><code><wx/app.h></code></p>
</blockquote>
<p><a href="http://www.wxpython.org/onlinedocs.php" rel="nofollow">wxPython API docs</a></p>
| 0
|
2009-04-14T14:19:36Z
|
[
"python",
"user-interface",
"events",
"wxpython"
] |
wxPython: Calling an event manually
| 747,781
|
<p>How can I call a specific event manually from my own code?</p>
| 16
|
2009-04-14T14:14:27Z
| 748,801
|
<p>I think you want <a href="http://www.wxpython.org/docs/api/wx-module.html#PostEvent">wx.PostEvent</a>.</p>
<p>There's also some info about posting events from other thread for <a href="http://wiki.wxpython.org/LongRunningTasks">long running tasks on the wxPython wiki</a>.</p>
| 8
|
2009-04-14T18:28:22Z
|
[
"python",
"user-interface",
"events",
"wxpython"
] |
wxPython: Calling an event manually
| 747,781
|
<p>How can I call a specific event manually from my own code?</p>
| 16
|
2009-04-14T14:14:27Z
| 841,045
|
<p>Old topic, but I think I've got this figured out after being confused about it for a long time, so if anyone else comes through here looking for the answer, this might help.</p>
<p>To manually post an event, you can use</p>
<pre><code>self.GetEventHandler().ProcessEvent(event)
</code></pre>
<p>(wxWidgets docs <a href="http://docs.wxwidgets.org/stable/wx_wxevthandler.html#wxevthandlerprocessevent">here</a>, wxPython docs <a href="http://www.wxpython.org/docs/api/wx.EvtHandler-class.html">here</a>)</p>
<p>or</p>
<pre><code>wx.PostEvent(self.GetEventHandler(), event)
</code></pre>
<p>(<a href="http://docs.wxwidgets.org/stable/wx_miscellany.html#wxpostevent">wxWidgets docs</a>, <a href="http://www.wxpython.org/docs/api/wx-module.html#PostEvent">wxPython docs</a>) </p>
<p>where <code>event</code> is the event you want to post. Construct the event with e.g.</p>
<pre><code>wx.PyCommandEvent(wx.EVT_BUTTON.typeId, self.GetId())
</code></pre>
<p>if you want to post a EVT_BUTTON event. Making it a <a href="http://www.wxpython.org/docs/api/wx.PyCommandEvent-class.html">PyCommandEvent</a> means that it will propagate upwards; other event types don't propagate by default.</p>
<p>You can also create custom events that can carry whatever data you want them to. Here's an example:</p>
<pre><code>myEVT_CUSTOM = wx.NewEventType()
EVT_CUSTOM = wx.PyEventBinder(myEVT_CUSTOM, 1)
class MyEvent(wx.PyCommandEvent):
def __init__(self, evtType, id):
wx.PyCommandEvent.__init__(self, evtType, id)
myVal = None
def SetMyVal(self, val):
self.myVal = val
def GetMyVal(self):
return self.myVal
</code></pre>
<p>(I think I found this code in a mailing list archive somewhere, but I can't seem to find it again. If this is your example, thanks! Please add a comment and take credit for it!)</p>
<p>So now, to Post a custom event:</p>
<pre><code>event = MyEvent(myEVT_CUSTOM, self.GetId())
event.SetMyVal('here is some custom data')
self.GetEventHandler().ProcessEvent(event)
</code></pre>
<p>and you can bind it just like any other event</p>
<pre><code>self.Bind(EVT_CUSTOM, self.on_event)
</code></pre>
<p>and get the custom data in the event handler</p>
<pre><code>def on_event(self, e):
data = e.GetMyVal()
print 'custom data is: {0}'.format(data)
</code></pre>
<p>Or include the custom data in the event constructor and save a step:</p>
<pre><code>class MyEvent(wx.PyCommandEvent):
def __init__(self, evtType, id, val = None):
wx.PyCommandEvent.__init__(self, evtType, id)
self.myVal = val
</code></pre>
<p>etc.</p>
<p>Hope this is helpful to someone.</p>
| 45
|
2009-05-08T17:55:39Z
|
[
"python",
"user-interface",
"events",
"wxpython"
] |
wxPython: Calling an event manually
| 747,781
|
<p>How can I call a specific event manually from my own code?</p>
| 16
|
2009-04-14T14:14:27Z
| 4,189,924
|
<p>There's a simple, straightforward way to do it with recent versions of wxPython (see <a href="http://wiki.wxpython.org/CustomEventClasses" rel="nofollow">http://wiki.wxpython.org/CustomEventClasses</a>):</p>
<pre><code> # create event class
import wx.lib.newevent
SomeNewEvent, EVT_SOME_NEW_EVENT = wx.lib.newevent.NewEvent()
# post it, with arbitrary data attached
wx.PostEvent(target, SomeNewEvent(attr1=foo, attr2=bar))
# bind it as usual
target.Bind(EVT_SOME_NEW_EVENT, target.handler)
</code></pre>
| 4
|
2010-11-15T23:38:17Z
|
[
"python",
"user-interface",
"events",
"wxpython"
] |
Python borg pattern problem
| 747,793
|
<p>I'm having problems implementing a borg in python. I found an example in an answer to <a href="http://stackoverflow.com/questions/736335/python-superglobal">this question</a> but it's not working for me, unless I'm missing something. Here's the code:</p>
<pre><code>
class Config:
"""
Borg singleton config object
"""
__we_are_one = {}
__myvalue = ""
def __init__(self):
#implement the borg pattern (we are one)
self.__dict__ = self.__we_are_one
self.__myvalue = ""
def myvalue(self, value=None):
if value:
self.__myvalue = value
return self.__myvalue
conf = Config()
conf.myvalue("Hello")
conf2 = Config()
print conf2.myvalue()
</code></pre>
<p>I assume this is meant to print "Hello", but for me it just prints a blank line. Any ideas why this might be?</p>
| 6
|
2009-04-14T14:17:36Z
| 747,881
|
<p>The problem appears to be that init() is resetting myvalue to an empty string. When I remove that line I get the expected output.</p>
| 1
|
2009-04-14T14:32:26Z
|
[
"python",
"design-patterns"
] |
Python borg pattern problem
| 747,793
|
<p>I'm having problems implementing a borg in python. I found an example in an answer to <a href="http://stackoverflow.com/questions/736335/python-superglobal">this question</a> but it's not working for me, unless I'm missing something. Here's the code:</p>
<pre><code>
class Config:
"""
Borg singleton config object
"""
__we_are_one = {}
__myvalue = ""
def __init__(self):
#implement the borg pattern (we are one)
self.__dict__ = self.__we_are_one
self.__myvalue = ""
def myvalue(self, value=None):
if value:
self.__myvalue = value
return self.__myvalue
conf = Config()
conf.myvalue("Hello")
conf2 = Config()
print conf2.myvalue()
</code></pre>
<p>I assume this is meant to print "Hello", but for me it just prints a blank line. Any ideas why this might be?</p>
| 6
|
2009-04-14T14:17:36Z
| 747,888
|
<p>It looks like it's working rather too well :-)</p>
<p>The issue is that the assignment <code>self.__myvalue = ""</code> in <code>__init__</code> will always clobber the value of <code>myvalue</code> every time a new Borg is, er, created. You can see this if you add some additional print statements to your test:</p>
<pre><code>conf = Config()
conf.myvalue("Hello")
print conf.myvalue() # prints Hello
conf2 = Config()
print conf.myvalue() # prints nothing
print conf2.myvalue() # prints nothing
</code></pre>
<p>Remove the <code>self.__myvalue</code> and things will be fine.</p>
<p>Having said that, the implementation of <code>myvalue()</code> is a little weird. Better, I'd say, to have explicit getters and setters using properties. You'll also want some code in <code>__init__</code> to initialize the value of <code>myvalue</code> if it doesn't exist yet, or to at least handle that it might not exist in the getter. Perhaps something like:</p>
<pre><code>class Config(object):
"""
Borg singleton config object
"""
_we_are_one = {}
def __init__(self):
#implement the borg pattern (we are one)
self.__dict__ = self._we_are_one
def set_myvalue(self, val):
self._myvalue = val
def get_myvalue(self):
return getattr(self, '_myvalue', None)
myvalue = property(get_myvalue, set_myvalue)
c = Config()
print c.myvalue # prints None
c.myvalue = 5
print c.myvalue # prints 5
c2 = Config()
print c2.myvalue #prints 5
</code></pre>
| 13
|
2009-04-14T14:33:32Z
|
[
"python",
"design-patterns"
] |
Python borg pattern problem
| 747,793
|
<p>I'm having problems implementing a borg in python. I found an example in an answer to <a href="http://stackoverflow.com/questions/736335/python-superglobal">this question</a> but it's not working for me, unless I'm missing something. Here's the code:</p>
<pre><code>
class Config:
"""
Borg singleton config object
"""
__we_are_one = {}
__myvalue = ""
def __init__(self):
#implement the borg pattern (we are one)
self.__dict__ = self.__we_are_one
self.__myvalue = ""
def myvalue(self, value=None):
if value:
self.__myvalue = value
return self.__myvalue
conf = Config()
conf.myvalue("Hello")
conf2 = Config()
print conf2.myvalue()
</code></pre>
<p>I assume this is meant to print "Hello", but for me it just prints a blank line. Any ideas why this might be?</p>
| 6
|
2009-04-14T14:17:36Z
| 747,940
|
<p>Combining the removal of <code>self.__myvalue = ""</code> with the <a href="http://code.activestate.com/recipes/66531/#c20" rel="nofollow">new-style Borg</a> and the suggestions to avoid <code>__</code> in variable names, we get:</p>
<pre><code>class Config(object):
"""
Borg singleton config object
"""
_we_are_one = {}
_myvalue = ""
def __new__(cls, *p, **k):
self = object.__new__(cls, *p, **k)
self.__dict__ = cls._we_are_one
return self
def myvalue(self, value=None):
if value:
self._myvalue = value
return self._myvalue
if __name__ == '__main__':
conf = Config()
conf.myvalue("Hello")
conf2 = Config()
print conf2.myvalue()
</code></pre>
| 4
|
2009-04-14T14:43:16Z
|
[
"python",
"design-patterns"
] |
Python borg pattern problem
| 747,793
|
<p>I'm having problems implementing a borg in python. I found an example in an answer to <a href="http://stackoverflow.com/questions/736335/python-superglobal">this question</a> but it's not working for me, unless I'm missing something. Here's the code:</p>
<pre><code>
class Config:
"""
Borg singleton config object
"""
__we_are_one = {}
__myvalue = ""
def __init__(self):
#implement the borg pattern (we are one)
self.__dict__ = self.__we_are_one
self.__myvalue = ""
def myvalue(self, value=None):
if value:
self.__myvalue = value
return self.__myvalue
conf = Config()
conf.myvalue("Hello")
conf2 = Config()
print conf2.myvalue()
</code></pre>
<p>I assume this is meant to print "Hello", but for me it just prints a blank line. Any ideas why this might be?</p>
| 6
|
2009-04-14T14:17:36Z
| 4,857,198
|
<pre><code>class Borg(object):
"""Demonstrating the Borg-pattern: All the instances of a class already
know what one of them learned... Scary, isn't it?"""
def __init__(self, name):
self.name = name
@classmethod
def borg_knowledge(cls, who_is_it):
if hasattr(cls, "b_knowledge"):
return "%s: I already know that the borg pattern is awesome!" % who_is_it
else:
cls.b_knowledge = True
return "%s: Learning about the borg pattern..." % who_is_it
def personal_experience(self):
if hasattr(self, "p_knowledge"):
return "%s: I already know that!" % self.name
else:
self.p_knowledge = True
return "%s: Learning something..." % self.name
b1 = Borg("b1")
b2 = Borg("b2")
print ">> Created b1 and b2, both Borg"; print
print ">> Usual class behavior. One instance does not know what the other does."
print b1.personal_experience()
print b2.personal_experience()
print
print ">> Borg have a shared knowledge a.k.a. why classmethods are different!"
print b1.borg_knowledge(b1.name)
print b2.borg_knowledge(b2.name)
</code></pre>
| 1
|
2011-01-31T23:12:20Z
|
[
"python",
"design-patterns"
] |
Python borg pattern problem
| 747,793
|
<p>I'm having problems implementing a borg in python. I found an example in an answer to <a href="http://stackoverflow.com/questions/736335/python-superglobal">this question</a> but it's not working for me, unless I'm missing something. Here's the code:</p>
<pre><code>
class Config:
"""
Borg singleton config object
"""
__we_are_one = {}
__myvalue = ""
def __init__(self):
#implement the borg pattern (we are one)
self.__dict__ = self.__we_are_one
self.__myvalue = ""
def myvalue(self, value=None):
if value:
self.__myvalue = value
return self.__myvalue
conf = Config()
conf.myvalue("Hello")
conf2 = Config()
print conf2.myvalue()
</code></pre>
<p>I assume this is meant to print "Hello", but for me it just prints a blank line. Any ideas why this might be?</p>
| 6
|
2009-04-14T14:17:36Z
| 5,602,852
|
<pre><code>> The problem appears to be that init() is resetting myvalue to an
> empty string. When You remove that
> line ('self.__myvalue = ""') then you will get the expected
> output.
</code></pre>
| 0
|
2011-04-09T04:21:28Z
|
[
"python",
"design-patterns"
] |
Python borg pattern problem
| 747,793
|
<p>I'm having problems implementing a borg in python. I found an example in an answer to <a href="http://stackoverflow.com/questions/736335/python-superglobal">this question</a> but it's not working for me, unless I'm missing something. Here's the code:</p>
<pre><code>
class Config:
"""
Borg singleton config object
"""
__we_are_one = {}
__myvalue = ""
def __init__(self):
#implement the borg pattern (we are one)
self.__dict__ = self.__we_are_one
self.__myvalue = ""
def myvalue(self, value=None):
if value:
self.__myvalue = value
return self.__myvalue
conf = Config()
conf.myvalue("Hello")
conf2 = Config()
print conf2.myvalue()
</code></pre>
<p>I assume this is meant to print "Hello", but for me it just prints a blank line. Any ideas why this might be?</p>
| 6
|
2009-04-14T14:17:36Z
| 27,284,610
|
<p>I tried implementing this using the "old-style" as well as the "new-style" and I cannot see a difference between them. Is there an advantage to one over the other? Or are these basically equivalent?</p>
<pre><code>class Borg(object):
shared_state = {'a_value': True}
def __init__(self):
self.__dict__ = self.shared_state
class NewBorg(object):
shared_state = {'a_value': True}
def __new__(cls, *p, **k):
self = object.__new__(cls, *p, **k)
self.__dict__ = cls.shared_state
return self
borg_a = Borg()
borg_b = Borg()
print id(borg_a), '!=', id(borg_b)
assert borg_a.shared_state == borg_b.shared_state
borg_a.shared_state['a_value'] = False
assert borg_a.shared_state == borg_b.shared_state
new_borg_a = NewBorg()
new_borg_b = NewBorg()
print id(new_borg_a), '!=', id(new_borg_b)
assert new_borg_a.shared_state == new_borg_b.shared_state
new_borg_a.shared_state['a_value'] = False
assert new_borg_a.shared_state == new_borg_b.shared_state
</code></pre>
| 0
|
2014-12-04T01:11:39Z
|
[
"python",
"design-patterns"
] |
How to get output of exe in python script?
| 748,028
|
<p>When I call an external <code>.exe</code> program in Python, how can I get <code>printf</code> output from the <code>.exe</code> application and print it to my Python IDE?</p>
| 4
|
2009-04-14T15:02:33Z
| 748,058
|
<p>To call an external program from Python, use the <a href="http://docs.python.org/library/subprocess.html#module-subprocess">subprocess</a> module.</p>
<blockquote>
<p>The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. </p>
</blockquote>
<p>An example from the doc (<code>output</code> is a file object that provides output from the child process.):</p>
<pre><code>output = subprocess.Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
</code></pre>
<p>A concrete example, using <code>cmd</code>, the Windows command line interpreter with 2 arguments:</p>
<pre><code>>>> p1 = subprocess.Popen(["cmd", "/C", "date"],stdout=subprocess.PIPE)
>>> p1.communicate()[0]
'The current date is: Tue 04/14/2009 \r\nEnter the new date: (mm-dd-yy) '
>>>
</code></pre>
| 14
|
2009-04-14T15:09:02Z
|
[
"python",
"ide",
"executable",
"redirect"
] |
How to get output of exe in python script?
| 748,028
|
<p>When I call an external <code>.exe</code> program in Python, how can I get <code>printf</code> output from the <code>.exe</code> application and print it to my Python IDE?</p>
| 4
|
2009-04-14T15:02:33Z
| 748,170
|
<p>I am pretty sure that you are talking about Windows here (based on the phrasing of your question), but in a Unix/Linux (including Mac) environment, the commands module is also available:</p>
<pre><code>import commands
( stat, output ) = commands.getstatusoutput( "somecommand" )
if( stat == 0 ):
print "Command succeeded, here is the output: %s" % output
else:
print "Command failed, here is the output: %s" % output
</code></pre>
<p>The commands module provides an extremely simple interface to run commands and get the status (return code) and the output (reads from stdout and stderr). Optionally, you can get just status or just output by calling commands.getstatus() or commands.getoutput() respectively.</p>
| 5
|
2009-04-14T15:38:55Z
|
[
"python",
"ide",
"executable",
"redirect"
] |
benchmarking django apps
| 748,130
|
<p>I'm interested in testing the performance of my django apps as I go, what is the best way to get line by line performance data?</p>
<p><strong>note</strong>: Googling this returns lots of people benchmarking django itself. I'm not looking for a benchmarks of django, I'm trying to test the performance of the django apps that I'm writing :)</p>
<p>Thanks!</p>
<p><strong>edit</strong>: By "line by line" I just mean timing individual functions, db calls, etc to find out where the bottlenecks are on a very granular level</p>
| 13
|
2009-04-14T15:26:16Z
| 748,177
|
<p>There's two layers to this. We have most of #1 in place for our testing. We're about to start on #2.</p>
<ol>
<li><p>Django in isolation. The ordinary Django unit tests works well here. Create some tests that cycle through a few (less than 6) "typical" use cases. Get this, post that, etc. Collect timing data. This isn't real web performance, but it's an easy-to-work with test scenario that you can use for tuning.</p></li>
<li><p>Your whole web stack. In this case, you need a regular server running Squid, Apache, Django, MySQL, whatever. You need a second computer(s) to act a client exercise your web site through urllib2, doing a few (less than 6) "typical" use cases. Get this, post that, etc. Collect timing data. This still isn't "real" web performance, because it isn't through the internet, but it's as close as you're going to get without a really elaborate setup.</p></li>
</ol>
<p>Note that the #2 (end-to-end) includes a great deal of caching for performance. If your client scripts are doing similar work, caching will be really beneficial. if your client scripts do unique things each time, caching will be less beneficial.</p>
<p>The hardest part is determining what the "typical" workload is. This isn't functional testing, so the workload doesn't have to include everything. Also, the more concurrent sessions your client is running, the slower it becomes. Don't struggle trying to optimize your server when your test client is the slowest part of the processing.</p>
<hr>
<p><strong>Edit</strong></p>
<p>If "line-by-line" means "profiling", well, you've got to get a Python profiler running.</p>
<p><a href="https://docs.python.org/library/profile.html" rel="nofollow">https://docs.python.org/library/profile.html</a></p>
<p>Note that there's plenty of caching in the Django ORM layer. So running a view function a half-dozen times to get a meaningful set of measurements isn't sensible. You have to run a "typical" set of operations and then find hot-spots in the profile. </p>
<p>Generally, your application is easy to optimize -- you shouldn't be doing much. Your view functions should be short and have no processing to speak of. Your form and model method functions, similarly, should be very short.</p>
| 7
|
2009-04-14T15:39:50Z
|
[
"python",
"django",
"profiling"
] |
benchmarking django apps
| 748,130
|
<p>I'm interested in testing the performance of my django apps as I go, what is the best way to get line by line performance data?</p>
<p><strong>note</strong>: Googling this returns lots of people benchmarking django itself. I'm not looking for a benchmarks of django, I'm trying to test the performance of the django apps that I'm writing :)</p>
<p>Thanks!</p>
<p><strong>edit</strong>: By "line by line" I just mean timing individual functions, db calls, etc to find out where the bottlenecks are on a very granular level</p>
| 13
|
2009-04-14T15:26:16Z
| 748,251
|
<p>One way to get line by line performance data (profiling) your Django app is to use a WSGI middleware component like <strong><a href="http://pypi.python.org/pypi/repoze.profile/0.8">repoze.profile</a></strong>.</p>
<p>Assuming you are using mod_wsgi with Apache you can insert repoze.profile into your app like this:</p>
<pre><code>...
application = django.core.handlers.wsgi.WSGIHandler()
...
from repoze.profile.profiler import AccumulatingProfileMiddleware
application = AccumulatingProfileMiddleware(
application,
log_filename='/path/to/logs/profile.log',
discard_first_request=True,
flush_at_shutdown=True,
path='/_profile'
)
</code></pre>
<p>And now you can point your browser to /_profile to view your profile data. Of course this won't work with mod_python or the internal Django server.</p>
| 5
|
2009-04-14T15:57:17Z
|
[
"python",
"django",
"profiling"
] |
Python: Convert those TinyURL (bit.ly, tinyurl, ow.ly) to full URLS
| 748,324
|
<p>I am just learning python and is interested in how this can be accomplished. During the search for the answer, I came across this service: <a href="http://www.longurlplease.com">http://www.longurlplease.com</a> </p>
<p>For example: </p>
<p><a href="http://bit.ly/rgCbf">http://bit.ly/rgCbf</a> can be converted to:</p>
<p><a href="http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place">http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place</a></p>
<p>I did some inspecting with Firefox and see that the original url is not in the header.</p>
| 12
|
2009-04-14T16:14:04Z
| 748,340
|
<p>Enter <a href="http://docs.python.org/library/urllib2.html"><code>urllib2</code></a>, which offers the easiest way of doing this:</p>
<pre><code>>>> import urllib2
>>> fp = urllib2.urlopen('http://bit.ly/rgCbf')
>>> fp.geturl()
'http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place'
</code></pre>
<p>For reference's sake, however, note that this is also possible with <a href="http://docs.python.org/library/httplib.html#module-httplib"><code>httplib</code></a>:</p>
<pre><code>>>> import httplib
>>> conn = httplib.HTTPConnection('bit.ly')
>>> conn.request('HEAD', '/rgCbf')
>>> response = conn.getresponse()
>>> response.getheader('location')
'http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place'
</code></pre>
<p>And with <a href="http://pycurl.sourceforge.net/"><code>PycURL</code></a>, although I'm not sure if this is the best way to do it using it:</p>
<pre><code>>>> import pycurl
>>> conn = pycurl.Curl()
>>> conn.setopt(pycurl.URL, "http://bit.ly/rgCbf")
>>> conn.setopt(pycurl.FOLLOWLOCATION, 1)
>>> conn.setopt(pycurl.CUSTOMREQUEST, 'HEAD')
>>> conn.setopt(pycurl.NOBODY, True)
>>> conn.perform()
>>> conn.getinfo(pycurl.EFFECTIVE_URL)
'http://webdesignledger.com/freebies/the-best-social-media-icons-all-in-one-place'
</code></pre>
| 32
|
2009-04-14T16:17:56Z
|
[
"python",
"bit.ly",
"tinyurl"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.