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 |
|---|---|---|---|---|---|---|---|---|---|
What's the most efficient way to find one of several substrings in Python? | 842,856 | <p>I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice the list contains hundreds of entries. </p>
<p>I'm processing a string, and what I'm looking for is to find the index of first appearance of any of these substrings.</p>
<p>To clarify, for '012cat' the result is 3, and for '0123dog789cat' the result is 4. </p>
<p>I also need to know which substring was found (e.g. its index in the substring list or the text itself), or at least the length of the substring matched.</p>
<p>There are obvious brute-force ways to achieve this, I wondered if there's any elegant Python/Regex solution for this.</p>
<p>Thanks,
Rax</p>
| 21 | 2009-05-09T07:20:49Z | 842,860 | <pre><code>subs = ['cat', 'fish', 'dog']
sentences = ['0123dog789cat']
import re
subs = re.compile("|".join(subs))
def search():
for sentence in sentences:
result = subs.search(sentence)
if result != None:
return (result.group(), result.span()[0])
# ('dog', 4)
</code></pre>
| 4 | 2009-05-09T07:24:07Z | [
"python",
"regex",
"string",
"substring"
] |
What's the most efficient way to find one of several substrings in Python? | 842,856 | <p>I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice the list contains hundreds of entries. </p>
<p>I'm processing a string, and what I'm looking for is to find the index of first appearance of any of these substrings.</p>
<p>To clarify, for '012cat' the result is 3, and for '0123dog789cat' the result is 4. </p>
<p>I also need to know which substring was found (e.g. its index in the substring list or the text itself), or at least the length of the substring matched.</p>
<p>There are obvious brute-force ways to achieve this, I wondered if there's any elegant Python/Regex solution for this.</p>
<p>Thanks,
Rax</p>
| 21 | 2009-05-09T07:20:49Z | 842,871 | <p>I would assume a regex is better than checking for each substring individually because <em>conceptually</em> the regular expression is modeled as a DFA, and so as the input is consumed all matches are being tested for at the same time (resulting in one scan of the input string).</p>
<p>So, here is an example:</p>
<pre><code>import re
def work():
to_find = re.compile("cat|fish|dog")
search_str = "blah fish cat dog haha"
match_obj = to_find.search(search_str)
the_index = match_obj.start() # produces 5, the index of fish
which_word_matched = match_obj.group() # "fish"
# Note, if no match, match_obj is None
</code></pre>
<p><em><strong>UPDATE:</em></strong>
Some care should be taken when combining words in to a single pattern of alternative words. The following code builds a regex, but <a href="http://docs.python.org/2.7/library/re.html#re.escape">escapes any regex special characters</a> and sorts the words so that longer words get a chance to match before any shorter prefixes of the same word:</p>
<pre><code>def wordlist_to_regex(words):
escaped = map(re.escape, words)
combined = '|'.join(sorted(escaped, key=len, reverse=True))
return re.compile(combined)
>>> r.search('smash atomic particles').span()
(6, 10)
>>> r.search('visit usenet:comp.lang.python today').span()
(13, 29)
>>> r.search('a north\south division').span()
(2, 13)
>>> r.search('012cat').span()
(3, 6)
>>> r.search('0123dog789cat').span()
(4, 7)
</code></pre>
<p><em><strong>END UPDATE</em></strong></p>
<p>It should be noted that you will want to form the regex (ie - call to re.compile()) as little as possible. The best case would be you know ahead of time what your searches are (or you compute them once/infrequently) and then save the result of re.compile somewhere. My example is just a simple nonsense function so you can see the usage of the regex. There are some more regex docs here:</p>
<p><a href="http://docs.python.org/library/re.html">http://docs.python.org/library/re.html</a></p>
<p>Hope this helps.</p>
<p><em><strong>UPDATE:</em></strong> I am unsure about how python implements regular expressions, but to answer Rax's question about whether or not there are limitations of re.compile() (for example, how many words you can try to "|" together to match at once), and the amount of time to run compile: neither of these seem to be an issue. I tried out this code, which is good enough to convince me. (I could have made this better by adding timing and reporting results, as well as throwing the list of words into a set to ensure there are no duplicates... but both of these improvements seem like overkill). This code ran basically instantaneously, and convinced me that I am able to search for 2000 words (of size 10), and that and of them will match appropriately. Here is the code:</p>
<pre><code>import random
import re
import string
import sys
def main(args):
words = []
letters_and_digits = "%s%s" % (string.letters, string.digits)
for i in range(2000):
chars = []
for j in range(10):
chars.append(random.choice(letters_and_digits))
words.append(("%s"*10) % tuple(chars))
search_for = re.compile("|".join(words))
first, middle, last = words[0], words[len(words) / 2], words[-1]
search_string = "%s, %s, %s" % (last, middle, first)
match_obj = search_for.search(search_string)
if match_obj is None:
print "Ahhhg"
return
index = match_obj.start()
which = match_obj.group()
if index != 0:
print "ahhhg"
return
if words[-1] != which:
print "ahhg"
return
print "success!!! Generated 2000 random words, compiled re, and was able to perform matches."
if __name__ == "__main__":
main(sys.argv)
</code></pre>
<p><em><strong>UPDATE:</em></strong> It should be noted that the order of of things ORed together in the regex <em>matters</em>. Have a look at the following test inspired by <a href="http://stackoverflow.com/users/6899/">TZOTZIOY</a>:</p>
<pre><code>>>> search_str = "01catdog"
>>> test1 = re.compile("cat|catdog")
>>> match1 = test1.search(search_str)
>>> match1.group()
'cat'
>>> match1.start()
2
>>> test2 = re.compile("catdog|cat") # reverse order
>>> match2 = test2.search(search_str)
>>> match2.group()
'catdog'
>>> match2.start()
2
</code></pre>
<p>This suggests the order matters :-/. I am not sure what this means for Rax's application, but at least the behavior is known.</p>
<p><em><strong>UPDATE:</em></strong> I posted <a href="http://stackoverflow.com/questions/844183/python-regular-expression-implementation-details">this questions about the implementation of regular expressions in Python</a> which will hopefully give us some insight into the issues found with this question.</p>
| 30 | 2009-05-09T07:34:52Z | [
"python",
"regex",
"string",
"substring"
] |
What's the most efficient way to find one of several substrings in Python? | 842,856 | <p>I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice the list contains hundreds of entries. </p>
<p>I'm processing a string, and what I'm looking for is to find the index of first appearance of any of these substrings.</p>
<p>To clarify, for '012cat' the result is 3, and for '0123dog789cat' the result is 4. </p>
<p>I also need to know which substring was found (e.g. its index in the substring list or the text itself), or at least the length of the substring matched.</p>
<p>There are obvious brute-force ways to achieve this, I wondered if there's any elegant Python/Regex solution for this.</p>
<p>Thanks,
Rax</p>
| 21 | 2009-05-09T07:20:49Z | 842,878 | <p>This is a vague, theoretical answer with no code provided, but I hope it can point you in the right direction.</p>
<p>First, you will need a more efficient lookup for your substring list. I would recommend some sort of tree structure. Start with a root, then add an <code>'a'</code> node if any substrings start with <code>'a'</code>, add a <code>'b'</code> node if any substrings start with <code>'b'</code>, and so on. For each of these nodes, keep adding subnodes.</p>
<p>For example, if you have a substring with the word "ant", you should have a root node, a child node <code>'a'</code>, a grandchild node <code>'n'</code>, and a great grandchild node <code>'t'</code>.</p>
<p>Nodes should be easy enough to make.</p>
<pre><code>class Node(object):
children = []
def __init__(self, name):
self.name = name
</code></pre>
<p>where <code>name</code> is a character.</p>
<p>Iterate through your strings letter by letter. Keep track of which letter you're on. At each letter, try to use the next few letters to traverse the tree. If you're successful, your letter number will be the position of the substring, and your traversal order will indicate the substring that was found.</p>
<p>Clarifying edit: DFAs should be much faster than this method, and so I should endorse <a href="http://stackoverflow.com/questions/842856/whats-the-most-efficient-way-to-find-one-of-several-substrings-in-python/842871#842871">Tom's answer</a>. I'm only keeping this answer up in case your substring list changes often, in which case using a tree <em>might</em> be faster.</p>
| 2 | 2009-05-09T07:40:42Z | [
"python",
"regex",
"string",
"substring"
] |
What's the most efficient way to find one of several substrings in Python? | 842,856 | <p>I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice the list contains hundreds of entries. </p>
<p>I'm processing a string, and what I'm looking for is to find the index of first appearance of any of these substrings.</p>
<p>To clarify, for '012cat' the result is 3, and for '0123dog789cat' the result is 4. </p>
<p>I also need to know which substring was found (e.g. its index in the substring list or the text itself), or at least the length of the substring matched.</p>
<p>There are obvious brute-force ways to achieve this, I wondered if there's any elegant Python/Regex solution for this.</p>
<p>Thanks,
Rax</p>
| 21 | 2009-05-09T07:20:49Z | 842,904 | <p>First of all, I would suggest you to sort the initial list in ascending order. Because scanning for a shorter substring is faster that scanning for a longer substring.</p>
| 0 | 2009-05-09T08:02:09Z | [
"python",
"regex",
"string",
"substring"
] |
What's the most efficient way to find one of several substrings in Python? | 842,856 | <p>I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice the list contains hundreds of entries. </p>
<p>I'm processing a string, and what I'm looking for is to find the index of first appearance of any of these substrings.</p>
<p>To clarify, for '012cat' the result is 3, and for '0123dog789cat' the result is 4. </p>
<p>I also need to know which substring was found (e.g. its index in the substring list or the text itself), or at least the length of the substring matched.</p>
<p>There are obvious brute-force ways to achieve this, I wondered if there's any elegant Python/Regex solution for this.</p>
<p>Thanks,
Rax</p>
| 21 | 2009-05-09T07:20:49Z | 842,955 | <p>How about this one.</p>
<pre><code>>>> substrings = ['cat', 'fish', 'dog']
>>> _string = '0123dog789cat'
>>> found = map(lambda x: (_string.index(x), x), filter(lambda x: x in _string, substrings))
[(10, 'cat'), (4, 'dog')]
>>> if found:
>>> min(found, key=lambda x: x[0])
(4, 'dog')
</code></pre>
<p>Obviously, you could return something other than a tuple.</p>
<p>This works by: </p>
<ul>
<li>Filtering the list of substrings down to those that are in the string</li>
<li>Building a list of tuples containing the index of the substring, and the substring</li>
<li>If a substring has been found, find the minimum value based on the index</li>
</ul>
| 0 | 2009-05-09T08:31:56Z | [
"python",
"regex",
"string",
"substring"
] |
What's the most efficient way to find one of several substrings in Python? | 842,856 | <p>I have a list of possible substrings, e.g. ['cat', 'fish', 'dog']. In practice the list contains hundreds of entries. </p>
<p>I'm processing a string, and what I'm looking for is to find the index of first appearance of any of these substrings.</p>
<p>To clarify, for '012cat' the result is 3, and for '0123dog789cat' the result is 4. </p>
<p>I also need to know which substring was found (e.g. its index in the substring list or the text itself), or at least the length of the substring matched.</p>
<p>There are obvious brute-force ways to achieve this, I wondered if there's any elegant Python/Regex solution for this.</p>
<p>Thanks,
Rax</p>
| 21 | 2009-05-09T07:20:49Z | 844,156 | <p>I just want to point out the time difference between DisplacedAussie's answer and Tom's answer. Both were fast when used once, so you shouldn't have any noticeable wait for either, but when you time them:</p>
<pre><code>import random
import re
import string
words = []
letters_and_digits = "%s%s" % (string.letters, string.digits)
for i in range(2000):
chars = []
for j in range(10):
chars.append(random.choice(letters_and_digits))
words.append(("%s"*10) % tuple(chars))
search_for = re.compile("|".join(words))
first, middle, last = words[0], words[len(words) / 2], words[-1]
search_string = "%s, %s, %s" % (last, middle, first)
def _search():
match_obj = search_for.search(search_string)
# Note, if no match, match_obj is None
if match_obj is not None:
return (match_obj.start(), match_obj.group())
def _map():
search_for = search_for.pattern.split("|")
found = map(lambda x: (search_string.index(x), x), filter(lambda x: x in search_string, search_for))
if found:
return min(found, key=lambda x: x[0])
if __name__ == '__main__':
from timeit import Timer
t = Timer("_search(search_for, search_string)", "from __main__ import _search, search_for, search_string")
print _search(search_for, search_string)
print t.timeit()
t = Timer("_map(search_for, search_string)", "from __main__ import _map, search_for, search_string")
print _map(search_for, search_string)
print t.timeit()
</code></pre>
<p>Outputs:</p>
<pre><code>(0, '841EzpjttV')
14.3660159111
(0, '841EzpjttV')
# I couldn't wait this long
</code></pre>
<p>I would go with Tom's answer, for both readability, and speed.</p>
| 3 | 2009-05-09T21:54:58Z | [
"python",
"regex",
"string",
"substring"
] |
How can I use Django admin list and filterering in my own views? | 843,182 | <p>Iâm just beginning to learn Django and I like the automatic listing in Django admin and the way you can configure filters and what columns to show. Is it possible to use it in my own applications?</p>
<p>Iâve looked in the source for the admin and figured out that I probably want to subclass the âChangeListâ-object in some way and use it in my own views. Any ideas?</p>
| 1 | 2009-05-09T12:05:13Z | 843,222 | <p>You're better off doing the following.</p>
<ol>
<li><p>Define a regular old Django query for your various kinds of filters. These are very easy to write.</p></li>
<li><p>Use the supplied <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/#list-detail-generic-views" rel="nofollow">generic</a> view functions. These are very easy to use.</p></li>
<li><p>Create your own templates with links to your filters. You'll be building a list links based on the results of a query. For a few hard-coded cases, this is very easy. In the super-general admin-interface case, this is not simple.</p></li>
</ol>
<p>Do this first. Get it to work. It won't take long. It's very important to understand Django at this level before diving into the way the admin applications work.</p>
<p>Later -- after you have something running -- you can spend several hours learning how the inner mysteries of the admin interface work.</p>
| 1 | 2009-05-09T12:32:50Z | [
"python",
"django",
"filter",
"django-views",
"django-queryset"
] |
How to render contents of a tag in unicode in BeautifulSoup? | 843,227 | <p>This is a soup from a WordPress post detail page:</p>
<pre><code>content = soup.body.find('div', id=re.compile('post'))
title = content.h2.extract()
item['title'] = unicode(title.string)
item['content'] = u''.join(map(unicode, content.contents))
</code></pre>
<p>I want to omit the enclosing <code>div</code> tag when assigning <code>item['content']</code>. Is there any way to render all the child tags of a tag in unicode? Something like:</p>
<pre><code>item['content'] = content.contents.__unicode__()
</code></pre>
<p>that will give me a single unicode string instead of a list.</p>
| 2 | 2009-05-09T12:38:38Z | 843,239 | <p>Have you tried:</p>
<pre><code>unicode(content)
</code></pre>
<p>It converts <code>content</code>'s markup to a single Unicode string.</p>
<p>Edit: If you don't want the enclosing tag, try:</p>
<pre><code>content.renderContents()
</code></pre>
| 6 | 2009-05-09T12:44:51Z | [
"python",
"xml",
"web-applications",
"screen-scraping",
"beautifulsoup"
] |
Logout or switch user in Windows using Python | 843,268 | <p>I want to write a small program that given a time (in minutes) as input, sleeps in the background for that time, and then forces a return to the "switch user screen" (equivalent to the Winkey+L combination) or logs off a user (may be another user logged in on the same machine).</p>
<p>What functions or libraries in Python could I use for this?</p>
<p>Edit: </p>
<ul>
<li>I prefer just a return to the "Switch User" screen rather than actually logging off</li>
<li>Perhaps there's a simple Windows command to do this, which I could use</li>
<li>I have Windows XP if that's relevant</li>
</ul>
| 1 | 2009-05-09T13:05:48Z | 843,280 | <p>Maybe you can use os.popen or <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> to run windows command line for logout.
I think logoff is the command. (According to this <a href="http://www.simplehelp.net/2006/09/12/windows-run-commands/" rel="nofollow">page</a>)</p>
| 1 | 2009-05-09T13:10:56Z | [
"python",
"windows"
] |
Logout or switch user in Windows using Python | 843,268 | <p>I want to write a small program that given a time (in minutes) as input, sleeps in the background for that time, and then forces a return to the "switch user screen" (equivalent to the Winkey+L combination) or logs off a user (may be another user logged in on the same machine).</p>
<p>What functions or libraries in Python could I use for this?</p>
<p>Edit: </p>
<ul>
<li>I prefer just a return to the "Switch User" screen rather than actually logging off</li>
<li>Perhaps there's a simple Windows command to do this, which I could use</li>
<li>I have Windows XP if that's relevant</li>
</ul>
| 1 | 2009-05-09T13:05:48Z | 843,294 | <p>I think you must use windows API, and run by python.
use os.system('logoff'); (or logout, I forget)
it is not tested, because I am using ubuntu now...</p>
| 0 | 2009-05-09T13:16:07Z | [
"python",
"windows"
] |
Logout or switch user in Windows using Python | 843,268 | <p>I want to write a small program that given a time (in minutes) as input, sleeps in the background for that time, and then forces a return to the "switch user screen" (equivalent to the Winkey+L combination) or logs off a user (may be another user logged in on the same machine).</p>
<p>What functions or libraries in Python could I use for this?</p>
<p>Edit: </p>
<ul>
<li>I prefer just a return to the "Switch User" screen rather than actually logging off</li>
<li>Perhaps there's a simple Windows command to do this, which I could use</li>
<li>I have Windows XP if that's relevant</li>
</ul>
| 1 | 2009-05-09T13:05:48Z | 843,298 | <p>There seems to be a simple way of locking a computer using no Python libraries except for ctypes:</p>
<pre><code>import ctypes
ctypes.windll.user32.LockWorkStation ()
</code></pre>
<p>Source: <a href="http://timgolden.me.uk/python/win32%5Fhow%5Fdo%5Fi/lock%5Fmy%5Fworkstation.html" rel="nofollow">Tim Golden's Python Stuff</a></p>
| 7 | 2009-05-09T13:18:10Z | [
"python",
"windows"
] |
Logout or switch user in Windows using Python | 843,268 | <p>I want to write a small program that given a time (in minutes) as input, sleeps in the background for that time, and then forces a return to the "switch user screen" (equivalent to the Winkey+L combination) or logs off a user (may be another user logged in on the same machine).</p>
<p>What functions or libraries in Python could I use for this?</p>
<p>Edit: </p>
<ul>
<li>I prefer just a return to the "Switch User" screen rather than actually logging off</li>
<li>Perhaps there's a simple Windows command to do this, which I could use</li>
<li>I have Windows XP if that's relevant</li>
</ul>
| 1 | 2009-05-09T13:05:48Z | 9,589,872 | <p>To switch users, you can use this <strong>Win32 API</strong> function <code>WTSDisconnectSession(HANDLE hServer, DWORD SessionId, BOOL bWait)</code></p>
<pre><code>#include "WtsApi32.h"
BOOL OsofemSwitchUser()
{
//Switch User
return WTSDisconnectSession(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, TRUE);
}
</code></pre>
<p>Remember to link it to the <code>WtsApi32.lib</code> library.<br/>
This will return you to the Switch User screen... Hope this help...</p>
| 1 | 2012-03-06T18:41:27Z | [
"python",
"windows"
] |
How do I check if a variable exists? | 843,277 | <p>I want to check if a variable exists. Now I'm doing something like this:</p>
<pre><code>try:
myVar
except NameError:
# Do something.
</code></pre>
<p>Are there other ways without exceptions?</p>
| 402 | 2009-05-09T13:10:31Z | 843,286 | <p><code>catch</code> is called <a href="http://docs.python.org/reference/compound%5Fstmts.html#the-try-statement" rel="nofollow"><code>except</code></a> in Python. other than that it's fine for such simple cases. There's the <a href="http://docs.python.org/library/exceptions.html#exceptions.AttributeError" rel="nofollow"><code>AttributeError</code></a> that can be used to check if an object has an attribute.</p>
| 4 | 2009-05-09T13:12:59Z | [
"python",
"exception",
"variables"
] |
How do I check if a variable exists? | 843,277 | <p>I want to check if a variable exists. Now I'm doing something like this:</p>
<pre><code>try:
myVar
except NameError:
# Do something.
</code></pre>
<p>Are there other ways without exceptions?</p>
| 402 | 2009-05-09T13:10:31Z | 843,293 | <p>To check the existence of a local variable:</p>
<pre><code>if 'myVar' in locals():
# myVar exists.
</code></pre>
<p>To check the existence of a global variable:</p>
<pre><code>if 'myVar' in globals():
# myVar exists.
</code></pre>
<p>To check if an object has an attribute:</p>
<pre><code>if hasattr(obj, 'attr_name'):
# obj.attr_name exists.
</code></pre>
| 735 | 2009-05-09T13:16:05Z | [
"python",
"exception",
"variables"
] |
How do I check if a variable exists? | 843,277 | <p>I want to check if a variable exists. Now I'm doing something like this:</p>
<pre><code>try:
myVar
except NameError:
# Do something.
</code></pre>
<p>Are there other ways without exceptions?</p>
| 402 | 2009-05-09T13:10:31Z | 843,306 | <p>The use of variables that haven't been defined is actually a bad thing in any language since it indicates that the logic of the program hasn't been thought through properly.</p>
<p>Python will assume you know what you're doing, otherwise you'd be using VB :-).</p>
<p>The following trick, which is similar to yours, will ensure that a variable has <em>some</em> value before use:</p>
<pre><code>try:
myVar
except NameError:
myVar = None
# Now you're free to use myVar without Python complaining.
</code></pre>
<p>However, I still don't think that's a good idea - in my opinion, you should refactor your code so that this situation does not occur.</p>
| 50 | 2009-05-09T13:19:28Z | [
"python",
"exception",
"variables"
] |
How do I check if a variable exists? | 843,277 | <p>I want to check if a variable exists. Now I'm doing something like this:</p>
<pre><code>try:
myVar
except NameError:
# Do something.
</code></pre>
<p>Are there other ways without exceptions?</p>
| 402 | 2009-05-09T13:10:31Z | 843,326 | <p>Using try/except is the best way to test for a variable's existence. But there's almost certainly a better way of doing whatever it is you're doing than setting/testing global variables.</p>
<p>For example, if you want to initialize a module-level variable the first time you call some function, you're better off with code something like this:</p>
<pre><code>my_variable = None
def InitMyVariable():
global my_variable
if my_variable is None:
my_variable = ...
</code></pre>
| 9 | 2009-05-09T13:27:55Z | [
"python",
"exception",
"variables"
] |
How do I check if a variable exists? | 843,277 | <p>I want to check if a variable exists. Now I'm doing something like this:</p>
<pre><code>try:
myVar
except NameError:
# Do something.
</code></pre>
<p>Are there other ways without exceptions?</p>
| 402 | 2009-05-09T13:10:31Z | 3,664,379 | <p>A way that often works well for handling this kind of situation is to not explicitly check if the variable exists but just go ahead and wrap the first usage of the possibly non-existing variable in a try/except NameError:</p>
<pre><code># Search for entry.
for x in y:
if x == 3:
found = x
# Work with found entry.
try:
print('Found: {0}'.format(found))
except NameError:
print('Not found')
else:
# Handle rest of Found case here
...
</code></pre>
| 3 | 2010-09-08T03:05:58Z | [
"python",
"exception",
"variables"
] |
How do I check if a variable exists? | 843,277 | <p>I want to check if a variable exists. Now I'm doing something like this:</p>
<pre><code>try:
myVar
except NameError:
# Do something.
</code></pre>
<p>Are there other ways without exceptions?</p>
| 402 | 2009-05-09T13:10:31Z | 22,645,635 | <p>I will assume that the test is going to be used in a function, similar to user97370's answer. I don't like that answer because it pollutes the global namespace. One way to fix it is to use a class instead:</p>
<pre><code>class InitMyVariable(object):
my_variable = None
def __call__(self):
if self.my_variable is None:
self. my_variable = ...
</code></pre>
<p>I don't like this, because it complicates the code and opens up questions such as, should this confirm to the Singleton programming pattern? Fortunately, Python has allowed functions to have attributes for a while, which gives us this simple solution:</p>
<pre><code>def InitMyVariable():
if InitMyVariable.my_variable is None:
InitMyVariable.my_variable = ...
InitMyVariable.my_variable = None
</code></pre>
| 1 | 2014-03-25T20:31:42Z | [
"python",
"exception",
"variables"
] |
How do I check if a variable exists? | 843,277 | <p>I want to check if a variable exists. Now I'm doing something like this:</p>
<pre><code>try:
myVar
except NameError:
# Do something.
</code></pre>
<p>Are there other ways without exceptions?</p>
| 402 | 2009-05-09T13:10:31Z | 26,616,037 | <p>for objects/modules, you can also </p>
<pre><code>'var' in dir(obj)
</code></pre>
<p>For example, </p>
<pre><code>>>> class Something(object):
... pass
...
>>> c = Something()
>>> c.a = 1
>>> 'a' in dir(c)
True
>>> 'b' in dir(c)
False
</code></pre>
| 5 | 2014-10-28T18:39:57Z | [
"python",
"exception",
"variables"
] |
How do I check if a variable exists? | 843,277 | <p>I want to check if a variable exists. Now I'm doing something like this:</p>
<pre><code>try:
myVar
except NameError:
# Do something.
</code></pre>
<p>Are there other ways without exceptions?</p>
| 402 | 2009-05-09T13:10:31Z | 30,651,757 | <p>A simple way is to initialize it at first saying <code>myVar = none;</code></p>
<p>Then later on: </p>
<pre><code>if myVar:
#Do something
</code></pre>
| 2 | 2015-06-04T18:46:22Z | [
"python",
"exception",
"variables"
] |
How do I check if a variable exists? | 843,277 | <p>I want to check if a variable exists. Now I'm doing something like this:</p>
<pre><code>try:
myVar
except NameError:
# Do something.
</code></pre>
<p>Are there other ways without exceptions?</p>
| 402 | 2009-05-09T13:10:31Z | 38,813,771 | <p>try:`</p>
<pre><code>Myvariable = ['v', 'a', 'r']
try:
print(Myvariable)
except Nameerror:
print('variable \"Myvariable\" not found')
</code></pre>
<p>hope this helps!</p>
| -2 | 2016-08-07T11:43:52Z | [
"python",
"exception",
"variables"
] |
Why is django giving error: no module named django.core? | 843,383 | <p>I get the error in question when I attempt to create a project. I followed the instructions found at <a href="http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/" rel="nofollow">how to install python an django in windows vista</a>.</p>
| 5 | 2009-05-09T14:06:16Z | 843,492 | <p>Most likely you don't have Django on your Python path. To test, quickly fire up Python and run:</p>
<pre><code>>>> import django
</code></pre>
<p>If that fails, it's just a matter of getting Django onto your Python path. Either you set the environment variable, or you move django into your <code>python2x/Lib/site-packages</code> directory. If it does work, try importing <code>core</code>. If that fails there, then something is probably wrong with your Django install.</p>
| 1 | 2009-05-09T15:26:58Z | [
"python",
"windows",
"django",
"django-admin"
] |
Why is django giving error: no module named django.core? | 843,383 | <p>I get the error in question when I attempt to create a project. I followed the instructions found at <a href="http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/" rel="nofollow">how to install python an django in windows vista</a>.</p>
| 5 | 2009-05-09T14:06:16Z | 843,530 | <p>Also make sure that you have permission to access all of django's files. I've seen these kinds of errors happen because of permissions issues before.</p>
<p><strong>EDIT</strong>: I haven't tried it out, but there's a link on that page to <a href="http://www.instantdjango.com/" rel="nofollow">Instant Django</a>, which looks like a pretty easy to set up.</p>
| 3 | 2009-05-09T15:52:07Z | [
"python",
"windows",
"django",
"django-admin"
] |
Why is django giving error: no module named django.core? | 843,383 | <p>I get the error in question when I attempt to create a project. I followed the instructions found at <a href="http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/" rel="nofollow">how to install python an django in windows vista</a>.</p>
| 5 | 2009-05-09T14:06:16Z | 2,172,331 | <p>You can get around this problem by providing the full path to your django-admin.py file</p>
<pre><code>python c:\python25\scripts\django-admin.py startproject mysite
</code></pre>
| 1 | 2010-01-31T16:09:14Z | [
"python",
"windows",
"django",
"django-admin"
] |
Why is django giving error: no module named django.core? | 843,383 | <p>I get the error in question when I attempt to create a project. I followed the instructions found at <a href="http://i.justrealized.com/2008/04/08/how-to-install-python-and-django-in-windows-vista/" rel="nofollow">how to install python an django in windows vista</a>.</p>
| 5 | 2009-05-09T14:06:16Z | 12,980,351 | <p>From your command line (<code>cmd</code>) run "ftype Python.File" and make sure that your .py files are being executed by the correct version/installation of Python. </p>
<p>It's possible another application has surreptitiously changed this under the hood.</p>
| 1 | 2012-10-19T18:32:36Z | [
"python",
"windows",
"django",
"django-admin"
] |
Python: get http headers from urllib call? | 843,392 | <p>does urllib fetch the whole page? when a urlopen call is made? </p>
<p>I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call?</p>
<pre><code>import urllib2
myurl = 'http://bit.ly/doFeT'
page = urllib2.urlopen(myurl) // open connection, get headers
html = page.readlines() // stream page
</code></pre>
| 36 | 2009-05-09T14:11:51Z | 843,401 | <p>What about sending a HEAD request instead of a normal GET request. The following snipped (copied from a similar <a href="http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python">question</a>) does exactly that. </p>
<pre><code>>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.com")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> print res.status, res.reason
200 OK
>>> print res.getheaders()
[('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]
</code></pre>
| 37 | 2009-05-09T14:17:34Z | [
"python",
"urllib",
"forwarding"
] |
Python: get http headers from urllib call? | 843,392 | <p>does urllib fetch the whole page? when a urlopen call is made? </p>
<p>I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call?</p>
<pre><code>import urllib2
myurl = 'http://bit.ly/doFeT'
page = urllib2.urlopen(myurl) // open connection, get headers
html = page.readlines() // stream page
</code></pre>
| 36 | 2009-05-09T14:11:51Z | 843,403 | <p>urllib2.urlopen does an HTTP GET (or POST if you supply a data argument), not an HTTP HEAD (if it did the latter, you couldn't do readlines or other accesses to the page body, of course).</p>
| 7 | 2009-05-09T14:18:33Z | [
"python",
"urllib",
"forwarding"
] |
Python: get http headers from urllib call? | 843,392 | <p>does urllib fetch the whole page? when a urlopen call is made? </p>
<p>I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call?</p>
<pre><code>import urllib2
myurl = 'http://bit.ly/doFeT'
page = urllib2.urlopen(myurl) // open connection, get headers
html = page.readlines() // stream page
</code></pre>
| 36 | 2009-05-09T14:11:51Z | 1,640,946 | <p>Use the <code>response.info()</code> method to get the headers.</p>
<p>From the <a href="http://docs.python.org/library/urllib2.html?highlight=urllib2#module-urllib2">urllib2 docs</a>:</p>
<blockquote>
<p>urllib2.urlopen(url[, data][, timeout])</p>
<p>...</p>
<p>This function returns a file-like object with two additional methods:</p>
<ul>
<li>geturl() â return the URL of the resource retrieved, commonly used to determine if a redirect was followed</li>
<li>info() â return the meta-information of the page, such as headers, in the form of an httplib.HTTPMessage instance (see Quick Reference to HTTP Headers)</li>
</ul>
</blockquote>
<p>So, for your example, try stepping through the result of <code>response.info().headers</code> for what you're looking for.</p>
<p>Note the major caveat to using httplib.HTTPMessage is documented in <a href="http://bugs.python.org/issue4773">python issue 4773</a>.</p>
| 36 | 2009-10-29T00:17:31Z | [
"python",
"urllib",
"forwarding"
] |
Python: get http headers from urllib call? | 843,392 | <p>does urllib fetch the whole page? when a urlopen call is made? </p>
<p>I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call?</p>
<pre><code>import urllib2
myurl = 'http://bit.ly/doFeT'
page = urllib2.urlopen(myurl) // open connection, get headers
html = page.readlines() // stream page
</code></pre>
| 36 | 2009-05-09T14:11:51Z | 9,350,032 | <p>Actually, it appears that urllib2 can do an HTTP HEAD request.</p>
<p>The <a href="http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python">question</a> that @reto linked to, above, shows how to get urllib2 to do a HEAD request.</p>
<p>Here's my take on it:</p>
<pre><code>import urllib2
# Derive from Request class and override get_method to allow a HEAD request.
class HeadRequest(urllib2.Request):
def get_method(self):
return "HEAD"
myurl = 'http://bit.ly/doFeT'
request = HeadRequest(myurl)
try:
response = urllib2.urlopen(request)
response_headers = response.info()
# This will just display all the dictionary key-value pairs. Replace this
# line with something useful.
response_headers.dict
except urllib2.HTTPError, e:
# Prints the HTTP Status code of the response but only if there was a
# problem.
print ("Error code: %s" % e.code)
</code></pre>
<p>If you check this with something like the Wireshark network protocol analazer, you can see that it is actually sending out a HEAD request, rather than a GET. </p>
<p>This is the HTTP request and response from the code above, as captured by Wireshark:</p>
<blockquote>
<p>HEAD /doFeT HTTP/1.1<br/> Accept-Encoding: identity<br/> Host:
bit.ly<br/> Connection: close<br/> User-Agent: Python-urllib/2.7<br/></p>
<p>HTTP/1.1 301 Moved<br/> Server: nginx<br/> Date: Sun, 19 Feb 2012
13:20:56 GMT<br/> Content-Type: text/html; charset=utf-8<br/>
Cache-control: private; max-age=90<br/> Location:
<a href="http://www.kidsidebyside.org/?p=445">http://www.kidsidebyside.org/?p=445</a><br/> MIME-Version: 1.0<br/>
Content-Length: 127<br/> Connection: close<br/> Set-Cookie:
_bit=4f40f738-00153-02ed0-421cf10a;domain=.bit.ly;expires=Fri Aug 17 13:20:56 2012;path=/; HttpOnly<br/></p>
</blockquote>
<p>However, as mentioned in one of the comments in the other question, if the URL in question includes a redirect then urllib2 will do a GET request to the destination, not a HEAD. This could be a major shortcoming, if you really wanted to only make HEAD requests.</p>
<p>The request above involves a redirect. Here is request to the destination, as captured by Wireshark:</p>
<blockquote>
<p>GET /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1<br/>
Accept-Encoding: identity<br/> Host: www.kidsidebyside.org<br/>
Connection: close<br/> User-Agent: Python-urllib/2.7<br/></p>
</blockquote>
<p>An alternative to using urllib2 is to use Joe Gregorio's <a href="http://code.google.com/p/httplib2/">httplib2</a> library:</p>
<pre><code>import httplib2
url = "http://bit.ly/doFeT"
http_interface = httplib2.Http()
try:
response, content = http_interface.request(url, method="HEAD")
print ("Response status: %d - %s" % (response.status, response.reason))
# This will just display all the dictionary key-value pairs. Replace this
# line with something useful.
response.__dict__
except httplib2.ServerNotFoundError, e:
print (e.message)
</code></pre>
<p>This has the advantage of using HEAD requests for both the initial HTTP request and the redirected request to the destination URL.</p>
<p>Here's the first request:</p>
<blockquote>
<p>HEAD /doFeT HTTP/1.1<br/> Host: bit.ly<br/> accept-encoding: gzip,
deflate<br/> user-agent: Python-httplib2/0.7.2 (gzip)<br/></p>
</blockquote>
<p>Here's the second request, to the destination:</p>
<blockquote>
<p>HEAD /2009/05/come-and-draw-the-circle-of-unity-with-us/ HTTP/1.1<br/>
Host: www.kidsidebyside.org<br/> accept-encoding: gzip, deflate<br/>
user-agent: Python-httplib2/0.7.2 (gzip)<br/></p>
</blockquote>
| 15 | 2012-02-19T14:27:46Z | [
"python",
"urllib",
"forwarding"
] |
Python: get http headers from urllib call? | 843,392 | <p>does urllib fetch the whole page? when a urlopen call is made? </p>
<p>I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call?</p>
<pre><code>import urllib2
myurl = 'http://bit.ly/doFeT'
page = urllib2.urlopen(myurl) // open connection, get headers
html = page.readlines() // stream page
</code></pre>
| 36 | 2009-05-09T14:11:51Z | 9,939,222 | <p>One-liner:</p>
<pre><code>$ python -c "import urllib2; print urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)).open(urllib2.Request('http://google.com'))"
</code></pre>
| 3 | 2012-03-30T08:11:23Z | [
"python",
"urllib",
"forwarding"
] |
Python: get http headers from urllib call? | 843,392 | <p>does urllib fetch the whole page? when a urlopen call is made? </p>
<p>I'd like to just read the http response header without getting the page it looks like urllib opens the http connection and then subsequently gets the actual html page... or does it just start buffering the page with the url open call?</p>
<pre><code>import urllib2
myurl = 'http://bit.ly/doFeT'
page = urllib2.urlopen(myurl) // open connection, get headers
html = page.readlines() // stream page
</code></pre>
| 36 | 2009-05-09T14:11:51Z | 24,992,147 | <pre><code>def _GetHtmlPage(self, addr):
headers = { 'User-Agent' : self.userAgent,
' Cookie' : self.cookies}
req = urllib2.Request(addr)
response = urllib2.urlopen(req)
print "ResponseInfo="
print response.info()
resultsHtml = unicode(response.read(), self.encoding)
return resultsHtml
</code></pre>
| -1 | 2014-07-28T09:25:02Z | [
"python",
"urllib",
"forwarding"
] |
Barchart (o plot) 3D in Python | 843,449 | <p>I need to plot some data in various forms. Currently I'm using <a href="http://en.wikipedia.org/wiki/Matplotlib" rel="nofollow">Matplotlib</a> and I'm fairly happy with the plots I'm able to produce.</p>
<p>This question is on how to plot the last one. The data is similar to the "distance table", like <a href="http://www.southernct.edu/wellness/uploads/textWidget/wysiwyg/documents/Campus_Walking_Map__Distance_Chart.pdf" rel="nofollow">this</a> (just bigger, my table is 128x128 and still have 3 or more number per element).</p>
<p>Now, my data is much better "structured" than a distance table (my data doesn't varies "randomly" like in a alphabetically sorted distance table), thus a 3D <a href="http://www.scipy.org/Cookbook/Matplotlib/BarCharts" rel="nofollow">barchart</a>, or maybe 3 of them, would be perfect. My understanding is that such a chart is missing in Matplotlib.</p>
<p>I could use a (colored) Countor3d like <a href="http://www.scipy.org/Cookbook/Matplotlib/mplot3D" rel="nofollow">these</a> or something in 2D like imshow, but it isn't really well representative of what the data is (the data has meaning just in my 128 points, there isn't anything between two points). And the height of bars is more readable than color, IMO.</p>
<p>Thus the questions:</p>
<ol>
<li>is it possible to create 3D barchart in Matplotlib? It should be clear that I mean with a 2D domain, not just a 2D barchart with a "fake" 3D rendering for aesthetics purposes</li>
<li>if the answer to the previous question is no, then is there some other library able to do that? I strongly prefer something Python-based, but I'm OK with other Linux-friendly possibilities</li>
<li>if the answer to the previous question is no, then do you have any suggestions on how to show that data? E.g. create a table with the values, superimposed to the imshow or other colored way?</li>
</ol>
| 6 | 2009-05-09T14:53:16Z | 843,561 | <p><a href="http://code.enthought.com/projects/mayavi/" rel="nofollow">MyavaVi2</a> can make <a href="http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html#d-data" rel="nofollow">3D barcharts</a> (scroll down a bit). Once you have <a href="http://en.wikipedia.org/wiki/MayaVi" rel="nofollow">MayaVi</a>/<a href="http://en.wikipedia.org/wiki/VTK" rel="nofollow">VTK</a>/<a href="http://en.wikipedia.org/wiki/Enthought" rel="nofollow">ETS</a>/etc. installed it all works beautifully, but it can be some work getting it all installed. Ubuntu has all of it packaged, but they're the only Linux distribution I know that does.</p>
| 5 | 2009-05-09T16:10:51Z | [
"python",
"matplotlib",
"plot",
"3d"
] |
Barchart (o plot) 3D in Python | 843,449 | <p>I need to plot some data in various forms. Currently I'm using <a href="http://en.wikipedia.org/wiki/Matplotlib" rel="nofollow">Matplotlib</a> and I'm fairly happy with the plots I'm able to produce.</p>
<p>This question is on how to plot the last one. The data is similar to the "distance table", like <a href="http://www.southernct.edu/wellness/uploads/textWidget/wysiwyg/documents/Campus_Walking_Map__Distance_Chart.pdf" rel="nofollow">this</a> (just bigger, my table is 128x128 and still have 3 or more number per element).</p>
<p>Now, my data is much better "structured" than a distance table (my data doesn't varies "randomly" like in a alphabetically sorted distance table), thus a 3D <a href="http://www.scipy.org/Cookbook/Matplotlib/BarCharts" rel="nofollow">barchart</a>, or maybe 3 of them, would be perfect. My understanding is that such a chart is missing in Matplotlib.</p>
<p>I could use a (colored) Countor3d like <a href="http://www.scipy.org/Cookbook/Matplotlib/mplot3D" rel="nofollow">these</a> or something in 2D like imshow, but it isn't really well representative of what the data is (the data has meaning just in my 128 points, there isn't anything between two points). And the height of bars is more readable than color, IMO.</p>
<p>Thus the questions:</p>
<ol>
<li>is it possible to create 3D barchart in Matplotlib? It should be clear that I mean with a 2D domain, not just a 2D barchart with a "fake" 3D rendering for aesthetics purposes</li>
<li>if the answer to the previous question is no, then is there some other library able to do that? I strongly prefer something Python-based, but I'm OK with other Linux-friendly possibilities</li>
<li>if the answer to the previous question is no, then do you have any suggestions on how to show that data? E.g. create a table with the values, superimposed to the imshow or other colored way?</li>
</ol>
| 6 | 2009-05-09T14:53:16Z | 843,640 | <p>For some time now, matplotlib had no 3D support, but it has been added back <a href="http://thread.gmane.org/gmane.comp.python.matplotlib.devel/6762/focus=6820" rel="nofollow">recently</a>. You will need to use the svn version, since no release has been made since, and the documentation is a little sparse (see examples/mplot3d/demo.py). I don't know if mplot3d supports real 3D bar charts, but one of the demos looks a little like it could be extended to something like that.</p>
<p>Edit: The source code for the demo is in <a href="http://matplotlib.sourceforge.net/examples/mplot3d/demo.html" rel="nofollow">the examples</a> but for some reason the result is not. I mean the <code>test_polys</code> function, and here's how it looks like:</p>
<p><img src="http://www.iki.fi/jks/tmp/poly3d.png" alt="example figure" title="" /></p>
<p>The <code>test_bar2D</code> function would be even better, but it's commented out in the demo as it causes an error with the current svn version. Might be some trivial problem, or something that's harder to fix.</p>
| 7 | 2009-05-09T16:56:07Z | [
"python",
"matplotlib",
"plot",
"3d"
] |
Barchart (o plot) 3D in Python | 843,449 | <p>I need to plot some data in various forms. Currently I'm using <a href="http://en.wikipedia.org/wiki/Matplotlib" rel="nofollow">Matplotlib</a> and I'm fairly happy with the plots I'm able to produce.</p>
<p>This question is on how to plot the last one. The data is similar to the "distance table", like <a href="http://www.southernct.edu/wellness/uploads/textWidget/wysiwyg/documents/Campus_Walking_Map__Distance_Chart.pdf" rel="nofollow">this</a> (just bigger, my table is 128x128 and still have 3 or more number per element).</p>
<p>Now, my data is much better "structured" than a distance table (my data doesn't varies "randomly" like in a alphabetically sorted distance table), thus a 3D <a href="http://www.scipy.org/Cookbook/Matplotlib/BarCharts" rel="nofollow">barchart</a>, or maybe 3 of them, would be perfect. My understanding is that such a chart is missing in Matplotlib.</p>
<p>I could use a (colored) Countor3d like <a href="http://www.scipy.org/Cookbook/Matplotlib/mplot3D" rel="nofollow">these</a> or something in 2D like imshow, but it isn't really well representative of what the data is (the data has meaning just in my 128 points, there isn't anything between two points). And the height of bars is more readable than color, IMO.</p>
<p>Thus the questions:</p>
<ol>
<li>is it possible to create 3D barchart in Matplotlib? It should be clear that I mean with a 2D domain, not just a 2D barchart with a "fake" 3D rendering for aesthetics purposes</li>
<li>if the answer to the previous question is no, then is there some other library able to do that? I strongly prefer something Python-based, but I'm OK with other Linux-friendly possibilities</li>
<li>if the answer to the previous question is no, then do you have any suggestions on how to show that data? E.g. create a table with the values, superimposed to the imshow or other colored way?</li>
</ol>
| 6 | 2009-05-09T14:53:16Z | 846,214 | <p>You might check out Chart Director:</p>
<blockquote>
<p><a href="http://www.advsofteng.com" rel="nofollow">http://www.advsofteng.com</a></p>
</blockquote>
<p>It has a pretty wide variety of charts and graphs and has a nice Python (and several other languages) API.</p>
<p>There are two editions: The free version puts a blurb on the generated image, and the
pay version is pretty reasonably priced.</p>
<p>Here's one of the more interesting looking 3d stacked bar charts:</p>
<p><img src="http://www.advsofteng.com/images/demo10.png" alt="sample graph"></p>
| 0 | 2009-05-10T22:09:16Z | [
"python",
"matplotlib",
"plot",
"3d"
] |
Barchart (o plot) 3D in Python | 843,449 | <p>I need to plot some data in various forms. Currently I'm using <a href="http://en.wikipedia.org/wiki/Matplotlib" rel="nofollow">Matplotlib</a> and I'm fairly happy with the plots I'm able to produce.</p>
<p>This question is on how to plot the last one. The data is similar to the "distance table", like <a href="http://www.southernct.edu/wellness/uploads/textWidget/wysiwyg/documents/Campus_Walking_Map__Distance_Chart.pdf" rel="nofollow">this</a> (just bigger, my table is 128x128 and still have 3 or more number per element).</p>
<p>Now, my data is much better "structured" than a distance table (my data doesn't varies "randomly" like in a alphabetically sorted distance table), thus a 3D <a href="http://www.scipy.org/Cookbook/Matplotlib/BarCharts" rel="nofollow">barchart</a>, or maybe 3 of them, would be perfect. My understanding is that such a chart is missing in Matplotlib.</p>
<p>I could use a (colored) Countor3d like <a href="http://www.scipy.org/Cookbook/Matplotlib/mplot3D" rel="nofollow">these</a> or something in 2D like imshow, but it isn't really well representative of what the data is (the data has meaning just in my 128 points, there isn't anything between two points). And the height of bars is more readable than color, IMO.</p>
<p>Thus the questions:</p>
<ol>
<li>is it possible to create 3D barchart in Matplotlib? It should be clear that I mean with a 2D domain, not just a 2D barchart with a "fake" 3D rendering for aesthetics purposes</li>
<li>if the answer to the previous question is no, then is there some other library able to do that? I strongly prefer something Python-based, but I'm OK with other Linux-friendly possibilities</li>
<li>if the answer to the previous question is no, then do you have any suggestions on how to show that data? E.g. create a table with the values, superimposed to the imshow or other colored way?</li>
</ol>
| 6 | 2009-05-09T14:53:16Z | 852,343 | <p>One more possibility is Gnuplot, which can draw some kind of <a href="http://t16web.lanl.gov/Kawano/gnuplot/plotpm3d-e.html#6.9" rel="nofollow">pseudo 3D bar charts</a>, and <a href="http://gnuplot-py.sourceforge.net/" rel="nofollow">gnuplot.py</a> allows interfacing to Gnuplot from Python. I have not tried it myself, though.</p>
| 5 | 2009-05-12T11:50:19Z | [
"python",
"matplotlib",
"plot",
"3d"
] |
Barchart (o plot) 3D in Python | 843,449 | <p>I need to plot some data in various forms. Currently I'm using <a href="http://en.wikipedia.org/wiki/Matplotlib" rel="nofollow">Matplotlib</a> and I'm fairly happy with the plots I'm able to produce.</p>
<p>This question is on how to plot the last one. The data is similar to the "distance table", like <a href="http://www.southernct.edu/wellness/uploads/textWidget/wysiwyg/documents/Campus_Walking_Map__Distance_Chart.pdf" rel="nofollow">this</a> (just bigger, my table is 128x128 and still have 3 or more number per element).</p>
<p>Now, my data is much better "structured" than a distance table (my data doesn't varies "randomly" like in a alphabetically sorted distance table), thus a 3D <a href="http://www.scipy.org/Cookbook/Matplotlib/BarCharts" rel="nofollow">barchart</a>, or maybe 3 of them, would be perfect. My understanding is that such a chart is missing in Matplotlib.</p>
<p>I could use a (colored) Countor3d like <a href="http://www.scipy.org/Cookbook/Matplotlib/mplot3D" rel="nofollow">these</a> or something in 2D like imshow, but it isn't really well representative of what the data is (the data has meaning just in my 128 points, there isn't anything between two points). And the height of bars is more readable than color, IMO.</p>
<p>Thus the questions:</p>
<ol>
<li>is it possible to create 3D barchart in Matplotlib? It should be clear that I mean with a 2D domain, not just a 2D barchart with a "fake" 3D rendering for aesthetics purposes</li>
<li>if the answer to the previous question is no, then is there some other library able to do that? I strongly prefer something Python-based, but I'm OK with other Linux-friendly possibilities</li>
<li>if the answer to the previous question is no, then do you have any suggestions on how to show that data? E.g. create a table with the values, superimposed to the imshow or other colored way?</li>
</ol>
| 6 | 2009-05-09T14:53:16Z | 34,894,803 | <p>This is my code for a simple Bar-3d using matplotlib. </p>
<pre><code>import mpl_toolkits
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
%matplotlib inline
## The value you want to plot
zval=[0.020752244,0.078514652,0.170302899,0.29543857,0.45358061,0.021255922,0.079022499,\
0.171294169,0.29749654,0.457114286,0.020009631,0.073154019,0.158043498,0.273889264,0.419618287]
fig = plt.figure(figsize=(12,9))
ax = fig.add_subplot(111,projection='3d')
col=["#ccebc5","#b3cde3","#fbb4ae"]*5
xpos=[1,2,3]*5
ypos=range(1,6,1)*5
zpos=[0]*15
dx=[0.4]*15
dy=[0.5]*15
dz=zval
for i in range(0,15,1):
ax.bar3d(ypos[i], xpos[i], zpos[i], dx[i], dy[i], dz[i],
color=col[i],alpha=0.75)
ax.view_init(azim=120)
plt.show()
</code></pre>
<p><img src="http://i8.tietuku.com/ea79b55837914ab2.png" alt=""></p>
| 1 | 2016-01-20T08:19:08Z | [
"python",
"matplotlib",
"plot",
"3d"
] |
How does garbage collection in Python work with class methods? | 843,459 | <pre><code>class example:
def exampleMethod(self):
aVar = 'some string'
return aVar
</code></pre>
<p>In this example, how does garbage collection work after each call to example.exampleMethod()? Will aVar be deallocated once the method returns?</p>
| 3 | 2009-05-09T15:03:38Z | 843,489 | <p>The variable is never deallocated.</p>
<p>The object (in this case a string, with a value of <code>'some string'</code> is reused again and again, so that object can never be deallocated.</p>
<p>Objects are deallocated when no variable refers to the object. Think of this.</p>
<pre><code>a = 'hi mom'
a = 'next value'
</code></pre>
<p>In this case, the first object (a string with the value <code>'hi mom'</code>) is no longer referenced anywhere in the script when the second statement is executed. The object (<code>'hi mom'</code>) can be removed from memory.</p>
| 6 | 2009-05-09T15:22:55Z | [
"python",
"garbage-collection"
] |
How does garbage collection in Python work with class methods? | 843,459 | <pre><code>class example:
def exampleMethod(self):
aVar = 'some string'
return aVar
</code></pre>
<p>In this example, how does garbage collection work after each call to example.exampleMethod()? Will aVar be deallocated once the method returns?</p>
| 3 | 2009-05-09T15:03:38Z | 843,498 | <p>Every time You assign an object to a variable, You increase this object's reference counter.</p>
<pre><code>a = MyObject() # +1, so it's at 1
b = a # +1, so it's now 2
a = 'something else' # -1, so it's 1
b = 'something else' # -1, so it's 0
</code></pre>
<p>Noone can access this the MyObject object We have created at the first line anymore.</p>
<p>When the counter reaches zero, the garbage collector frees the memory.</p>
<p>There is a way to make a tricky reference that does not increase reference counter (f.e. if You don't want an object to be hold in memory just because it's in some cache dict).</p>
<p>More on cPython's reference counting can be found <a href="http://www.python.org/doc/2.5.2/ext/refcounts.html" rel="nofollow">here</a>.</p>
<p>Python is language, cPython is it's (quite popular) implementation. Afaik the language itself doesn't specify <em>how</em> the memory is freed.</p>
| 4 | 2009-05-09T15:31:25Z | [
"python",
"garbage-collection"
] |
How does garbage collection in Python work with class methods? | 843,459 | <pre><code>class example:
def exampleMethod(self):
aVar = 'some string'
return aVar
</code></pre>
<p>In this example, how does garbage collection work after each call to example.exampleMethod()? Will aVar be deallocated once the method returns?</p>
| 3 | 2009-05-09T15:03:38Z | 843,525 | <p>From your example, if you call example.exampleMethod() , without assigning the results (eg. <code>a = example.exampleMethod()</code>) then it will be deallocated straight away (in CPython), as CPython uses a reference counting mechanism. Strings aren't a very good example to use, because they also have a number of implementation specific optimizations. Strings can be cached, and are not deallocated so that they can be reused. This is especially useful because strings are very common for use as keys in dicts.</p>
<p>Again, garbage collecting is specific to the implementations, so CPython, Jython and IronPython will have different behaviours, most of these being documented on the respective sites/manuals/code/etc. If you want to explore a bit, I'd suggest creating a class where you have defined the <strong>del</strong>() method, which will be called upon the object being garbage collected (it's the destructor). Make it print something so you can trace it's call :)</p>
| 3 | 2009-05-09T15:50:36Z | [
"python",
"garbage-collection"
] |
How does garbage collection in Python work with class methods? | 843,459 | <pre><code>class example:
def exampleMethod(self):
aVar = 'some string'
return aVar
</code></pre>
<p>In this example, how does garbage collection work after each call to example.exampleMethod()? Will aVar be deallocated once the method returns?</p>
| 3 | 2009-05-09T15:03:38Z | 843,579 | <p>As in Nico's answer, it depends on what you do with the result returned by exampleMethod. Python (or CPython anyway) uses reference counting. During the method, aVar references the string, while after that the variable aVar is deleted, which may leave no references, in which case, it is deleted.</p>
<p>Below is an example with a custom class that has a destructor (<strong>del</strong>(self), that print out "Object 1 being destructed" or similar. The gc is the garbage collector module, that automatically deletes objects with a reference count of 0. It's there for convenience, as otherwise there is no guarantee when the garbage collector is run. </p>
<pre><code>import gc
class Noisy(object):
def __init__(self, n):
self.n = n
def __del__(self):
print "Object " + str(self.n) + " being destructed"
class example(object):
def exampleMethod(self, n):
aVar = Noisy(n)
return aVar
a = example()
a.exampleMethod(1)
b = a.exampleMethod(2)
gc.collect()
print "Before b is deleted"
del b
gc.collect()
print "After b is deleted"
</code></pre>
<p>The result should be as follows:</p>
<pre><code>Object 1 being destructed
While b lives
Object 2 being destructed
After b is deleted
</code></pre>
<p>Notice that the first Noisy object is deleted after the method is returned, as it is not assigned to a variable, so has a reference count of 0, but the second one is deleted only after the variable b is deleted, leaving a reference count of 0.</p>
| 0 | 2009-05-09T16:23:19Z | [
"python",
"garbage-collection"
] |
Using virtualenv on Mac OS X | 843,531 | <p>I've been using virtualenv on Ubuntu and it rocks, so I'm trying to use it on my Mac and I'm having trouble.</p>
<p>The <code>virtualenv</code> command successfully creates the directory, and <code>easy_install</code> gladly installs packages in it, but I can't import anything I install. It seems like <code>sys.path</code> isn't being set correctly: it doesn't include the virtual <code>site-packages</code>, even if I use the <code>--no-site-packages</code> option. Am I doing something wrong?</p>
<p>I'm using Python 2.5.1 and virtualenv 1.3.3 on Mac OS 10.5.6</p>
<p><strong>Edit</strong>: Here's what happens when I try to use virtualenv:</p>
<pre><code>$ virtualenv test
New python executable in test/bin/python
Installing setuptools............done.
$ source test/bin/activate
(test)$ which python
/Users/Justin/test/bin/python
(test)$ which easy_install
/Users/Justin/test/bin/easy_install
(test)$ easy_install webcolors
[...]
Installed /Users/Justin/test/lib/python2.5/site-packages/webcolors-1.3-py2.5.egg
Processing dependencies for webcolors
Finished processing dependencies for webcolors
(test)$ python
[...]
>>> import webcolors
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named webcolors
>>> import sys
>>> print sys.path
['',
'/Library/Python/2.5/site-packages/SQLObject-0.10.2-py2.5.egg',
'/Library/Python/2.5/site-packages/FormEncode-1.0.1-py2.5.egg',
...,
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5',
'/Users/Justin/test/lib/python25.zip',
'/Users/Justin/test/lib/python2.5',
'/Users/Justin/test/lib/python2.5/plat-darwin',
'/Users/Justin/test/lib/python2.5/plat-mac',
'/Users/Justin/test/lib/python2.5/plat-mac/lib-scriptpackages',
'/Users/Justin/test/Extras/lib/python',
'/Users/Justin/test/lib/python2.5/lib-tk',
'/Users/Justin/test/lib/python2.5/lib-dynload',
'/Library/Python/2.5/site-packages',
'/Library/Python/2.5/site-packages/PIL']
</code></pre>
<p><strong>Edit 2</strong>: Using the <code>activate_this.py</code> script works, but running <code>source bin/activate</code> does not. Hopefully that helps narrow down the problem?</p>
| 2 | 2009-05-09T15:53:02Z | 843,539 | <p>I've not had any problems with the same OS X/Python/virtualenv version (OS X 10.5.6, Python 2.5.1, virtualenv 1.3.1)</p>
<pre><code>$ virtualenv test
New python executable in test/bin/python
Installing setuptools............done.
$ source test/bin/activate
(test)$ which python
/Users/dbr/test/bin/python
$ echo $PATH
/Users/dbr/test/bin:/usr/bin:[...]
$ python
[...]
>>> import sys
>>> print sys.path
['', '/Users/dbr/test/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg',
</code></pre>
<p>One thing to check - in a clean shell, run the following:</p>
<pre><code>$ virtualenv test
$ python
[...]
>>> import sys
>>> sys.path
['', '/Library/Python/2.5/site-packages/elementtree-1.2.7_20070827_preview-py2.5.egg'[...]
>>> sys.path.append("test/bin/")
>>> import activate_this
>>> sys.path
['/Users/dbr/test/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg'
</code></pre>
<p>Or from the virtualenv docs:</p>
<pre><code>activate_this = '/path/to/env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
</code></pre>
<p>That should force the current Python shell into the virtualenv</p>
<p>Also, after running <code>source test/bin/activate</code> try running python with the <code>-v</code> flag (verbose), it may produce something useful.</p>
| 5 | 2009-05-09T16:00:13Z | [
"python",
"osx",
"virtualenv"
] |
Using virtualenv on Mac OS X | 843,531 | <p>I've been using virtualenv on Ubuntu and it rocks, so I'm trying to use it on my Mac and I'm having trouble.</p>
<p>The <code>virtualenv</code> command successfully creates the directory, and <code>easy_install</code> gladly installs packages in it, but I can't import anything I install. It seems like <code>sys.path</code> isn't being set correctly: it doesn't include the virtual <code>site-packages</code>, even if I use the <code>--no-site-packages</code> option. Am I doing something wrong?</p>
<p>I'm using Python 2.5.1 and virtualenv 1.3.3 on Mac OS 10.5.6</p>
<p><strong>Edit</strong>: Here's what happens when I try to use virtualenv:</p>
<pre><code>$ virtualenv test
New python executable in test/bin/python
Installing setuptools............done.
$ source test/bin/activate
(test)$ which python
/Users/Justin/test/bin/python
(test)$ which easy_install
/Users/Justin/test/bin/easy_install
(test)$ easy_install webcolors
[...]
Installed /Users/Justin/test/lib/python2.5/site-packages/webcolors-1.3-py2.5.egg
Processing dependencies for webcolors
Finished processing dependencies for webcolors
(test)$ python
[...]
>>> import webcolors
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named webcolors
>>> import sys
>>> print sys.path
['',
'/Library/Python/2.5/site-packages/SQLObject-0.10.2-py2.5.egg',
'/Library/Python/2.5/site-packages/FormEncode-1.0.1-py2.5.egg',
...,
'/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5',
'/Users/Justin/test/lib/python25.zip',
'/Users/Justin/test/lib/python2.5',
'/Users/Justin/test/lib/python2.5/plat-darwin',
'/Users/Justin/test/lib/python2.5/plat-mac',
'/Users/Justin/test/lib/python2.5/plat-mac/lib-scriptpackages',
'/Users/Justin/test/Extras/lib/python',
'/Users/Justin/test/lib/python2.5/lib-tk',
'/Users/Justin/test/lib/python2.5/lib-dynload',
'/Library/Python/2.5/site-packages',
'/Library/Python/2.5/site-packages/PIL']
</code></pre>
<p><strong>Edit 2</strong>: Using the <code>activate_this.py</code> script works, but running <code>source bin/activate</code> does not. Hopefully that helps narrow down the problem?</p>
| 2 | 2009-05-09T15:53:02Z | 895,855 | <p>It turns out that my problems with virtualenv were my own fault: I had configured my <code>.bash_profile</code> to muck with the <code>PYTHONPATH</code> environment variable, which caused the import problems.</p>
<p>Thank you to everyone who took the time to answer; sorry for not investigating the problem further on my own.</p>
| 1 | 2009-05-21T23:54:38Z | [
"python",
"osx",
"virtualenv"
] |
Parse JavaScript to instrument code | 843,546 | <p>I need to split a JavaScript file into single instructions. For example</p>
<pre><code>a = 2;
foo()
function bar() {
b = 5;
print("spam");
}
</code></pre>
<p>has to be separated into three instructions. (assignment, function call and function definition).</p>
<p>Basically I need to instrument the code, injecting code between these instructions to perform checks. Splitting by ";" wouldn't obviously work because you can also end instructions with newlines and maybe I don't want to instrument code inside function and class definitions (I don't know yet). I took a course about grammars with <a href="http://en.wikipedia.org/wiki/Flex_lexical_analyser" rel="nofollow">flex</a>/<a href="http://en.wikipedia.org/wiki/GNU_bison" rel="nofollow">Bison</a> but in this case the semantic action for this rule would be "print all the descendants in the parse tree and put my code at the end" which can't be done with basic Bison I think. How do I do this? I also need to split the code because I need to interface with Python with python-spidermonkey.
Or... is there a library out there already which saves me from reinventing the wheel? It doesn't have to be in Python.</p>
| 7 | 2009-05-09T16:05:33Z | 843,591 | <p>Why not use a JavaScript parser? There are lots, including a Python API for ANTLR and a Python wrapper around SpiderMonkey.</p>
| 4 | 2009-05-09T16:28:39Z | [
"javascript",
"python",
"parsing",
"spidermonkey"
] |
Parse JavaScript to instrument code | 843,546 | <p>I need to split a JavaScript file into single instructions. For example</p>
<pre><code>a = 2;
foo()
function bar() {
b = 5;
print("spam");
}
</code></pre>
<p>has to be separated into three instructions. (assignment, function call and function definition).</p>
<p>Basically I need to instrument the code, injecting code between these instructions to perform checks. Splitting by ";" wouldn't obviously work because you can also end instructions with newlines and maybe I don't want to instrument code inside function and class definitions (I don't know yet). I took a course about grammars with <a href="http://en.wikipedia.org/wiki/Flex_lexical_analyser" rel="nofollow">flex</a>/<a href="http://en.wikipedia.org/wiki/GNU_bison" rel="nofollow">Bison</a> but in this case the semantic action for this rule would be "print all the descendants in the parse tree and put my code at the end" which can't be done with basic Bison I think. How do I do this? I also need to split the code because I need to interface with Python with python-spidermonkey.
Or... is there a library out there already which saves me from reinventing the wheel? It doesn't have to be in Python.</p>
| 7 | 2009-05-09T16:05:33Z | 843,593 | <p>Why not use an existing JavaScript interpreter like <a href="http://www.mozilla.org/rhino/" rel="nofollow">Rhino</a> (Java) or <a href="http://pypi.python.org/pypi/python-spidermonkey" rel="nofollow">python-spidermonkey</a> (not sure whether this one is still alive)? It will parse the JS and then you can examine the resulting parse tree. I'm not sure how easy it will be to recreate the original code but that mostly depends on how readable the instrumented code must be. If no one ever looks at it, just generate a really compact form.</p>
<p><a href="http://pyjamas.sourceforge.net/" rel="nofollow">pyjamas</a> might also be of interest; this is a Python to JavaScript transpiler. </p>
<p>[EDIT] While this doesn't solve your problem at first glance, you might use it for a different approach: Instead of instrumenting JavaScript, write your code in Python instead (which can be easily instrumented; all the tools are already there) and then convert the result to JavaScript.</p>
<p>Lastly, if you want to solve your problem in Python but can't find a parser: Use a Java engine to add comments to the code which you can then search for in Python to instrument the code.</p>
| 0 | 2009-05-09T16:29:54Z | [
"javascript",
"python",
"parsing",
"spidermonkey"
] |
Parse JavaScript to instrument code | 843,546 | <p>I need to split a JavaScript file into single instructions. For example</p>
<pre><code>a = 2;
foo()
function bar() {
b = 5;
print("spam");
}
</code></pre>
<p>has to be separated into three instructions. (assignment, function call and function definition).</p>
<p>Basically I need to instrument the code, injecting code between these instructions to perform checks. Splitting by ";" wouldn't obviously work because you can also end instructions with newlines and maybe I don't want to instrument code inside function and class definitions (I don't know yet). I took a course about grammars with <a href="http://en.wikipedia.org/wiki/Flex_lexical_analyser" rel="nofollow">flex</a>/<a href="http://en.wikipedia.org/wiki/GNU_bison" rel="nofollow">Bison</a> but in this case the semantic action for this rule would be "print all the descendants in the parse tree and put my code at the end" which can't be done with basic Bison I think. How do I do this? I also need to split the code because I need to interface with Python with python-spidermonkey.
Or... is there a library out there already which saves me from reinventing the wheel? It doesn't have to be in Python.</p>
| 7 | 2009-05-09T16:05:33Z | 843,805 | <p>Why not try a javascript beautifier?</p>
<p>For example <a href="http://jsbeautifier.org/" rel="nofollow">http://jsbeautifier.org/</a></p>
<p>Or see <a href="http://stackoverflow.com/questions/18985/javascript-beautifier">http://stackoverflow.com/questions/18985/javascript-beautifier</a></p>
| 0 | 2009-05-09T18:28:34Z | [
"javascript",
"python",
"parsing",
"spidermonkey"
] |
Parse JavaScript to instrument code | 843,546 | <p>I need to split a JavaScript file into single instructions. For example</p>
<pre><code>a = 2;
foo()
function bar() {
b = 5;
print("spam");
}
</code></pre>
<p>has to be separated into three instructions. (assignment, function call and function definition).</p>
<p>Basically I need to instrument the code, injecting code between these instructions to perform checks. Splitting by ";" wouldn't obviously work because you can also end instructions with newlines and maybe I don't want to instrument code inside function and class definitions (I don't know yet). I took a course about grammars with <a href="http://en.wikipedia.org/wiki/Flex_lexical_analyser" rel="nofollow">flex</a>/<a href="http://en.wikipedia.org/wiki/GNU_bison" rel="nofollow">Bison</a> but in this case the semantic action for this rule would be "print all the descendants in the parse tree and put my code at the end" which can't be done with basic Bison I think. How do I do this? I also need to split the code because I need to interface with Python with python-spidermonkey.
Or... is there a library out there already which saves me from reinventing the wheel? It doesn't have to be in Python.</p>
| 7 | 2009-05-09T16:05:33Z | 1,338,857 | <p>JavaScript is tricky to parse; you need a full JavaScript parser.
The <a href="http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html" rel="nofollow">DMS Software Reengineering Toolkit</a> can parse full JavaScript and build a corresponding <a href="http://en.wikipedia.org/wiki/Abstract_syntax_tree" rel="nofollow">AST</a>.
AST operators can then be used to walk over the tree to "split it". Even easier, however, is to apply source-to-source transformations that look for one surface syntax (JavaScript) pattern, and replace it by another. You can use such transformations to insert the instrumentation into the code, rather than splitting the code to make holds in which to do the insertions. After the transformations are complete, DMS can regenerate valid JavaScript code (complete with the orignal comments if unaffected).</p>
| 2 | 2009-08-27T04:32:51Z | [
"javascript",
"python",
"parsing",
"spidermonkey"
] |
Parse JavaScript to instrument code | 843,546 | <p>I need to split a JavaScript file into single instructions. For example</p>
<pre><code>a = 2;
foo()
function bar() {
b = 5;
print("spam");
}
</code></pre>
<p>has to be separated into three instructions. (assignment, function call and function definition).</p>
<p>Basically I need to instrument the code, injecting code between these instructions to perform checks. Splitting by ";" wouldn't obviously work because you can also end instructions with newlines and maybe I don't want to instrument code inside function and class definitions (I don't know yet). I took a course about grammars with <a href="http://en.wikipedia.org/wiki/Flex_lexical_analyser" rel="nofollow">flex</a>/<a href="http://en.wikipedia.org/wiki/GNU_bison" rel="nofollow">Bison</a> but in this case the semantic action for this rule would be "print all the descendants in the parse tree and put my code at the end" which can't be done with basic Bison I think. How do I do this? I also need to split the code because I need to interface with Python with python-spidermonkey.
Or... is there a library out there already which saves me from reinventing the wheel? It doesn't have to be in Python.</p>
| 7 | 2009-05-09T16:05:33Z | 7,461,246 | <p>Forget my parser. <a href="https://bitbucket.org/mvantellingen/pyjsparser" rel="nofollow">https://bitbucket.org/mvantellingen/pyjsparser</a> is great and complete parser. I've fixed a couple of it's bugs here: <a href="https://bitbucket.org/nullie/pyjsparser" rel="nofollow">https://bitbucket.org/nullie/pyjsparser</a></p>
| 0 | 2011-09-18T11:44:45Z | [
"javascript",
"python",
"parsing",
"spidermonkey"
] |
Writing a __init__ function to be used in django model | 843,580 | <p>I'm trying to write an <code>__init__</code> function for one of my models so that I can create an object by doing</p>
<pre><code>p = User('name','email')
</code></pre>
<p>When I write the model, I have </p>
<pre><code> def __init__(self, name, email, house_id, password):
models.Model.__init__(self)
self.name = name
self.email = email
</code></pre>
<p>This works, and I can save the object to the database, but when I do 'User.objects.all()', it doesn't pull anything up unless I take out my <code>__init__</code> function. Any ideas?</p>
| 40 | 2009-05-09T16:23:35Z | 843,669 | <p>Django expects the signature of a model's constructor to be <code>(self, *args, **kwargs)</code>, or some reasonable facsimile. Your changing the signature to something completely incompatible has broken it.</p>
| 34 | 2009-05-09T17:10:33Z | [
"python",
"django"
] |
Writing a __init__ function to be used in django model | 843,580 | <p>I'm trying to write an <code>__init__</code> function for one of my models so that I can create an object by doing</p>
<pre><code>p = User('name','email')
</code></pre>
<p>When I write the model, I have </p>
<pre><code> def __init__(self, name, email, house_id, password):
models.Model.__init__(self)
self.name = name
self.email = email
</code></pre>
<p>This works, and I can save the object to the database, but when I do 'User.objects.all()', it doesn't pull anything up unless I take out my <code>__init__</code> function. Any ideas?</p>
| 40 | 2009-05-09T16:23:35Z | 843,740 | <p>Relying on Django's built-in functionality and passing named parameters would be the simplest way to go.</p>
<pre><code>p = User(name="Fred", email="fred@example.com")
</code></pre>
<p>But if you're set on saving some keystrokes, I'd suggest adding a static convenience method to the class instead of messing with the initializer.</p>
<pre><code># In User class declaration
@classmethod
def create(cls, name, email):
return cls(name=name, email=email)
# Use it
p = User.create("Fred", "fred@example.com")
</code></pre>
| 65 | 2009-05-09T17:55:47Z | [
"python",
"django"
] |
Writing a __init__ function to be used in django model | 843,580 | <p>I'm trying to write an <code>__init__</code> function for one of my models so that I can create an object by doing</p>
<pre><code>p = User('name','email')
</code></pre>
<p>When I write the model, I have </p>
<pre><code> def __init__(self, name, email, house_id, password):
models.Model.__init__(self)
self.name = name
self.email = email
</code></pre>
<p>This works, and I can save the object to the database, but when I do 'User.objects.all()', it doesn't pull anything up unless I take out my <code>__init__</code> function. Any ideas?</p>
| 40 | 2009-05-09T16:23:35Z | 28,050,067 | <p>Don't create models with args parameters. If you make a model like so:</p>
<pre><code> User('name','email')
</code></pre>
<p>It becomes very unreadable very quickly as most models require more than that for initialization. You could very easily end up with:</p>
<pre><code>User('Bert', 'Reynolds', 'me@bertreynolds.com','0123456789','5432106789',....)
</code></pre>
<p>Another problem here is that you don't know whether 'Bert' is the first or the last name. The last two numbers could easily be a phone number and a system id. But without it being explicit you will more easily mix them up, or mix up the order if you are using identifiers. What's more is that doing it order-based will put yet another constraint on other developers who use this method and won't remember the arbitrary order of parameters.</p>
<p>You should prefer something like this instead:</p>
<pre><code>User(
first_name='Bert',
last_name='Reynolds',
email='me@bertreynolds.com',
phone='0123456789',
system_id='5432106789',
)
</code></pre>
<p>If this is for tests or something like that, you can use a factory to quickly create models. The factory boy link may be useful: <a href="http://factoryboy.readthedocs.org/en/latest/" rel="nofollow">http://factoryboy.readthedocs.org/en/latest/</a></p>
| 1 | 2015-01-20T16:13:03Z | [
"python",
"django"
] |
Writing a __init__ function to be used in django model | 843,580 | <p>I'm trying to write an <code>__init__</code> function for one of my models so that I can create an object by doing</p>
<pre><code>p = User('name','email')
</code></pre>
<p>When I write the model, I have </p>
<pre><code> def __init__(self, name, email, house_id, password):
models.Model.__init__(self)
self.name = name
self.email = email
</code></pre>
<p>This works, and I can save the object to the database, but when I do 'User.objects.all()', it doesn't pull anything up unless I take out my <code>__init__</code> function. Any ideas?</p>
| 40 | 2009-05-09T16:23:35Z | 28,218,753 | <p>The correct answer is to avoid overriding <code>__init__</code> and write a classmethod as described in the <a href="https://docs.djangoproject.com/en/1.7/ref/models/instances/#creating-objects">Django docs</a>.</p>
<p>But this could be done like you're trying, you just need to add in <code>*args, **kwargs</code> to be accepted by your <code>__init__</code>, and pass them on to the super method call.</p>
<pre><code>def __init__(self, name, email, house_id, password, *args, **kwargs):
super(models.Model, self).__init__(self, *args, **kwargs)
self.name = name
self.email = email
</code></pre>
| 5 | 2015-01-29T15:45:04Z | [
"python",
"django"
] |
call function between time intervals | 843,614 | <p>In app engine I would like to call a function if the current time is between a particular interval. This is what I am doing now. </p>
<pre><code>ist_time = datetime.utcnow() + timedelta(hours=5, minutes = 30)
ist_midnight = ist_time.replace(hour=0, minute=0, second=0, microsecond=0)
market_open = ist_midnight + timedelta(hours=9, minutes = 55)
market_close = ist_midnight + timedelta(hours=16, minutes = 01)
if ist_time >= market_open and ist_time <= market_close:
check_for_updates()
</code></pre>
<p>Any better way of doing this.</p>
| 0 | 2009-05-09T16:42:36Z | 843,644 | <p>This is more compact, but not so obvious:</p>
<pre><code>if '09:55' <= time.strftime(
'%H:%M', time.gmtime((time.time() + 60 * (5 * 60 + 30)))) <= '16:01':
check_for_updates()
</code></pre>
<p>Depending on how important it is for you to do the calculations absolutely properly, you may want to consider daylight saving time (use <em>pytz</em> for that -- it is possible to upload <em>pytz</em> bundled to your app to AppEngine) and seconds and millisecods as well (e.g. use <code>< '16:02'</code> instead of <code><= '16:01'</code>, because the former doesn't depend on the second/subsecond precision.</p>
| 1 | 2009-05-09T16:58:09Z | [
"python",
"datetime",
"time",
"timezone"
] |
call function between time intervals | 843,614 | <p>In app engine I would like to call a function if the current time is between a particular interval. This is what I am doing now. </p>
<pre><code>ist_time = datetime.utcnow() + timedelta(hours=5, minutes = 30)
ist_midnight = ist_time.replace(hour=0, minute=0, second=0, microsecond=0)
market_open = ist_midnight + timedelta(hours=9, minutes = 55)
market_close = ist_midnight + timedelta(hours=16, minutes = 01)
if ist_time >= market_open and ist_time <= market_close:
check_for_updates()
</code></pre>
<p>Any better way of doing this.</p>
| 0 | 2009-05-09T16:42:36Z | 843,984 | <p>It seems like you might want datetime's "time" type, which doesn't care about date.</p>
<pre><code>import datetime
ist_time = datetime.utcnow() + datetime.timedelta(hours=5, minutes = 30)
# Turn this into a time object (no day information).
ist_time = ist_time.time()
if datetime.time(9, 55) <= ist_time <= datetime.time(16, 1):
...
</code></pre>
<p>I'm sure there's a more elegant way to handle the timezone adjustment using tzinfo, but I have to confess I've never dealt with timezones.</p>
| 0 | 2009-05-09T20:23:33Z | [
"python",
"datetime",
"time",
"timezone"
] |
Profiling in Python: Who called the function? | 843,671 | <p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p>
<p><strong>EDIT:</strong></p>
<p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the name of the function that called it?</p>
| 40 | 2009-05-09T17:10:52Z | 843,690 | <p>That may not answer your question directly, but will definitely help. If use the profiler with option --sort cumulative it will sort the functions by cumulative time. Which is helpful to detect not only heavy functions but the functions that call them.</p>
<pre><code>python -m cProfile --sort cumulative myScript.py
</code></pre>
<p>There is a workaround to get the caller function:</p>
<pre><code>import inspect
print inspect.getframeinfo(inspect.currentframe().f_back)[2]
</code></pre>
<p>You can add as many f_back as you want in case you want the caller caller etc
If you want to calculate frequent calls you can do this:</p>
<pre><code>record = {}
caller = inspect.getframeinfo(inspect.currentframe().f_back)[2]
record[caller] = record.get(caller, 0) + 1
</code></pre>
<p>Then print them by order of frequency:</p>
<pre><code>print sorted(record.items(), key=lambda a: a[1])
</code></pre>
| 32 | 2009-05-09T17:18:58Z | [
"python",
"profiling"
] |
Profiling in Python: Who called the function? | 843,671 | <p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p>
<p><strong>EDIT:</strong></p>
<p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the name of the function that called it?</p>
| 40 | 2009-05-09T17:10:52Z | 843,692 | <p>I have not used cProfile myself, but most profilers give you a call hierarchy.<br />
Googling I found this <a href="http://us.pycon.org/media/2009/talkdata/PyCon2009/015/fletcher-profiling-2009.pdf" rel="nofollow">slides</a> about cProfile. Maybe that helps. Page 6 looks like cProfile does provide a hierarchy.</p>
| 1 | 2009-05-09T17:20:00Z | [
"python",
"profiling"
] |
Profiling in Python: Who called the function? | 843,671 | <p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p>
<p><strong>EDIT:</strong></p>
<p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the name of the function that called it?</p>
| 40 | 2009-05-09T17:10:52Z | 843,703 | <p><a href="http://docs.python.org/library/inspect.html#inspect.stack">inspect.stack()</a> will give you the current caller stack.</p>
| 10 | 2009-05-09T17:25:37Z | [
"python",
"profiling"
] |
Profiling in Python: Who called the function? | 843,671 | <p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p>
<p><strong>EDIT:</strong></p>
<p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the name of the function that called it?</p>
| 40 | 2009-05-09T17:10:52Z | 843,725 | <p>I almost always view the output of the cProfile module using <a href="http://code.google.com/p/jrfonseca/wiki/Gprof2Dot">Gprof2dot</a>, basically it converts the output into a graphvis graph (a <code>.dot</code> file), for example:</p>
<p><a href="http://jrfonseca.googlecode.com/svn/wiki/gprof2dot.png"><img src="http://i.stack.imgur.com/1LrS7.png" alt="example gprof2dot output"></a></p>
<p>It makes it very easy to determine which function is slowest, and which function[s] called it.</p>
<p>Usage is:</p>
<pre><code>python -m cProfile -o output.pstats path/to/your/script arg1 arg2
gprof2dot.py -f pstats output.pstats | dot -Tpng -o output.png
</code></pre>
| 92 | 2009-05-09T17:41:25Z | [
"python",
"profiling"
] |
Profiling in Python: Who called the function? | 843,671 | <p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p>
<p><strong>EDIT:</strong></p>
<p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the name of the function that called it?</p>
| 40 | 2009-05-09T17:10:52Z | 845,850 | <p>Sorry I'm not familiar with Python, but there's a <a href="http://stackoverflow.com/questions/375913/what-can-i-use-to-profile-c-code-in-linux/378024#378024">general method</a> that works, assuming you can manually interrupt execution at a random time.</p>
<p>Just do so, and display the call stack. It will tell you, with high probability, what you want to know. If you want to be more certain, just do it several times.</p>
<p>It works because the guilty caller has to be on the call stack for the fraction of time that's being wasted, which exposes it to your interrupts for that much of the time, whether it is spread over many short calls or a few lengthy ones.</p>
<p>NOTE: This process is more like diagnosis than measurement. Suppose that bad call is wasting 90% of the time. Then each time you halt it, the probability is 90% that the bad call statement is right there on the call stack for you to see, and you will be able to see that it's bad. However, if you want to exactly measure the wastage, that's a different problem. For that, you will need a lot more samples, to see what % of them contain that call. Or alternatively, just fix the guilty call, clock the speedup, and that will tell you exactly what the wastage was.</p>
| 0 | 2009-05-10T18:45:34Z | [
"python",
"profiling"
] |
Profiling in Python: Who called the function? | 843,671 | <p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p>
<p><strong>EDIT:</strong></p>
<p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the name of the function that called it?</p>
| 40 | 2009-05-09T17:10:52Z | 845,905 | <p>You might want to take a look at <a href="http://pycallgraph.slowchop.com/" rel="nofollow">pycallgraph</a>.</p>
| 3 | 2009-05-10T19:16:22Z | [
"python",
"profiling"
] |
Profiling in Python: Who called the function? | 843,671 | <p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p>
<p><strong>EDIT:</strong></p>
<p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the name of the function that called it?</p>
| 40 | 2009-05-09T17:10:52Z | 18,358,552 | <p>Pycscope does this. I just found it today, so I can't speak to how good it is, but the few examples I've tried have been pretty good (though not perfect).</p>
<p><a href="https://pypi.python.org/pypi/pycscope/" rel="nofollow">https://pypi.python.org/pypi/pycscope/</a></p>
<p>You would use this to generate a cscope file and then a cscope plugin from an editor, VIM specifically. I tried using it with vanilla cscope, it seems that plain cscope gets confused.</p>
| 0 | 2013-08-21T13:18:29Z | [
"python",
"profiling"
] |
Profiling in Python: Who called the function? | 843,671 | <p>I'm profiling in Python using <code>cProfile</code>. I found a function that takes a lot of CPU time. How do I find out which function is calling this heavy function the most?</p>
<p><strong>EDIT:</strong></p>
<p>I'll settle for a workaround: Can I write a Python line inside that heavy function that will print the name of the function that called it?</p>
| 40 | 2009-05-09T17:10:52Z | 33,163,091 | <p>It is possible to do it using profiler <code>cProfile</code> in standard library.
<br/>
In <code>pstats.Stats</code> (the profiler result) there is method <code>print_callees</code> (or alternatively <code>print_callers</code>).</p>
<p><br/>Example code:</p>
<pre><code>import cProfile, pstats
pr = cProfile.Profile()
pr.enable()
# ... do something ...
pr.disable()
ps = pstats.Stats(pr).strip_dirs().sort_stats('cumulative')
ps.print_callees()
</code></pre>
<p>Result will be something like:</p>
<pre><code>Function called...
ncalls tottime cumtime
ElementTree.py:1517(_start_list) -> 24093 0.048 0.124 ElementTree.py:1399(start)
46429 0.015 0.041 ElementTree.py:1490(_fixtext)
70522 0.015 0.015 ElementTree.py:1497(_fixname)
ElementTree.py:1527(_data) -> 47827 0.017 0.026 ElementTree.py:1388(data)
47827 0.018 0.053 ElementTree.py:1490(_fixtext)
</code></pre>
<p>On the left you have the caller, on the right you have the callee.
<br/>
(for example <code>_fixtext</code> was called from <code>_data</code> 47827 times and from <code>_start_list</code> 46429 times)</p>
<p><br/> See also:</p>
<ul>
<li><a href="https://docs.python.org/2/library/profile.html#pstats.Stats.print_callees" rel="nofollow">docs.python.org/..#print_callees</a> - show call hierarchy. Group by the caller. (used above)</li>
<li><a href="https://docs.python.org/2/library/profile.html#pstats.Stats.print_callers" rel="nofollow">docs.python.org/..#print_callers</a> - show call hierarchy. Group by the callee.</li>
</ul>
<p><br/> Couple of notes:</p>
<ul>
<li>Your code needs to be edited for this (insert those profile statements).
<br/> (i.e. not possible to use from command line like <code>python -m cProfile myscript.py</code>. Though it is possible to write separate script for that)</li>
<li>A bit unrelated, but <code>strip_dirs()</code> must go before <code>sort_stats()</code> (otherwise sorting does not work)</li>
</ul>
| 0 | 2015-10-16T05:22:07Z | [
"python",
"profiling"
] |
How do I choose which Python installation to run in a PyObjC program? | 843,698 | <p>I use Python 2.6 more than I use Leopard's default python installation, so I have it set as my main Python installation. But I'd rather use the default Python for a PyObjC program I'm working on. Is there any way to specify to only use it instead of Python 2.6?</p>
| 1 | 2009-05-09T17:22:14Z | 843,701 | <p>Try specifying the full path to the Python interpreter in the command line, something like:</p>
<pre><code>/foo/bar/python2.6 script.py
/baz/python objcscript.py
</code></pre>
<p>You can also add a shebang to the beginning of your script (first line):</p>
<pre><code>#! /foo/bar/python2.6 script.py
</code></pre>
<p>If you have the environment variable <code>PYTHONPATH</code> set, you might have to unset it or change it.</p>
| 2 | 2009-05-09T17:25:05Z | [
"python",
"objective-c",
"osx",
"pyobjc"
] |
How do I choose which Python installation to run in a PyObjC program? | 843,698 | <p>I use Python 2.6 more than I use Leopard's default python installation, so I have it set as my main Python installation. But I'd rather use the default Python for a PyObjC program I'm working on. Is there any way to specify to only use it instead of Python 2.6?</p>
| 1 | 2009-05-09T17:22:14Z | 845,044 | <p>AFAIR this helped me (in main.m):</p>
<pre><code> NSArray *pythonPathArray = [NSArray arrayWithObjects: resourcePath, [resourcePath stringByAppendingPathComponent:@"PyObjC"], @"/System/Library/Frameworks/Python.framework/Versions/Current/Extras/lib/python/", @"/Library/Python/2.5/site-packages", nil];
</code></pre>
<p>Also, make sure that this point to the Python installation you want to use (main.m):</p>
<pre><code> Py_SetProgramName("/usr/bin/python");
</code></pre>
| 2 | 2009-05-10T10:07:34Z | [
"python",
"objective-c",
"osx",
"pyobjc"
] |
How do I choose which Python installation to run in a PyObjC program? | 843,698 | <p>I use Python 2.6 more than I use Leopard's default python installation, so I have it set as my main Python installation. But I'd rather use the default Python for a PyObjC program I'm working on. Is there any way to specify to only use it instead of Python 2.6?</p>
| 1 | 2009-05-09T17:22:14Z | 845,560 | <p>Finally figured this one out myself. The key to this is to make the final executable link with /System/Library/Frameworks/Python.framework instead of /Library/Frameworks/Python.framework.</p>
| 3 | 2009-05-10T15:57:20Z | [
"python",
"objective-c",
"osx",
"pyobjc"
] |
list.append or list +=? | 843,751 | <p>Which is more pythonic?</p>
<pre><code>list.append(1)
</code></pre>
<p>or</p>
<pre><code>list += [1]
</code></pre>
| 25 | 2009-05-09T17:59:10Z | 843,761 | <p>From the <a href="http://www.python.org/dev/peps/pep-0020/">Zen of Python</a>:</p>
<blockquote>
<p>Explicit is better than implicit.</p>
</blockquote>
<p>So: <code>list.append(1)</code></p>
| 54 | 2009-05-09T18:05:09Z | [
"python"
] |
list.append or list +=? | 843,751 | <p>Which is more pythonic?</p>
<pre><code>list.append(1)
</code></pre>
<p>or</p>
<pre><code>list += [1]
</code></pre>
| 25 | 2009-05-09T17:59:10Z | 843,762 | <p><code>list.append(1)</code> is faster, because it doesn't create a temporary list object.</p>
| 57 | 2009-05-09T18:05:12Z | [
"python"
] |
list.append or list +=? | 843,751 | <p>Which is more pythonic?</p>
<pre><code>list.append(1)
</code></pre>
<p>or</p>
<pre><code>list += [1]
</code></pre>
| 25 | 2009-05-09T17:59:10Z | 843,781 | <p>list.append(1)
more readable and to consistent with the context</p>
| 3 | 2009-05-09T18:13:40Z | [
"python"
] |
list.append or list +=? | 843,751 | <p>Which is more pythonic?</p>
<pre><code>list.append(1)
</code></pre>
<p>or</p>
<pre><code>list += [1]
</code></pre>
| 25 | 2009-05-09T17:59:10Z | 843,908 | <p>Since there's also</p>
<pre><code>list.extend(l)
</code></pre>
<p>which appends all elements of the given list, I would use</p>
<pre><code>list.append(1)
</code></pre>
<p>for symmetry and readability's sake.</p>
| 6 | 2009-05-09T19:50:50Z | [
"python"
] |
list.append or list +=? | 843,751 | <p>Which is more pythonic?</p>
<pre><code>list.append(1)
</code></pre>
<p>or</p>
<pre><code>list += [1]
</code></pre>
| 25 | 2009-05-09T17:59:10Z | 843,936 | <p>These are two different operations, what you are doing with += is the extend operation. Here is what Python documents have to say about this:</p>
<blockquote>
<p>list.append(x): Add an item to the end of the list; equivalent to a[len(a):] = [x].</p>
<p>list.extend(L): Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.</p>
</blockquote>
<p>So in += you provide a list, in append you just add a new element.</p>
| 16 | 2009-05-09T20:02:44Z | [
"python"
] |
list.append or list +=? | 843,751 | <p>Which is more pythonic?</p>
<pre><code>list.append(1)
</code></pre>
<p>or</p>
<pre><code>list += [1]
</code></pre>
| 25 | 2009-05-09T17:59:10Z | 844,287 | <p>While most people here are preferring the append option, I personally prefer the other one because it looks nicer even though it may be slower (or maybe its optimized).</p>
<blockquote>
<p>Beautiful is better than ugly.</p>
</blockquote>
<p>When you write lots of Python code, I don't usually see something like this:</p>
<pre><code>list.append(1)
</code></pre>
<p>It's more like this:</p>
<pre><code>somecollectionname.append(anotherelementname+5*10)
</code></pre>
<p>So to me at least, it is nicer to see:</p>
<pre><code>somecollectionname += [anotherelementname+5*10]
</code></pre>
<p>Because its easy to recognize at a glance that you are adding to a list. Having said that, I sometimes find myself using both forms.</p>
| 5 | 2009-05-09T23:12:50Z | [
"python"
] |
list.append or list +=? | 843,751 | <p>Which is more pythonic?</p>
<pre><code>list.append(1)
</code></pre>
<p>or</p>
<pre><code>list += [1]
</code></pre>
| 25 | 2009-05-09T17:59:10Z | 844,354 | <p>If you've got a single element, <code>a</code>, that you want to add to your list <code>l</code>, then putting <code>a</code> into its own list and extending <code>l</code> with it seems like adding unnecessary complexity. I would thus prefer </p>
<pre><code>l.append(a)
</code></pre>
<p>over</p>
<pre><code>l += [a]
</code></pre>
<p>If <code>a</code> is already a list, then choosing</p>
<pre><code>l += a
</code></pre>
<p>or </p>
<pre><code>l.extend(a)
</code></pre>
<p>is a matter of preference, IMO. On the other hand, if you're going to be doing a lot of extends, you can get a performance boost by "hoisting" the method lookup:</p>
<pre><code>extend = l.extend
for sublist in bunch_of_lists:
extend(sublist)
</code></pre>
<p>Finally, I think that the append operation isn't used too often in Pythonic code, because append is used very often in "accumulator" idioms, where I'd expect a more experienced Python programmer to use a list comprehension/etc.</p>
<p>So instead of:</p>
<pre><code>l = []
for a in numbers:
l.append(str(a))
</code></pre>
<p>You'd probably see:</p>
<pre><code>l = [str(a) for a in numbers]
</code></pre>
<p>or</p>
<pre><code>l = map(str, numbers)
</code></pre>
| 3 | 2009-05-09T23:47:43Z | [
"python"
] |
list.append or list +=? | 843,751 | <p>Which is more pythonic?</p>
<pre><code>list.append(1)
</code></pre>
<p>or</p>
<pre><code>list += [1]
</code></pre>
| 25 | 2009-05-09T17:59:10Z | 28,676,064 | <h2>Beware of fundamentalism</h2>
<p>Have you noticed the term "more pythonic" in your question?
I think it implies that you are asking a not-so-helpful question.</p>
<p>If one is merely <em>more</em> pythonic than the other (rather than being
pythonic while the other is not) it could be said that you have
violated the Zen of Python on a meta level:
<em>"Simple is better than complex"</em> should also hold for the
process of searching for the form in which you express
your logic -- once you have found something pythonic,
that is good enough. Keep the search simple.</p>
<p>So my answer would be:
Neither of them is more pythonic.
<strong>The most pythonic thing is to go on and write a nice program.</strong></p>
| 0 | 2015-02-23T14:29:53Z | [
"python"
] |
FastCgi crashes -- Want to catch all exceptions but how? | 843,753 | <p>I have a django app running on apache with fastcgi (uses Flup's WSGIServer).</p>
<p>This gets setup via dispatch.fcgi, concatenated below:</p>
<pre><code>#!/usr/bin/python
import sys, os
sys.path.insert(0, os.path.realpath('/usr/local/django_src/django'))
PROJECT_PATH=os.environ['PROJECT_PATH']
sys.path.insert(0, PROJECT_PATH)
os.chdir(PROJECT_PATH)
os.environ['DJANGO_SETTINGS_MODULE'] = "settings"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded",daemonize='false',)
</code></pre>
<p>The runfastcgi is the one that does the work, eventually running a WSGIServer on a WSGIHandler.</p>
<p>Sometimes an exception happens which crashes fastcgi.</p>
<p>EDIT: I don't know what error crashes fastcgi, or whether fastcgi even crashes. I just know that sometimes the site goes down--consistently down--until I reboot apache. THe only errors that appear in the error.log are the broken pipe and incomplete headers ones, listed below.</p>
<p>Incomplete headers:</p>
<p>note: I've replaced sensitive information or clutter with "..."</p>
<pre><code>[Sat May 09 ...] [error] [client ...] (104)Connection reset by peer: FastCGI: comm with server ".../dispatch.fcgi" aborted: read failed
[Sat May 09 ...] [error] [client ...] FastCGI: incomplete headers (0 bytes) received from server ".../dispatch.fcgi"
[Sat May 09 ...] [error] [client ...] (32)Broken pipe: FastCGI: comm with server ".../dispatch.fcgi" aborted: write failed,
</code></pre>
<p>Broken pipe:</p>
<p>note: this happens to be for a trac site not a django app, but it looks the same.</p>
<pre><code>Unhandled exception in thread started by <bound method Connection.run of <trac.web._fcgi.Connection object at 0xb53d7c0c>>
Traceback (most recent call last):
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 654, in run
self.process_input()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 690, in process_input
self._do_params(rec)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 789, in _do_params
self._start_request(req)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 773, in _start_request
req.run()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 582, in run
self._flush()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 589, in _flush
self.stdout.close()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 348, in close
self._conn.writeRecord(rec)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 705, in writeRecord
rec.write(self._sock)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 542, in write
self._sendall(sock, header)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 520, in _sendall
sent = sock.send(data)
socket.error: (32, 'Broken pipe')
</code></pre>
<p>I've looked through /var/log/apache2/error.log, but I can't seem to find the cause of the crashing. I sometimes have memory swapping problems, but I think this is different. (Please excuse my ignorance. I am willing to learn how to implement and debug server admin stuff better.)</p>
<p>I'd like to wrap the the runfastcgi with a try/except. What is the best way to handle random exceptions (until I figure out the actual cause(s))?</p>
<p>I believe the WSGIServer handles many requests. If I catch an exception, can I re-call runfastcgi without fear of an infinite loop? Should I return an Error HttpRequest for the offending, exception-calling request? I'm not even sure how to do that.</p>
<p>I've been looking through django/core/servers/fastcgi.py and django/core/handlers/wsgi.py and django/http/<strong>init</strong>.py</p>
<p>I haven't been able to make progress understanding flup's side of things.</p>
<p>Have ideas or experiences I might learn from?</p>
<p>Thanks!</p>
| 0 | 2009-05-09T18:00:25Z | 843,811 | <p>This is probably a Flup <a href="http://trac.saddi.com/flup/ticket/18" rel="nofollow">bug</a>. When a flup-based server's client connection is closed before flup is done sending data, it raises a socket.error: (32, 'Broken pipe') exception.</p>
<p>Trying to catch the exception by a try catch around runfastcgi will not work. Simply because the exception is raised by a thread.</p>
<p>OK, I'll explain why the wrapping your own code in a try catch won't work. If you look closely at the exception traceback you'll see that the first statement in the trace is not runfastcgi. That's because the exception is happening in a different thread. If you want to catch the exception you need to wrap any of the statements listed by the trace in a try/catch like this:</p>
<pre><code># in file /usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 654, in run
try:
self.process_input()
except socket.error:
# ignore or print an error
pass
</code></pre>
<p>The point is, you can catch the error by modifing Flup's code. But I don't see any benefit from this. Especial because this exception seems to be harmless and there already is a patch for it.</p>
| 2 | 2009-05-09T18:37:04Z | [
"python",
"django",
"fastcgi",
"wsgi",
"flup"
] |
FastCgi crashes -- Want to catch all exceptions but how? | 843,753 | <p>I have a django app running on apache with fastcgi (uses Flup's WSGIServer).</p>
<p>This gets setup via dispatch.fcgi, concatenated below:</p>
<pre><code>#!/usr/bin/python
import sys, os
sys.path.insert(0, os.path.realpath('/usr/local/django_src/django'))
PROJECT_PATH=os.environ['PROJECT_PATH']
sys.path.insert(0, PROJECT_PATH)
os.chdir(PROJECT_PATH)
os.environ['DJANGO_SETTINGS_MODULE'] = "settings"
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded",daemonize='false',)
</code></pre>
<p>The runfastcgi is the one that does the work, eventually running a WSGIServer on a WSGIHandler.</p>
<p>Sometimes an exception happens which crashes fastcgi.</p>
<p>EDIT: I don't know what error crashes fastcgi, or whether fastcgi even crashes. I just know that sometimes the site goes down--consistently down--until I reboot apache. THe only errors that appear in the error.log are the broken pipe and incomplete headers ones, listed below.</p>
<p>Incomplete headers:</p>
<p>note: I've replaced sensitive information or clutter with "..."</p>
<pre><code>[Sat May 09 ...] [error] [client ...] (104)Connection reset by peer: FastCGI: comm with server ".../dispatch.fcgi" aborted: read failed
[Sat May 09 ...] [error] [client ...] FastCGI: incomplete headers (0 bytes) received from server ".../dispatch.fcgi"
[Sat May 09 ...] [error] [client ...] (32)Broken pipe: FastCGI: comm with server ".../dispatch.fcgi" aborted: write failed,
</code></pre>
<p>Broken pipe:</p>
<p>note: this happens to be for a trac site not a django app, but it looks the same.</p>
<pre><code>Unhandled exception in thread started by <bound method Connection.run of <trac.web._fcgi.Connection object at 0xb53d7c0c>>
Traceback (most recent call last):
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 654, in run
self.process_input()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 690, in process_input
self._do_params(rec)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 789, in _do_params
self._start_request(req)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 773, in _start_request
req.run()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 582, in run
self._flush()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 589, in _flush
self.stdout.close()
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 348, in close
self._conn.writeRecord(rec)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 705, in writeRecord
rec.write(self._sock)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 542, in write
self._sendall(sock, header)
File "/usr/lib/python2.4/site-packages/Trac-0.12dev_r7715-py2.4.egg/trac/web/_fcgi.py", line 520, in _sendall
sent = sock.send(data)
socket.error: (32, 'Broken pipe')
</code></pre>
<p>I've looked through /var/log/apache2/error.log, but I can't seem to find the cause of the crashing. I sometimes have memory swapping problems, but I think this is different. (Please excuse my ignorance. I am willing to learn how to implement and debug server admin stuff better.)</p>
<p>I'd like to wrap the the runfastcgi with a try/except. What is the best way to handle random exceptions (until I figure out the actual cause(s))?</p>
<p>I believe the WSGIServer handles many requests. If I catch an exception, can I re-call runfastcgi without fear of an infinite loop? Should I return an Error HttpRequest for the offending, exception-calling request? I'm not even sure how to do that.</p>
<p>I've been looking through django/core/servers/fastcgi.py and django/core/handlers/wsgi.py and django/http/<strong>init</strong>.py</p>
<p>I haven't been able to make progress understanding flup's side of things.</p>
<p>Have ideas or experiences I might learn from?</p>
<p>Thanks!</p>
| 0 | 2009-05-09T18:00:25Z | 844,131 | <p><em>Broken pipe</em> usually doesn't come deterministically. You get a <em>Broken pipe</em> if a write operation on a pipe or socket fails because the other end has closed the connection. So if your FastCGI gets a <em>Broken pipe</em>, it means that the webserver has closed to connection too early. In some cases this is not an problem, it can be ignored silently.</p>
<p>As a quick hack, try to catch and ignore the <code>socket.error</code> with <code>Broken pipe</code>. You may have to add an <code>except:</code> clause to many more places.</p>
| 0 | 2009-05-09T21:36:13Z | [
"python",
"django",
"fastcgi",
"wsgi",
"flup"
] |
How can I check Hamming Weight without converting to binary? | 843,828 | <p>How can I get the <strong>number of "1"s</strong> in the binary representation of a number without actually converting and counting ?</p>
<p>e.g.</p>
<pre><code> def number_of_ones(n):
# do something
# I want to MAKE this FASTER (computationally less complex).
c = 0
while n:
c += n%2
n /= 2
return c
>>> number_of_ones(5)
2
>>> number_of_ones(4)
1
</code></pre>
| 8 | 2009-05-09T18:54:53Z | 843,846 | <p>I'm not a python programmer, but hopefully it will be enough for you to follow.</p>
<pre><code>c = 0
while n:
c += 1
n &= n - 1
return c
</code></pre>
<p>While a little obscure, it's primary advantage is speed and simplicity. The while loop is only iterated once for every bit set to 1 in n.</p>
| 7 | 2009-05-09T19:05:58Z | [
"python",
"algorithm",
"discrete-mathematics"
] |
How can I check Hamming Weight without converting to binary? | 843,828 | <p>How can I get the <strong>number of "1"s</strong> in the binary representation of a number without actually converting and counting ?</p>
<p>e.g.</p>
<pre><code> def number_of_ones(n):
# do something
# I want to MAKE this FASTER (computationally less complex).
c = 0
while n:
c += n%2
n /= 2
return c
>>> number_of_ones(5)
2
>>> number_of_ones(4)
1
</code></pre>
| 8 | 2009-05-09T18:54:53Z | 843,854 | <p>If you're actually concerned about speed, code it up in C (see <a href="http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer">this question</a> for how), and interface with the C implementation using something like <a href="http://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a>.</p>
| 1 | 2009-05-09T19:12:23Z | [
"python",
"algorithm",
"discrete-mathematics"
] |
How can I check Hamming Weight without converting to binary? | 843,828 | <p>How can I get the <strong>number of "1"s</strong> in the binary representation of a number without actually converting and counting ?</p>
<p>e.g.</p>
<pre><code> def number_of_ones(n):
# do something
# I want to MAKE this FASTER (computationally less complex).
c = 0
while n:
c += n%2
n /= 2
return c
>>> number_of_ones(5)
2
>>> number_of_ones(4)
1
</code></pre>
| 8 | 2009-05-09T18:54:53Z | 843,899 | <p>IMO, a good approach would be to use a look-up table - create a dictionary which converts bytes to number of 1's (you can use the code you posted to generate it, it would only need to run once), and then use something like this:</p>
<pre><code>def number_of_ones(n):
sum = 0
while n != 0:
sum += lookup_table[n & 0xff]
n >>= 8
return sum
</code></pre>
<p>I believe this is a fairly good trade-off between space and running-time.</p>
| 5 | 2009-05-09T19:46:52Z | [
"python",
"algorithm",
"discrete-mathematics"
] |
How can I check Hamming Weight without converting to binary? | 843,828 | <p>How can I get the <strong>number of "1"s</strong> in the binary representation of a number without actually converting and counting ?</p>
<p>e.g.</p>
<pre><code> def number_of_ones(n):
# do something
# I want to MAKE this FASTER (computationally less complex).
c = 0
while n:
c += n%2
n /= 2
return c
>>> number_of_ones(5)
2
>>> number_of_ones(4)
1
</code></pre>
| 8 | 2009-05-09T18:54:53Z | 843,940 | <p>If you want to do it in a single line, you could use:</p>
<pre><code>sum( [x&(1<<i)>0 for i in range(32)] )
</code></pre>
| 4 | 2009-05-09T20:03:13Z | [
"python",
"algorithm",
"discrete-mathematics"
] |
How can I check Hamming Weight without converting to binary? | 843,828 | <p>How can I get the <strong>number of "1"s</strong> in the binary representation of a number without actually converting and counting ?</p>
<p>e.g.</p>
<pre><code> def number_of_ones(n):
# do something
# I want to MAKE this FASTER (computationally less complex).
c = 0
while n:
c += n%2
n /= 2
return c
>>> number_of_ones(5)
2
>>> number_of_ones(4)
1
</code></pre>
| 8 | 2009-05-09T18:54:53Z | 843,957 | <p>You cannot make this computationally less complex. It will be O(n) the number of bits, or, as the answer with the & trick showed, O(n) the number of bits set to 1; but unless all of the numbers you are using are a special case, the latter should on average be n/2, so both of those O(n) numbers are the same.</p>
<p>And the lookup-table trick, of course, is actually doing nothing for the computational complexity; it's just paying for time with space but without changing the underlying economics, which are that you must examine each bit once <em>somehow</em> and there is no way around that. You cannot, logically, answer a question about the bits in the number without inspecting each of them.</p>
<p>Now, I suppose I'm being a bit sloppy since many of these examples are actually O(n^2) since in Python you have to examine the whole number at once time, so with a Python long integer of, say, 100 bytes, a + or an & or a / operation will look at each byte at least once, and that will happen over and over until the number is reduced to zero (in the schemes outlined above), so these, again, are really O(n^2) operations. I am not sure Python will allow a true O(n) solution here.</p>
<p>Anyway: if you were really asking about <em>computational</em> complexity, which specifically means big-O analysis, that's your answer. :-)</p>
| 6 | 2009-05-09T20:12:20Z | [
"python",
"algorithm",
"discrete-mathematics"
] |
How can I check Hamming Weight without converting to binary? | 843,828 | <p>How can I get the <strong>number of "1"s</strong> in the binary representation of a number without actually converting and counting ?</p>
<p>e.g.</p>
<pre><code> def number_of_ones(n):
# do something
# I want to MAKE this FASTER (computationally less complex).
c = 0
while n:
c += n%2
n /= 2
return c
>>> number_of_ones(5)
2
>>> number_of_ones(4)
1
</code></pre>
| 8 | 2009-05-09T18:54:53Z | 36,503,001 | <p>p= lambda n:n and 1+p(n&(n-1))</p>
<p>This uses short-circuiting and recursion, when n is greater than 0, it switches to calculate 1+p(n&(n-1)) where p(n&(n-1)) is called and so on, when n is 0 it returns 0. Complexity being O(n) since it runs the number of times the number of ones exist in the binary.</p>
<p>Example: p(9)=1+p(8)=1+1+p(0)=1+1+0=2</p>
| 0 | 2016-04-08T15:03:25Z | [
"python",
"algorithm",
"discrete-mathematics"
] |
How can I check Hamming Weight without converting to binary? | 843,828 | <p>How can I get the <strong>number of "1"s</strong> in the binary representation of a number without actually converting and counting ?</p>
<p>e.g.</p>
<pre><code> def number_of_ones(n):
# do something
# I want to MAKE this FASTER (computationally less complex).
c = 0
while n:
c += n%2
n /= 2
return c
>>> number_of_ones(5)
2
>>> number_of_ones(4)
1
</code></pre>
| 8 | 2009-05-09T18:54:53Z | 36,555,670 | <p>Here:</p>
<p>def bitCount(int_no):</p>
<pre><code>c = 0
while(int_no):
int_no &= (int_no - 1)
c += 1
return c
</code></pre>
<p>This might be an old and efficient way to do this... originally implementated in C (Algo has a name I can't remember). It works fine for me hope it does for any other person</p>
| 0 | 2016-04-11T17:47:35Z | [
"python",
"algorithm",
"discrete-mathematics"
] |
wxPython: Drawing a vector-based image from file | 844,110 | <p>How can I draw a vector-based image from a file in wxPython? I know nothing of image formats for such a thing, so please recommend.</p>
| 3 | 2009-05-09T21:26:37Z | 844,139 | <p>You can do this with using cairo & librsvg python bindings. There is a small example <a href="http://www.daa.com.au/pipermail/pygtk/2007-April/013778.html" rel="nofollow">here</a>.</p>
| 3 | 2009-05-09T21:43:13Z | [
"python",
"wxpython",
"vector-graphics"
] |
wxPython: Drawing a vector-based image from file | 844,110 | <p>How can I draw a vector-based image from a file in wxPython? I know nothing of image formats for such a thing, so please recommend.</p>
| 3 | 2009-05-09T21:26:37Z | 884,997 | <p>I have done something similar, I had a custom vector image format that I needed to render in a wxPython window. In order to accomplish this I used the GDI interface for drawing commands and I wrote my own parser module. There is a great GDI tutorial at this site that should help you out: <a href="http://www.zetcode.com/wxpython/gdi/" rel="nofollow">http://www.zetcode.com/wxpython/gdi/</a></p>
| 1 | 2009-05-19T20:59:49Z | [
"python",
"wxpython",
"vector-graphics"
] |
Downloading a web page and all of its resource files in Python | 844,115 | <p>I want to be able to download a page and all of its associated resources (images, style sheets, script files, etc) using Python. I am (somewhat) familiar with urllib2 and know how to download individual urls, but before I go and start hacking at BeautifulSoup + urllib2 I wanted to be sure that there wasn't already a Python equivalent to "wget --page-requisites <a href="http://www.google.com">http://www.google.com</a>". </p>
<p>Specifically I am interested in gathering statistical information about how long it takes to download an entire web page, including all resources.</p>
<p>Thanks
Mark</p>
| 8 | 2009-05-09T21:28:26Z | 844,121 | <p>Websucker? See <a href="http://effbot.org/zone/websucker.htm" rel="nofollow">http://effbot.org/zone/websucker.htm</a></p>
| 2 | 2009-05-09T21:31:08Z | [
"python",
"urllib2",
"wget"
] |
Downloading a web page and all of its resource files in Python | 844,115 | <p>I want to be able to download a page and all of its associated resources (images, style sheets, script files, etc) using Python. I am (somewhat) familiar with urllib2 and know how to download individual urls, but before I go and start hacking at BeautifulSoup + urllib2 I wanted to be sure that there wasn't already a Python equivalent to "wget --page-requisites <a href="http://www.google.com">http://www.google.com</a>". </p>
<p>Specifically I am interested in gathering statistical information about how long it takes to download an entire web page, including all resources.</p>
<p>Thanks
Mark</p>
| 8 | 2009-05-09T21:28:26Z | 2,837,722 | <p>websucker.py doesn't import css links. HTTrack.com is not python, it's C/C++, but it's a good, maintained, utility for downloading a website for offline browsing.</p>
<p><a href="http://www.mail-archive.com/python-bugs-list@python.org/msg13523.html" rel="nofollow">http://www.mail-archive.com/python-bugs-list@python.org/msg13523.html</a>
[issue1124] Webchecker not parsing css "@import url"</p>
<p>Guido> This is essentially unsupported and unmaintaned example code. Feel free
to submit a patch though!</p>
| 2 | 2010-05-14T21:22:34Z | [
"python",
"urllib2",
"wget"
] |
where to put method that works on a model | 844,142 | <p>I'm working with Django.</p>
<p>I have a model called Agrument. Arguments have sides and owners. I have a function that returns back the side of the most recent argument of a certain user.</p>
<p>like obj.get_current_side(username)</p>
<p>I've added this to the actual Argument model like this</p>
<pre><code> def get_current_side(self, user):
return self.argument_set.latest('pub_date').side
</code></pre>
<p>I am starting to think this doesn't make sense because there may not be an instance of an Argument. Is this a place I would use a class method? I thought about making a util class, but I'm thinking that it makes sense to be associated with the Argument class.</p>
| 1 | 2009-05-09T21:47:00Z | 844,168 | <p>I think what you are looking for are model managers. </p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/db/managers/#topics-db-managers" rel="nofollow">Django docs on managers</a> with managers you can add a function to the model class instead of a model instance. </p>
| 0 | 2009-05-09T22:03:16Z | [
"python",
"django"
] |
where to put method that works on a model | 844,142 | <p>I'm working with Django.</p>
<p>I have a model called Agrument. Arguments have sides and owners. I have a function that returns back the side of the most recent argument of a certain user.</p>
<p>like obj.get_current_side(username)</p>
<p>I've added this to the actual Argument model like this</p>
<pre><code> def get_current_side(self, user):
return self.argument_set.latest('pub_date').side
</code></pre>
<p>I am starting to think this doesn't make sense because there may not be an instance of an Argument. Is this a place I would use a class method? I thought about making a util class, but I'm thinking that it makes sense to be associated with the Argument class.</p>
| 1 | 2009-05-09T21:47:00Z | 844,176 | <p>It would make more sense to have instance methods on the <code>User</code> model:</p>
<pre><code>def get_current_side(self):
try:
return self.arguments.latest('pub_date').side
except User.DoesNotExist, e:
return None
</code></pre>
<p>You can do this by extending the <code>User</code> model as explained here:</p>
<ul>
<li><a href="http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/" rel="nofollow">Extending the Django User model with inheritance</a></li>
</ul>
<p><em>Edit: I'm not exactly sure which exception gets thrown.</em></p>
| 2 | 2009-05-09T22:08:19Z | [
"python",
"django"
] |
where to put method that works on a model | 844,142 | <p>I'm working with Django.</p>
<p>I have a model called Agrument. Arguments have sides and owners. I have a function that returns back the side of the most recent argument of a certain user.</p>
<p>like obj.get_current_side(username)</p>
<p>I've added this to the actual Argument model like this</p>
<pre><code> def get_current_side(self, user):
return self.argument_set.latest('pub_date').side
</code></pre>
<p>I am starting to think this doesn't make sense because there may not be an instance of an Argument. Is this a place I would use a class method? I thought about making a util class, but I'm thinking that it makes sense to be associated with the Argument class.</p>
| 1 | 2009-05-09T21:47:00Z | 844,998 | <p>This should be a method on a custom model manager:</p>
<pre><code># in models.py
class ArgumentManager(models.manager.Manager):
def get_current_side(self, user):
try:
return self.filter(user=user).latest('pub_date').side
except Argument.DoesNotExist:
return None
class Argument(models.Model):
# fields etc...
objects = ArgumentManager()
# Calling:
side = Argument.objects.get_current_side(user)
</code></pre>
<p>Alternaticely you <strong>can</strong> extend <code>contrib.auth.user</code> and add <code>get_current_size()</code> on it. But I wouldn't mess with it until I'm very confident with Django.</p>
<p>BTW: Most of the code in this page is wrong; for example <code>user</code> variable is not used at all on the OP's snipplet.</p>
| 1 | 2009-05-10T09:22:00Z | [
"python",
"django"
] |
Regular expression implementation details | 844,183 | <p>A <a href="http://stackoverflow.com/questions/842856/whats-the-most-efficient-way-to-find-one-of-several-substrings-in-python">question that I answered</a> got me wondering:</p>
<p>How are regular expressions implemented in Python? What sort of efficiency guarantees are there? Is the implementation "standard", or is it subject to change?</p>
<p>I thought that regular expressions would be implemented as DFAs, and therefore were very efficient (requiring at most one scan of the input string). <a href="http://stackoverflow.com/users/90848/laurence-gonsalves">Laurence Gonsalves</a> raised an interesting point that not all Python regular expressions are regular. (His example is r"(a+)b\1", which matches some number of a's, a b, and then the same number of a's as before). This clearly cannot be implemented with a DFA.</p>
<p>So, to reiterate: what are the implementation details and guarantees of Python regular expressions?</p>
<p>It would also be nice if someone could give some sort of explanation (in light of the implementation) as to why the regular expressions "cat|catdog" and "catdog|cat" lead to different search results in the string "catdog", as mentioned in the <a href="http://stackoverflow.com/questions/842856/whats-the-most-efficient-way-to-find-one-of-several-substrings-in-python">question that I referenced before</a>.</p>
| 11 | 2009-05-09T22:12:50Z | 844,267 | <p>Python's re module was based on <a href="http://en.wikipedia.org/wiki/PCRE" rel="nofollow">PCRE</a>, but has moved on to their own implementation.</p>
<p>Here is the link to the <a href="http://hg.python.org/cpython/file/a82fc1f366b4/Modules/_sre.c" rel="nofollow">C code</a>.</p>
<p>It appears as though the library is based on recursive backtracking when an incorrect path has been taken.</p>
<p><img src="http://pdos.csail.mit.edu/~rsc/regexp-img/grep1p.png" alt="alt text"></p>
<p>Regular expression and text size n<br>
a?<sup>n</sup>a<sup>n</sup> matching a<sup>n</sup></p>
<p>Keep in mind that this graph is not representative of normal regex searches.</p>
<p><a href="http://swtch.com/~rsc/regexp/regexp1.html" rel="nofollow">http://swtch.com/~rsc/regexp/regexp1.html</a></p>
| 16 | 2009-05-09T23:03:17Z | [
"python",
"regex"
] |
Regular expression implementation details | 844,183 | <p>A <a href="http://stackoverflow.com/questions/842856/whats-the-most-efficient-way-to-find-one-of-several-substrings-in-python">question that I answered</a> got me wondering:</p>
<p>How are regular expressions implemented in Python? What sort of efficiency guarantees are there? Is the implementation "standard", or is it subject to change?</p>
<p>I thought that regular expressions would be implemented as DFAs, and therefore were very efficient (requiring at most one scan of the input string). <a href="http://stackoverflow.com/users/90848/laurence-gonsalves">Laurence Gonsalves</a> raised an interesting point that not all Python regular expressions are regular. (His example is r"(a+)b\1", which matches some number of a's, a b, and then the same number of a's as before). This clearly cannot be implemented with a DFA.</p>
<p>So, to reiterate: what are the implementation details and guarantees of Python regular expressions?</p>
<p>It would also be nice if someone could give some sort of explanation (in light of the implementation) as to why the regular expressions "cat|catdog" and "catdog|cat" lead to different search results in the string "catdog", as mentioned in the <a href="http://stackoverflow.com/questions/842856/whats-the-most-efficient-way-to-find-one-of-several-substrings-in-python">question that I referenced before</a>.</p>
| 11 | 2009-05-09T22:12:50Z | 846,095 | <p>There are no "efficiency guarantees" on Python REs any more than on any other part of the language (C++'s standard library is the only widespread language standard I know that tries to establish such standards -- but there are no standards, even in C++, specifying that, say, multiplying two ints must take constant time, or anything like that); nor is there any guarantee that big optimizations won't be applied at any time.</p>
<p>Today, F. Lundh (originally responsible for implementing Python's current RE module, etc), presenting Unladen Swallow at Pycon Italia, mentioned that one of the avenues they'll be exploring is to compile regular expressions directly to LLVM intermediate code (rather than their own bytecode flavor to be interpreted by an ad-hoc runtime) -- since ordinary Python code is also getting compiled to LLVM (in a soon-forthcoming release of Unladen Swallow), a RE and its surrounding Python code could then be optimized together, even in quite aggressive ways sometimes. I doubt anything like that will be anywhere close to "production-ready" very soon, though;-).</p>
| 5 | 2009-05-10T21:01:56Z | [
"python",
"regex"
] |
Regular expression implementation details | 844,183 | <p>A <a href="http://stackoverflow.com/questions/842856/whats-the-most-efficient-way-to-find-one-of-several-substrings-in-python">question that I answered</a> got me wondering:</p>
<p>How are regular expressions implemented in Python? What sort of efficiency guarantees are there? Is the implementation "standard", or is it subject to change?</p>
<p>I thought that regular expressions would be implemented as DFAs, and therefore were very efficient (requiring at most one scan of the input string). <a href="http://stackoverflow.com/users/90848/laurence-gonsalves">Laurence Gonsalves</a> raised an interesting point that not all Python regular expressions are regular. (His example is r"(a+)b\1", which matches some number of a's, a b, and then the same number of a's as before). This clearly cannot be implemented with a DFA.</p>
<p>So, to reiterate: what are the implementation details and guarantees of Python regular expressions?</p>
<p>It would also be nice if someone could give some sort of explanation (in light of the implementation) as to why the regular expressions "cat|catdog" and "catdog|cat" lead to different search results in the string "catdog", as mentioned in the <a href="http://stackoverflow.com/questions/842856/whats-the-most-efficient-way-to-find-one-of-several-substrings-in-python">question that I referenced before</a>.</p>
| 11 | 2009-05-09T22:12:50Z | 1,635,192 | <p><a href="http://perl.plover.com/NPC/" rel="nofollow">Matching regular expressions with backreferences is NP-hard</a>, which is at least as hard as <a href="http://en.wikipedia.org/wiki/NP-complete" rel="nofollow">NP-Complete</a>. That basically means that it's as hard as any problem you're likely to encounter, and most computer scientists think it could require exponential time in the worst case. If you could match such "regular" expressions (which really aren't, in the technical sense) in polynomial time, you could win <a href="http://www.claymath.org/millennium/P%5Fvs%5FNP/" rel="nofollow">a million bucks</a>.</p>
| 1 | 2009-10-28T04:24:21Z | [
"python",
"regex"
] |
Is a graph library (eg NetworkX) the right solution for my Python problem? | 844,505 | <p>I'm rewriting a data-driven legacy application in Python. One of the primary tables is referred to as a "graph table", and does appear to be a directed graph, so I was exploring the NetworkX package to see whether it would make sense to use it for the graph table manipulations, and really implement it as a graph rather than a complicated set of arrays.</p>
<p>However I'm starting to wonder whether the way we use this table is poorly suited for an actual graph manipulation library. Most of the NetworkX functionality seems to be oriented towards characterizing the graph itself in some way, determining shortest distance between two nodes, and things like that. None of that is relevant to my application. </p>
<p>I'm hoping if I can describe the actual usage here, someone can advise me whether I'm just missing something -- I've never really worked with graphs before so this is quite possible -- or if I should be exploring some other data structure. (And if so, what would you suggest?)</p>
<p>We use the table primarily to transform a user-supplied string of keywords into an ordered list of components. This constitutes 95% of the use cases; the other 5% are "given a partial keyword string, supply all possible completions" and "generate all possible legal keyword strings". Oh, and validate the graph against malformation.</p>
<p>Here's an edited excerpt of the table. Columns are:</p>
<p>keyword innode outnode component</p>
<pre><code>acs 1 20 clear
default 1 100 clear
noota 20 30 clear
default 20 30 hst_ota
ota 20 30 hst_ota
acs 30 10000 clear
cos 30 11000 clear
sbc 10000 10199 clear
hrc 10000 10150 clear
wfc1 10000 10100 clear
default 10100 10101 clear
default 10101 10130 acs_wfc_im123
f606w 10130 10140 acs_f606w
f550m 10130 10140 acs_f550m
f555w 10130 10140 acs_f555w
default 10140 10300 clear
wfc1 10300 10310 acs_wfc_ebe_win12f
default 10310 10320 acs_wfc_ccd1
</code></pre>
<p>Given the keyword string "acs,wfc1,f555w" and this table, the traversal logic is:</p>
<ul>
<li><p>Start at node 1; "acs" is in the string, so go to node 20.</p></li>
<li><p>None of the presented keywords for node 20 are in the string, so choose the default, pick up hst_ota, and go to node 30.</p></li>
<li><p>"acs" is in the string, so go to node 10000.</p></li>
<li><p>"wfc1" is in the string, so go to node 10100.</p></li>
<li><p>Only one choice; go to node 10101.</p></li>
<li><p>Only one choice, so pick up acs_wfc_im123 and go to node 10130.</p></li>
<li><p>"f555w" is in the string, so pick up acs_f555w and go to node 10140.</p></li>
<li><p>Only one choice, so go to node 10300.</p></li>
<li><p>"wfc1" is in the string, so pick up acs_wfc_ebe_win12f and go to node 10310.</p></li>
<li><p>Only one choice, so pick up acs_wfc_ccd1 and go to node 10320 -- which doesn't exist, so we're done.</p></li>
</ul>
<p>Thus the final list of components is </p>
<pre><code>hst_ota
acs_wfc_im123
acs_f555w
acs_wfc_ebe_win12f
acs_wfc_ccd1
</code></pre>
<p>I can make a graph from just the innodes and outnodes of this table, but I couldn't for the life of me figure out how to build in the keyword information that determines which choice to make when faced with multiple possibilities. </p>
<p>Updated to add examples of the other use cases:</p>
<ul>
<li><p>Given a string "acs", return ("hrc","wfc1") as possible legal next choices</p></li>
<li><p>Given a string "acs, wfc1, foo", raise an exception due to an unused keyword</p></li>
<li><p>Return all possible legal strings:</p>
<ul>
<li>cos</li>
<li>acs, hrc</li>
<li>acs, wfc1, f606w</li>
<li>acs, wfc1, f550m</li>
<li>acs, wfc1, f555w</li>
</ul></li>
<li><p>Validate that all nodes can be reached and that there are no loops.</p></li>
</ul>
<p>I can tweak Alex's solution for the first two of these, but I don't see how to do it for the last two. </p>
| 2 | 2009-05-10T01:34:33Z | 845,659 | <p>Definitely not suitable for general purpose graph libraries (whatever you're supposed to do if more than one of the words meaningful in a node is in the input string -- is that an error? -- or if none does and there is no default for the node, as for node 30 in the example you supply). Just write the table as a dict from node to tuple (default stuff, dict from word to specific stuff) where each stuff is a tuple (destination, word-to-add) (and use None for the special "word-to-add" <code>clear</code>). So e.g.:</p>
<pre><code>tab = {1: (100, None), {'acs': (20, None)}),
20: ((30, 'hst_ota'), {'ota': (30, 'hst_ota'), 'noota': (30, None)}),
30: ((None, None), {'acs': (10000,None), 'cos':(11000,None)}),
etc etc
</code></pre>
<p>Now handling this table and an input comma-separated string is easy, thanks to set operations -- e.g.:</p>
<pre><code>def f(icss):
kws = set(icss.split(','))
N = 1
while N in tab:
stuff, others = tab[N]
found = kws & set(others)
if found:
# maybe error if len(found) > 1 ?
stuff = others[found.pop()]
N, word_to_add = stuff
if word_to_add is not None:
print word_to_add
</code></pre>
| 2 | 2009-05-10T16:57:30Z | [
"python",
"graph"
] |
Is a graph library (eg NetworkX) the right solution for my Python problem? | 844,505 | <p>I'm rewriting a data-driven legacy application in Python. One of the primary tables is referred to as a "graph table", and does appear to be a directed graph, so I was exploring the NetworkX package to see whether it would make sense to use it for the graph table manipulations, and really implement it as a graph rather than a complicated set of arrays.</p>
<p>However I'm starting to wonder whether the way we use this table is poorly suited for an actual graph manipulation library. Most of the NetworkX functionality seems to be oriented towards characterizing the graph itself in some way, determining shortest distance between two nodes, and things like that. None of that is relevant to my application. </p>
<p>I'm hoping if I can describe the actual usage here, someone can advise me whether I'm just missing something -- I've never really worked with graphs before so this is quite possible -- or if I should be exploring some other data structure. (And if so, what would you suggest?)</p>
<p>We use the table primarily to transform a user-supplied string of keywords into an ordered list of components. This constitutes 95% of the use cases; the other 5% are "given a partial keyword string, supply all possible completions" and "generate all possible legal keyword strings". Oh, and validate the graph against malformation.</p>
<p>Here's an edited excerpt of the table. Columns are:</p>
<p>keyword innode outnode component</p>
<pre><code>acs 1 20 clear
default 1 100 clear
noota 20 30 clear
default 20 30 hst_ota
ota 20 30 hst_ota
acs 30 10000 clear
cos 30 11000 clear
sbc 10000 10199 clear
hrc 10000 10150 clear
wfc1 10000 10100 clear
default 10100 10101 clear
default 10101 10130 acs_wfc_im123
f606w 10130 10140 acs_f606w
f550m 10130 10140 acs_f550m
f555w 10130 10140 acs_f555w
default 10140 10300 clear
wfc1 10300 10310 acs_wfc_ebe_win12f
default 10310 10320 acs_wfc_ccd1
</code></pre>
<p>Given the keyword string "acs,wfc1,f555w" and this table, the traversal logic is:</p>
<ul>
<li><p>Start at node 1; "acs" is in the string, so go to node 20.</p></li>
<li><p>None of the presented keywords for node 20 are in the string, so choose the default, pick up hst_ota, and go to node 30.</p></li>
<li><p>"acs" is in the string, so go to node 10000.</p></li>
<li><p>"wfc1" is in the string, so go to node 10100.</p></li>
<li><p>Only one choice; go to node 10101.</p></li>
<li><p>Only one choice, so pick up acs_wfc_im123 and go to node 10130.</p></li>
<li><p>"f555w" is in the string, so pick up acs_f555w and go to node 10140.</p></li>
<li><p>Only one choice, so go to node 10300.</p></li>
<li><p>"wfc1" is in the string, so pick up acs_wfc_ebe_win12f and go to node 10310.</p></li>
<li><p>Only one choice, so pick up acs_wfc_ccd1 and go to node 10320 -- which doesn't exist, so we're done.</p></li>
</ul>
<p>Thus the final list of components is </p>
<pre><code>hst_ota
acs_wfc_im123
acs_f555w
acs_wfc_ebe_win12f
acs_wfc_ccd1
</code></pre>
<p>I can make a graph from just the innodes and outnodes of this table, but I couldn't for the life of me figure out how to build in the keyword information that determines which choice to make when faced with multiple possibilities. </p>
<p>Updated to add examples of the other use cases:</p>
<ul>
<li><p>Given a string "acs", return ("hrc","wfc1") as possible legal next choices</p></li>
<li><p>Given a string "acs, wfc1, foo", raise an exception due to an unused keyword</p></li>
<li><p>Return all possible legal strings:</p>
<ul>
<li>cos</li>
<li>acs, hrc</li>
<li>acs, wfc1, f606w</li>
<li>acs, wfc1, f550m</li>
<li>acs, wfc1, f555w</li>
</ul></li>
<li><p>Validate that all nodes can be reached and that there are no loops.</p></li>
</ul>
<p>I can tweak Alex's solution for the first two of these, but I don't see how to do it for the last two. </p>
| 2 | 2009-05-10T01:34:33Z | 851,532 | <p>Adding an answer to respond to the further requirements newly edited in...: I still wouldn't go for a general-purpose library. For "all nodes can be reached and there are no loops", simply reasoning in terms of sets (ignoring the triggering keywords) should do: (again untested code, but the general outline should help even if there's some typo &c):</p>
<pre><code>def add_descendants(someset, node):
"auxiliary function: add all descendants of node to someset"
stuff, others = tab[node]
othernode, _ = stuff
if othernode is not None:
someset.add(othernode)
for othernode, _ in others.values():
if othernode is not None:
someset.add(othernode)
def islegal():
"Return bool, message (bool is True for OK tab, False if not OK)"
# make set of all nodes ever mentioned in the table
all_nodes = set()
for node in tab:
all_nodes.add(node)
add_desendants(all_nodes, node)
# check for loops and connectivity
previously_seen = set()
currently_seen = set([1])
while currently_seen:
node = currently_seen.pop()
if node in previously_seen:
return False, "loop involving node %s" % node
previously_seen.add(node)
add_descendants(currently_seen, node)
unreachable = all_nodes - currently_seen
if unreachable:
return False, "%d unreachable nodes: %s" % (len(unreachable), unreachable)
else:
terminal = currently_seen - set(tab)
if terminal:
return True, "%d terminal nodes: %s" % (len(terminal), terminal)
return True, "Everything hunky-dory"
</code></pre>
<p>For the "legal strings" you'll need some other code, but I can't write it for you because I have not yet understood what makes a string legal or otherwise...!</p>
| 0 | 2009-05-12T07:13:35Z | [
"python",
"graph"
] |
Python regex question: stripping multi-line comments but maintaining a line break | 844,681 | <p>I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /<em>....</em>/). However, if the multi-line comment has at least one line-break in it (\n), I want the output to have exactly one line break instead.</p>
<p>For example, the code:</p>
<pre><code>qwe /* 123
456
789 */ asd
</code></pre>
<p>should turn exactly into:</p>
<pre><code>qwe
asd
</code></pre>
<p>and not "qweasd" or:</p>
<pre><code>qwe
asd
</code></pre>
<p>What would be the best way to do so?
Thanks</p>
<p><hr /></p>
<p>EDIT:
Example code for testing:</p>
<pre><code>comments_test = "hello // comment\n"+\
"line 2 /* a comment */\n"+\
"line 3 /* a comment*/ /*comment*/\n"+\
"line 4 /* a comment\n"+\
"continuation of a comment*/ line 5\n"+\
"/* comment */line 6\n"+\
"line 7 /*********\n"+\
"********************\n"+\
"**************/\n"+\
"line ?? /*********\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"**************/\n"+\
"line ??"
</code></pre>
<p>Expected results:</p>
<pre><code>hello
line 2
line 3
line 4
line 5
line 6
line 7
line ??
line ??
</code></pre>
| 3 | 2009-05-10T04:20:41Z | 844,688 | <p>Is this what you're looking for?</p>
<pre><code>>>> print(s)
qwe /* 123
456
789 */ asd
>>> print(re.sub(r'\s*/\*.*\n.*\*/\s*', '\n', s, flags=re.S))
qwe
asd
</code></pre>
<p>This will work only for those comments that are more than one line, but will leave others alone. </p>
| 1 | 2009-05-10T04:30:47Z | [
"python",
"regex",
"parsing",
"comments"
] |
Python regex question: stripping multi-line comments but maintaining a line break | 844,681 | <p>I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /<em>....</em>/). However, if the multi-line comment has at least one line-break in it (\n), I want the output to have exactly one line break instead.</p>
<p>For example, the code:</p>
<pre><code>qwe /* 123
456
789 */ asd
</code></pre>
<p>should turn exactly into:</p>
<pre><code>qwe
asd
</code></pre>
<p>and not "qweasd" or:</p>
<pre><code>qwe
asd
</code></pre>
<p>What would be the best way to do so?
Thanks</p>
<p><hr /></p>
<p>EDIT:
Example code for testing:</p>
<pre><code>comments_test = "hello // comment\n"+\
"line 2 /* a comment */\n"+\
"line 3 /* a comment*/ /*comment*/\n"+\
"line 4 /* a comment\n"+\
"continuation of a comment*/ line 5\n"+\
"/* comment */line 6\n"+\
"line 7 /*********\n"+\
"********************\n"+\
"**************/\n"+\
"line ?? /*********\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"**************/\n"+\
"line ??"
</code></pre>
<p>Expected results:</p>
<pre><code>hello
line 2
line 3
line 4
line 5
line 6
line 7
line ??
line ??
</code></pre>
| 3 | 2009-05-10T04:20:41Z | 844,716 | <p>How about this:</p>
<pre><code>re.sub(r'\s*/\*(.|\n)*?\*/\s*', '\n', s, re.DOTALL).strip()
</code></pre>
<p>It attacks leading whitespace, <code>/*</code>, any text and newline up until the first <code>*\</code>, then any whitespace after that.</p>
<p>Its a little twist on sykora's example but it is also non-greedy on the inside. You also might want to look into the Multiline option.</p>
| 1 | 2009-05-10T04:56:47Z | [
"python",
"regex",
"parsing",
"comments"
] |
Python regex question: stripping multi-line comments but maintaining a line break | 844,681 | <p>I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /<em>....</em>/). However, if the multi-line comment has at least one line-break in it (\n), I want the output to have exactly one line break instead.</p>
<p>For example, the code:</p>
<pre><code>qwe /* 123
456
789 */ asd
</code></pre>
<p>should turn exactly into:</p>
<pre><code>qwe
asd
</code></pre>
<p>and not "qweasd" or:</p>
<pre><code>qwe
asd
</code></pre>
<p>What would be the best way to do so?
Thanks</p>
<p><hr /></p>
<p>EDIT:
Example code for testing:</p>
<pre><code>comments_test = "hello // comment\n"+\
"line 2 /* a comment */\n"+\
"line 3 /* a comment*/ /*comment*/\n"+\
"line 4 /* a comment\n"+\
"continuation of a comment*/ line 5\n"+\
"/* comment */line 6\n"+\
"line 7 /*********\n"+\
"********************\n"+\
"**************/\n"+\
"line ?? /*********\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"**************/\n"+\
"line ??"
</code></pre>
<p>Expected results:</p>
<pre><code>hello
line 2
line 3
line 4
line 5
line 6
line 7
line ??
line ??
</code></pre>
| 3 | 2009-05-10T04:20:41Z | 844,717 | <p>See <a href="http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns">can-regular-expressions-be-used-to-match-nested-patterns</a> - if you consider nested comments, regular expressions are not the solution.</p>
| 0 | 2009-05-10T04:57:04Z | [
"python",
"regex",
"parsing",
"comments"
] |
Python regex question: stripping multi-line comments but maintaining a line break | 844,681 | <p>I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /<em>....</em>/). However, if the multi-line comment has at least one line-break in it (\n), I want the output to have exactly one line break instead.</p>
<p>For example, the code:</p>
<pre><code>qwe /* 123
456
789 */ asd
</code></pre>
<p>should turn exactly into:</p>
<pre><code>qwe
asd
</code></pre>
<p>and not "qweasd" or:</p>
<pre><code>qwe
asd
</code></pre>
<p>What would be the best way to do so?
Thanks</p>
<p><hr /></p>
<p>EDIT:
Example code for testing:</p>
<pre><code>comments_test = "hello // comment\n"+\
"line 2 /* a comment */\n"+\
"line 3 /* a comment*/ /*comment*/\n"+\
"line 4 /* a comment\n"+\
"continuation of a comment*/ line 5\n"+\
"/* comment */line 6\n"+\
"line 7 /*********\n"+\
"********************\n"+\
"**************/\n"+\
"line ?? /*********\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"**************/\n"+\
"line ??"
</code></pre>
<p>Expected results:</p>
<pre><code>hello
line 2
line 3
line 4
line 5
line 6
line 7
line ??
line ??
</code></pre>
| 3 | 2009-05-10T04:20:41Z | 844,721 | <pre><code>comment_re = re.compile(
r'(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
re.DOTALL | re.MULTILINE
)
def comment_replacer(match):
start,mid,end = match.group(1,2,3)
if mid is None:
# single line comment
return ''
elif start is not None or end is not None:
# multi line comment at start or end of a line
return ''
elif '\n' in mid:
# multi line comment with line break
return '\n'
else:
# multi line comment without line break
return ' '
def remove_comments(text):
return comment_re.sub(comment_replacer, text)
</code></pre>
<ul>
<li><code>(^)?</code> will match if the comment starts at the beginning of a line, as long as the <code>MULTILINE</code>-flag is used.</li>
<li><code>[^\S\n]</code> will match any whitespace character except newline. We don't want to match line breaks if the comment starts on it's own line.</li>
<li><code>/\*(.*?)\*/</code> will match a multi-line comment and capture the content. Lazy matching, so we don't match two or more comments. <code>DOTALL</code>-flag makes <code>.</code> match newlines.</li>
<li><code>//[^\n]</code> will match a single-line comment. Can't use <code>.</code> because of the <code>DOTALL</code>-flag.</li>
<li><code>($)?</code> will match if the comment stops at the end of a line, as long as the <code>MULTILINE</code>-flag is used.</li>
</ul>
<p>Examples:</p>
<pre><code>>>> s = ("qwe /* 123\n"
"456\n"
"789 */ asd /* 123 */ zxc\n"
"rty // fgh\n")
>>> print '"' + '"\n"'.join(
... remove_comments(s).splitlines()
... ) + '"'
"qwe"
"asd zxc"
"rty"
>>> comments_test = ("hello // comment\n"
... "line 2 /* a comment */\n"
... "line 3 /* a comment*/ /*comment*/\n"
... "line 4 /* a comment\n"
... "continuation of a comment*/ line 5\n"
... "/* comment */line 6\n"
... "line 7 /*********\n"
... "********************\n"
... "**************/\n"
... "line ?? /*********\n"
... "********************\n"
... "********************\n"
... "********************\n"
... "********************\n"
... "**************/\n")
>>> print '"' + '"\n"'.join(
... remove_comments(comments_test).splitlines()
... ) + '"'
"hello"
"line 2"
"line 3 "
"line 4"
"line 5"
"line 6"
"line 7"
"line ??"
"line ??"
</code></pre>
<p><strong>Edits:</strong></p>
<ul>
<li>Updated to new specification.</li>
<li>Added another example.</li>
</ul>
| 9 | 2009-05-10T05:01:02Z | [
"python",
"regex",
"parsing",
"comments"
] |
Python regex question: stripping multi-line comments but maintaining a line break | 844,681 | <p>I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /<em>....</em>/). However, if the multi-line comment has at least one line-break in it (\n), I want the output to have exactly one line break instead.</p>
<p>For example, the code:</p>
<pre><code>qwe /* 123
456
789 */ asd
</code></pre>
<p>should turn exactly into:</p>
<pre><code>qwe
asd
</code></pre>
<p>and not "qweasd" or:</p>
<pre><code>qwe
asd
</code></pre>
<p>What would be the best way to do so?
Thanks</p>
<p><hr /></p>
<p>EDIT:
Example code for testing:</p>
<pre><code>comments_test = "hello // comment\n"+\
"line 2 /* a comment */\n"+\
"line 3 /* a comment*/ /*comment*/\n"+\
"line 4 /* a comment\n"+\
"continuation of a comment*/ line 5\n"+\
"/* comment */line 6\n"+\
"line 7 /*********\n"+\
"********************\n"+\
"**************/\n"+\
"line ?? /*********\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"**************/\n"+\
"line ??"
</code></pre>
<p>Expected results:</p>
<pre><code>hello
line 2
line 3
line 4
line 5
line 6
line 7
line ??
line ??
</code></pre>
| 3 | 2009-05-10T04:20:41Z | 844,731 | <p>The fact that you have to even ask this question, and that the solutions given are, shall we say, less than perfectly readable :-) should be a good indication that REs are not the real answer to this question.</p>
<p>You would be far better, from a readability viewpoint, to actually code this up as a relatively simple parser.</p>
<p>Too often, people try to use REs to be "clever" (I don't mean that in a disparaging way), thinking that a single line is elegant, but all they end up with is an unmaintainable morass of characters. I'd rather have a fully commented 20-line solution that I can understand in an instant.</p>
| 5 | 2009-05-10T05:07:18Z | [
"python",
"regex",
"parsing",
"comments"
] |
Performing a getattr() style lookup in a django template | 844,746 | <p>Python's getattr() method is useful when you don't know the name of a certain attribute in advance.</p>
<p>This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups? </p>
| 31 | 2009-05-10T05:15:16Z | 844,764 | <p>There isn't a built-in tag, but it shouldn't be too difficult to <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags" rel="nofollow">write your own</a>.</p>
| 0 | 2009-05-10T05:29:51Z | [
"python",
"django",
"django-templates"
] |
Performing a getattr() style lookup in a django template | 844,746 | <p>Python's getattr() method is useful when you don't know the name of a certain attribute in advance.</p>
<p>This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups? </p>
| 31 | 2009-05-10T05:15:16Z | 844,774 | <p>I don't think so. But it wouldn't be too hard to write a <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/" rel="nofollow">custom template tag</a> to return an attribute in the context dict. If you're simply trying to return a string, try something like this:</p>
<pre><code>class GetAttrNode(template.Node):
def __init__(self, attr_name):
self.attr_name = attr_name
def render(self, context):
try:
return context[self.attr_name]
except:
# (better yet, return an exception here)
return ''
@register.tag
def get_attr(parser, token):
return GetAttrNode(token)
</code></pre>
<p>Note that it's probably just as easy to do this in your view instead of in the template, unless this is a condition that is repeated often in your data.</p>
| 2 | 2009-05-10T05:35:31Z | [
"python",
"django",
"django-templates"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.