title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
Listing the processes running on one's computer in Python | 367,068 | <p>Is there a cross-platform way to list the processes running on one's computer through a python script? For Unix based system "ps -ef" works, but I am new to Python and don't know a way to write something that would work across any platform.</p>
<p>Thanks!</p>
| 3 | 2008-12-14T22:20:34Z | 367,083 | <p>Python itself doesn't offer any such functionality. On PyPI, there is the <a href="http://pypi.python.org/pypi/enumprocess/0.1" rel="nofollow">enumprocess</a> package, which supposedly helps; there is also the <a href="http://www.psychofx.com/psi/trac/wiki/" rel="nofollow">PSI</a> package. I haven't personally used any of them.</p>
| 2 | 2008-12-14T22:30:57Z | [
"python",
"cross-platform",
"process"
] |
Listing the processes running on one's computer in Python | 367,068 | <p>Is there a cross-platform way to list the processes running on one's computer through a python script? For Unix based system "ps -ef" works, but I am new to Python and don't know a way to write something that would work across any platform.</p>
<p>Thanks!</p>
| 3 | 2008-12-14T22:20:34Z | 5,484,303 | <p>While <a href="https://bitbucket.org/chrismiles/psi/wiki/Home" rel="nofollow">PSI</a> page lists some alternatives, what you need is <a href="http://code.google.com/p/psutil/" rel="nofollow">psutil</a>. It is the only one that supports Windows, or as it states on a home page:</p>
<blockquote>
<p>Linux, Windows, OSX and FreeBSD both
32-bit and 64-bit with Python versions
from 2.4 to 3.2.</p>
</blockquote>
| 1 | 2011-03-30T09:10:07Z | [
"python",
"cross-platform",
"process"
] |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | <p>I know of <code>python -c '<code>'</code>, but I'm wondering if there's a more elegant python equivalent to <code>perl -pi -e '<code>'</code>. I still use it quite a bit for things like find and replace in a whole directory (<code>perl -pi -e s/foo/bar/g *</code> or even <code>find . | xargs perl -pi -e s/foo/bar/g</code> for sub-directories).</p>
<p>I actually feel that that which makes Perl Perl (free form Tim Toady-ness) is what makes <code>perl -pi -e</code> work so well, while with Python you'd have to do something along the lines of importing the re module, creating an re instance and then capture stdin, but maybe there's a Python shortcut that does all that and I missed it (sorely missed it)...</p>
| 15 | 2008-12-14T22:57:33Z | 367,136 | <p>Python is for muggles. If magic you want, Perl you should use!</p>
| 23 | 2008-12-14T23:12:50Z | [
"python",
"perl",
"command-line",
"language-features"
] |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | <p>I know of <code>python -c '<code>'</code>, but I'm wondering if there's a more elegant python equivalent to <code>perl -pi -e '<code>'</code>. I still use it quite a bit for things like find and replace in a whole directory (<code>perl -pi -e s/foo/bar/g *</code> or even <code>find . | xargs perl -pi -e s/foo/bar/g</code> for sub-directories).</p>
<p>I actually feel that that which makes Perl Perl (free form Tim Toady-ness) is what makes <code>perl -pi -e</code> work so well, while with Python you'd have to do something along the lines of importing the re module, creating an re instance and then capture stdin, but maybe there's a Python shortcut that does all that and I missed it (sorely missed it)...</p>
| 15 | 2008-12-14T22:57:33Z | 367,181 | <p>The command line usage from '<code>python -h</code>' certainly strongly suggests there is no such equivalent. Perl tends to make extensive use of '<code>$_</code>' (your examples make implicit use of it), and I don't think Python supports any similar concept, thereby making Python equivalents of the Perl one-liners much harder.</p>
| 9 | 2008-12-14T23:53:48Z | [
"python",
"perl",
"command-line",
"language-features"
] |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | <p>I know of <code>python -c '<code>'</code>, but I'm wondering if there's a more elegant python equivalent to <code>perl -pi -e '<code>'</code>. I still use it quite a bit for things like find and replace in a whole directory (<code>perl -pi -e s/foo/bar/g *</code> or even <code>find . | xargs perl -pi -e s/foo/bar/g</code> for sub-directories).</p>
<p>I actually feel that that which makes Perl Perl (free form Tim Toady-ness) is what makes <code>perl -pi -e</code> work so well, while with Python you'd have to do something along the lines of importing the re module, creating an re instance and then capture stdin, but maybe there's a Python shortcut that does all that and I missed it (sorely missed it)...</p>
| 15 | 2008-12-14T22:57:33Z | 367,238 | <p>An equivalent to -pi isn't that hard to write in Python.</p>
<ol>
<li><p>Write yourself a handy module with the -p and -i features you really like. Let's call it <code>pypi.py</code>.</p></li>
<li><p>Use <code>python -c 'import pypi; pypi.subs("this","that")'</code></p></li>
</ol>
<p>You can implement the basic -p loop with the <a href="http://docs.python.org/library/fileinput.html">fileinput</a> module.</p>
<p>You'd have a function, <code>subs</code> that implements the essential "-i" algorithm of opening a file, saving the backup copy, and doing the substitute on each line.</p>
<p>There are some activestate recipes like this. Here are some:</p>
<ul>
<li><a href="http://code.activestate.com/recipes/437932/">http://code.activestate.com/recipes/437932/</a></li>
<li><a href="http://code.activestate.com/recipes/435904/">http://code.activestate.com/recipes/435904/</a></li>
<li><a href="http://code.activestate.com/recipes/576537/">http://code.activestate.com/recipes/576537/</a></li>
</ul>
<p>Not built-in. But not difficult to write. And once written easy to customize.</p>
| 9 | 2008-12-15T00:58:30Z | [
"python",
"perl",
"command-line",
"language-features"
] |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | <p>I know of <code>python -c '<code>'</code>, but I'm wondering if there's a more elegant python equivalent to <code>perl -pi -e '<code>'</code>. I still use it quite a bit for things like find and replace in a whole directory (<code>perl -pi -e s/foo/bar/g *</code> or even <code>find . | xargs perl -pi -e s/foo/bar/g</code> for sub-directories).</p>
<p>I actually feel that that which makes Perl Perl (free form Tim Toady-ness) is what makes <code>perl -pi -e</code> work so well, while with Python you'd have to do something along the lines of importing the re module, creating an re instance and then capture stdin, but maybe there's a Python shortcut that does all that and I missed it (sorely missed it)...</p>
| 15 | 2008-12-14T22:57:33Z | 367,260 | <p>I think perl is better suited for this kind of on the fly scripting. If you want quick on the fly one-off scripting capability I recommend sticking to perl, awk, sed, and standard unix command-line tools.</p>
<p>But if your interested in using python, I use <a href="http://docs.python.org/library/optparse.html" rel="nofollow">optparse</a> to write my own command line tools and recommend it.
optparse provides a clean and easy-to-use command line option parser with built in help generation.</p>
<p>Here's a sample:</p>
<pre><code>def myfunc(filename, use_versbose):
# function code
if __name__ == '__main__':
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
(options, args) = parser.parse_args()
if options.filename:
myfunc(options.filename, options.verbose)
else:
print 'ERROR -- Necessary command line options not given!'
print parser.print_help()
</code></pre>
<p>parser.print_help() generates the following output, and is automatically displayed when -h or --help is given at the command line:</p>
<pre><code>usage: <yourscript> [options]
options:
-h, --help show this help message and exit
-f FILE, --file=FILE write report to FILE
-q, --quiet don't print status messages to stdout
</code></pre>
| 6 | 2008-12-15T01:23:27Z | [
"python",
"perl",
"command-line",
"language-features"
] |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | <p>I know of <code>python -c '<code>'</code>, but I'm wondering if there's a more elegant python equivalent to <code>perl -pi -e '<code>'</code>. I still use it quite a bit for things like find and replace in a whole directory (<code>perl -pi -e s/foo/bar/g *</code> or even <code>find . | xargs perl -pi -e s/foo/bar/g</code> for sub-directories).</p>
<p>I actually feel that that which makes Perl Perl (free form Tim Toady-ness) is what makes <code>perl -pi -e</code> work so well, while with Python you'd have to do something along the lines of importing the re module, creating an re instance and then capture stdin, but maybe there's a Python shortcut that does all that and I missed it (sorely missed it)...</p>
| 15 | 2008-12-14T22:57:33Z | 9,611,564 | <p>The fileinput module has the capability for in-place editing. You can't dispense with the backups, though. Here's how to use it for a one-liner:</p>
<pre class="lang-sh prettyprint-override"><code>python -c 'import fileinput, sys; for line in fileinput.input(inplace=True): sys.stdout.write(line, "foo", "bar")'
</code></pre>
<p>Personally, I just usually use Perl when I need to do something like this. It is one of the few times I use Perl.</p>
| 1 | 2012-03-08T01:05:00Z | [
"python",
"perl",
"command-line",
"language-features"
] |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | <p>I know of <code>python -c '<code>'</code>, but I'm wondering if there's a more elegant python equivalent to <code>perl -pi -e '<code>'</code>. I still use it quite a bit for things like find and replace in a whole directory (<code>perl -pi -e s/foo/bar/g *</code> or even <code>find . | xargs perl -pi -e s/foo/bar/g</code> for sub-directories).</p>
<p>I actually feel that that which makes Perl Perl (free form Tim Toady-ness) is what makes <code>perl -pi -e</code> work so well, while with Python you'd have to do something along the lines of importing the re module, creating an re instance and then capture stdin, but maybe there's a Python shortcut that does all that and I missed it (sorely missed it)...</p>
| 15 | 2008-12-14T22:57:33Z | 14,429,701 | <p>I know this is a couple of years too late, but I've recently
found a very nice tool called <a href="http://code.google.com/p/pyp/">pyp</a>, which does
exactly what you've asked for.</p>
<p>I think your command should be:</p>
<pre><code>pyp "p.replace('foo','bar')"
</code></pre>
| 9 | 2013-01-20T21:45:29Z | [
"python",
"perl",
"command-line",
"language-features"
] |
Is there a Python equivalent to `perl -pi -e`? | 367,115 | <p>I know of <code>python -c '<code>'</code>, but I'm wondering if there's a more elegant python equivalent to <code>perl -pi -e '<code>'</code>. I still use it quite a bit for things like find and replace in a whole directory (<code>perl -pi -e s/foo/bar/g *</code> or even <code>find . | xargs perl -pi -e s/foo/bar/g</code> for sub-directories).</p>
<p>I actually feel that that which makes Perl Perl (free form Tim Toady-ness) is what makes <code>perl -pi -e</code> work so well, while with Python you'd have to do something along the lines of importing the re module, creating an re instance and then capture stdin, but maybe there's a Python shortcut that does all that and I missed it (sorely missed it)...</p>
| 15 | 2008-12-14T22:57:33Z | 24,758,853 | <p>The above may work for stdin, but does not look like it would work for a file.</p>
<p>Maybe something like:</p>
<p>--</p>
<pre><code>import fileinput
import sys
for line in fileinput.input("./poop", inplace=True):
line = line.replace("foo", "bar")
sys.stdout.write(line)
</code></pre>
<p>--
where "./poop" can be replaced with where your file is and line.replace should support things like line.replace("{}".format(variablehere),"newtext")</p>
| 0 | 2014-07-15T13:00:01Z | [
"python",
"perl",
"command-line",
"language-features"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ',', 'me']
</code></pre>
<p>So, I want the string split at whitespace with the punctuation split from the words.</p>
<p>I've tried to parse the string first and then run the split:</p>
<pre><code>>>> for character in c:
... if character in ".,;!?":
... outputCharacter = " %s" % character
... else:
... outputCharacter = character
... separatedPunctuation += outputCharacter
>>> print separatedPunctuation
help , me
>>> print separatedPunctuation.split()
['help', ',', 'me']
</code></pre>
<p>This produces the result I want, but is painfully slow on large files.</p>
<p>Is there a way to do this more efficiently?</p>
| 22 | 2008-12-14T23:30:33Z | 367,160 | <p>Have you tried using a regex?</p>
<p><a href="http://docs.python.org/library/re.html#re-syntax" rel="nofollow">http://docs.python.org/library/re.html#re-syntax</a></p>
<p><hr /></p>
<p>By the way. Why do you need the "," at the second one? You will know that after each text is written i.e. </p>
<p>[0]</p>
<p>","</p>
<p>[1]</p>
<p>","</p>
<p>So if you want to add the "," you can just do it after each iteration when you use the array..</p>
| 0 | 2008-12-14T23:34:49Z | [
"python",
"string",
"split"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ',', 'me']
</code></pre>
<p>So, I want the string split at whitespace with the punctuation split from the words.</p>
<p>I've tried to parse the string first and then run the split:</p>
<pre><code>>>> for character in c:
... if character in ".,;!?":
... outputCharacter = " %s" % character
... else:
... outputCharacter = character
... separatedPunctuation += outputCharacter
>>> print separatedPunctuation
help , me
>>> print separatedPunctuation.split()
['help', ',', 'me']
</code></pre>
<p>This produces the result I want, but is painfully slow on large files.</p>
<p>Is there a way to do this more efficiently?</p>
| 22 | 2008-12-14T23:30:33Z | 367,204 | <p>In perl-style regular expression syntax, <code>\b</code> matches a word boundary. This should come in handy for doing a regex-based split.</p>
<p><em>edit:</em> I have been informed by hop that "empty matches" do not work in the split function of Python's re module. I will leave this here as information for anyone else getting stumped by this "feature".</p>
| 5 | 2008-12-15T00:25:08Z | [
"python",
"string",
"split"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ',', 'me']
</code></pre>
<p>So, I want the string split at whitespace with the punctuation split from the words.</p>
<p>I've tried to parse the string first and then run the split:</p>
<pre><code>>>> for character in c:
... if character in ".,;!?":
... outputCharacter = " %s" % character
... else:
... outputCharacter = character
... separatedPunctuation += outputCharacter
>>> print separatedPunctuation
help , me
>>> print separatedPunctuation.split()
['help', ',', 'me']
</code></pre>
<p>This produces the result I want, but is painfully slow on large files.</p>
<p>Is there a way to do this more efficiently?</p>
| 22 | 2008-12-14T23:30:33Z | 367,209 | <p>I think you can find all the help you can imagine in the <a href="http://nltk.org" rel="nofollow">NLTK</a>, especially since you are using python. There's a good comprehensive discussion of this issue in the tutorial.</p>
| 0 | 2008-12-15T00:34:08Z | [
"python",
"string",
"split"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ',', 'me']
</code></pre>
<p>So, I want the string split at whitespace with the punctuation split from the words.</p>
<p>I've tried to parse the string first and then run the split:</p>
<pre><code>>>> for character in c:
... if character in ".,;!?":
... outputCharacter = " %s" % character
... else:
... outputCharacter = character
... separatedPunctuation += outputCharacter
>>> print separatedPunctuation
help , me
>>> print separatedPunctuation.split()
['help', ',', 'me']
</code></pre>
<p>This produces the result I want, but is painfully slow on large files.</p>
<p>Is there a way to do this more efficiently?</p>
| 22 | 2008-12-14T23:30:33Z | 367,244 | <p>Here's a minor update to your implementation. If your trying to doing anything more detailed I suggest looking into the NLTK that le dorfier suggested.</p>
<p>This might only be a little faster since ''.join() is used in place of +=, which is <a href="http://www.skymind.com/~ocrow/python_string/" rel="nofollow">known to be faster</a>.</p>
<pre><code>import string
d = "Hello, I'm a string!"
result = []
word = ''
for char in d:
if char not in string.whitespace:
if char not in string.ascii_letters + "'":
if word:
result.append(word)
result.append(char)
word = ''
else:
word = ''.join([word,char])
else:
if word:
result.append(word)
word = ''
print result
['Hello', ',', "I'm", 'a', 'string', '!']
</code></pre>
| 0 | 2008-12-15T01:05:11Z | [
"python",
"string",
"split"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ',', 'me']
</code></pre>
<p>So, I want the string split at whitespace with the punctuation split from the words.</p>
<p>I've tried to parse the string first and then run the split:</p>
<pre><code>>>> for character in c:
... if character in ".,;!?":
... outputCharacter = " %s" % character
... else:
... outputCharacter = character
... separatedPunctuation += outputCharacter
>>> print separatedPunctuation
help , me
>>> print separatedPunctuation.split()
['help', ',', 'me']
</code></pre>
<p>This produces the result I want, but is painfully slow on large files.</p>
<p>Is there a way to do this more efficiently?</p>
| 22 | 2008-12-14T23:30:33Z | 367,265 | <p>Here's my entry.</p>
<p>I have my doubts as to how well this will hold up in the sense of efficiency, or if it catches all cases (note the "!!!" grouped together; this may or may not be a good thing).</p>
<pre><code>>>> import re
>>> import string
>>> s = "Helo, my name is Joe! and i live!!! in a button; factory:"
>>> l = [item for item in map(string.strip, re.split("(\W+)", s)) if len(item) > 0]
>>> l
['Helo', ',', 'my', 'name', 'is', 'Joe', '!', 'and', 'i', 'live', '!!!', 'in', 'a', 'button', ';', 'factory', ':']
>>>
</code></pre>
<p>One obvious optimization would be to compile the regex before hand (using re.compile) if you're going to be doing this on a line-by-line basis. </p>
| 1 | 2008-12-15T01:30:32Z | [
"python",
"string",
"split"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ',', 'me']
</code></pre>
<p>So, I want the string split at whitespace with the punctuation split from the words.</p>
<p>I've tried to parse the string first and then run the split:</p>
<pre><code>>>> for character in c:
... if character in ".,;!?":
... outputCharacter = " %s" % character
... else:
... outputCharacter = character
... separatedPunctuation += outputCharacter
>>> print separatedPunctuation
help , me
>>> print separatedPunctuation.split()
['help', ',', 'me']
</code></pre>
<p>This produces the result I want, but is painfully slow on large files.</p>
<p>Is there a way to do this more efficiently?</p>
| 22 | 2008-12-14T23:30:33Z | 367,292 | <p>This is more or less the way to do it:</p>
<pre><code>>>> import re
>>> re.findall(r"[\w']+|[.,!?;]", "Hello, I'm a string!")
['Hello', ',', "I'm", 'a', 'string', '!']
</code></pre>
<p>The trick is, not to think about where to split the string, but what to include in the tokens.</p>
<p>Caveats:</p>
<ul>
<li>The underscore (_) is considered an inner-word character. Replace \w, if you don't want that.</li>
<li>This will not work with (single) quotes in the string.</li>
<li>Put any additional punctuation marks you want to use in the right half of the regular expression.</li>
<li>Anything not explicitely mentioned in the re is silently dropped.</li>
</ul>
| 35 | 2008-12-15T01:53:18Z | [
"python",
"string",
"split"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ',', 'me']
</code></pre>
<p>So, I want the string split at whitespace with the punctuation split from the words.</p>
<p>I've tried to parse the string first and then run the split:</p>
<pre><code>>>> for character in c:
... if character in ".,;!?":
... outputCharacter = " %s" % character
... else:
... outputCharacter = character
... separatedPunctuation += outputCharacter
>>> print separatedPunctuation
help , me
>>> print separatedPunctuation.split()
['help', ',', 'me']
</code></pre>
<p>This produces the result I want, but is painfully slow on large files.</p>
<p>Is there a way to do this more efficiently?</p>
| 22 | 2008-12-14T23:30:33Z | 8,930,959 | <p>Here is a Unicode-aware version:</p>
<pre><code>re.findall(r"\w+|[^\w\s]", text, re.UNICODE)
</code></pre>
<p>The first alternative catches sequences of word characters (as defined by unicode, so "résumé" won't turn into <code>['r', 'sum']</code>); the second catches individual non-word characters, ignoring whitespace.</p>
<p>Note that, unlike the top answer, this treats the single quote as separate punctuation (e.g. "I'm" -> <code>['I', "'", 'm']</code>). This appears to be standard in NLP, so I consider it a feature.</p>
| 13 | 2012-01-19T17:58:09Z | [
"python",
"string",
"split"
] |
Splitting a string into words and punctuation | 367,155 | <p>I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split.</p>
<p>For instance:</p>
<pre><code>>>> c = "help, me"
>>> print c.split()
['help,', 'me']
</code></pre>
<p>What I really want the list to look like is:</p>
<pre><code>['help', ',', 'me']
</code></pre>
<p>So, I want the string split at whitespace with the punctuation split from the words.</p>
<p>I've tried to parse the string first and then run the split:</p>
<pre><code>>>> for character in c:
... if character in ".,;!?":
... outputCharacter = " %s" % character
... else:
... outputCharacter = character
... separatedPunctuation += outputCharacter
>>> print separatedPunctuation
help , me
>>> print separatedPunctuation.split()
['help', ',', 'me']
</code></pre>
<p>This produces the result I want, but is painfully slow on large files.</p>
<p>Is there a way to do this more efficiently?</p>
| 22 | 2008-12-14T23:30:33Z | 23,092,385 | <p>I came up with a way to tokenize all words and <code>\W+</code> patterns using <code>\b</code> which doesn't need hardcoding:</p>
<pre><code>>>> import re
>>> sentence = 'Hello, world!'
>>> tokens = [t.strip() for t in re.findall(r'\b.*?\S.*?(?:\b|$)', sentence)]
['Hello', ',', 'world', '!']
</code></pre>
<p>Here <code>.*?\S.*?</code> is a pattern matching anything that is not a space and <code>$</code> is added to match last token in a string if it's a punctuation symbol.</p>
<p>Note the following though -- this will group punctuation that consists of more than one symbol:</p>
<pre><code>>>> print [t.strip() for t in re.findall(r'\b.*?\S.*?(?:\b|$)', '"Oh no", she said')]
['Oh', 'no', '",', 'she', 'said']
</code></pre>
<p>Of course, you can find and split such groups with:</p>
<pre><code>>>> for token in [t.strip() for t in re.findall(r'\b.*?\S.*?(?:\b|$)', '"You can", she said')]:
... print re.findall(r'(?:\w+|\W)', token)
['You']
['can']
['"', ',']
['she']
['said']
</code></pre>
| 0 | 2014-04-15T19:11:22Z | [
"python",
"string",
"split"
] |
Setting up a foreign key to an abstract base class with Django | 367,461 | <p>I've factored out common attributes from two classes into an abstract base class, however I have another model that needs to reference either one of those classes. It's not possible to reference an ABC as it doesn't actually have a database table.</p>
<p>The following example should illustrate my problem:</p>
<pre><code>class Answer(models.Model):
ovramt = models.ForeignKey("Ovramt")
question = models.ForeignKey("Question")
answer = models.CharField(max_length=3, choices=(("yes","yes"),("no","no") ("NA","N/A"))
likelihood = models.IntegerField(choices=LIKELY_CHOICES)
consequence = models.IntegerField(choices=CONSEQUENCE_CHOICES)
class Meta:
abstract = True
class Answer_A(Answer):
resident = models.ForeignKey("Resident")
def __unicode__(self):
return u"%s - %s - %s" %(self.ovramt.ssa.name, self.resident, self.question)
class Answer_B(Answer):
def __unicode__(self):
return u"%s - %s" %(self.ovramt.ssa.name, self.question)
class Answer_Risk(models.Model):
answer = models.ForeignKey("Answer")
risk = models.CharField(max_length=200)
def __unicode__(self):
return self.risk
</code></pre>
<p>Answer_A and Answer_B are slightly different in that Answer_A also needs a FK relationship to another table. Answer_B may also require some specific attributes later. The problem would STILL exist if I had Answer_B be the superclass - and have Answer_A subclass or compose it.</p>
<p>A 'Risk' is the same whether it's Answer_A or Answer_B. I also have other models that need to reference an 'Answer' regardless of it's sub-type. How can this be done? How can you reference a type regardless of it's sub-type?</p>
<p>Update:<br />
I was trying to avoid a join operation but I don't think I'm going to be able to. Would it be worth having the reference to 'Resident' in all 'Answer's and just nulling it where required? Or is that considered very bad practice? </p>
| 21 | 2008-12-15T04:16:33Z | 367,479 | <p>My gut would be to suggest removing the abstract modifier on the base class. You'll get the same model structure, but Answer will be it's own table. The downside of this is that if these are large tables and/or your queries are complex, queries against it could be noticeably slower.</p>
<p>Alternatively, you could keep your models as is, but replace the ForeignKey to Animal with a <a href="https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations" rel="nofollow">GenericForeignKey</a>. What you lose in the syntactic sugar of model inheritance, you gain a bit in query speed.</p>
<p>I don't believe it's possible to reference an abstract base model by ForeignKey (or anything functionally the same).</p>
| 7 | 2008-12-15T04:33:46Z | [
"python",
"django",
"inheritance",
"django-models"
] |
Setting up a foreign key to an abstract base class with Django | 367,461 | <p>I've factored out common attributes from two classes into an abstract base class, however I have another model that needs to reference either one of those classes. It's not possible to reference an ABC as it doesn't actually have a database table.</p>
<p>The following example should illustrate my problem:</p>
<pre><code>class Answer(models.Model):
ovramt = models.ForeignKey("Ovramt")
question = models.ForeignKey("Question")
answer = models.CharField(max_length=3, choices=(("yes","yes"),("no","no") ("NA","N/A"))
likelihood = models.IntegerField(choices=LIKELY_CHOICES)
consequence = models.IntegerField(choices=CONSEQUENCE_CHOICES)
class Meta:
abstract = True
class Answer_A(Answer):
resident = models.ForeignKey("Resident")
def __unicode__(self):
return u"%s - %s - %s" %(self.ovramt.ssa.name, self.resident, self.question)
class Answer_B(Answer):
def __unicode__(self):
return u"%s - %s" %(self.ovramt.ssa.name, self.question)
class Answer_Risk(models.Model):
answer = models.ForeignKey("Answer")
risk = models.CharField(max_length=200)
def __unicode__(self):
return self.risk
</code></pre>
<p>Answer_A and Answer_B are slightly different in that Answer_A also needs a FK relationship to another table. Answer_B may also require some specific attributes later. The problem would STILL exist if I had Answer_B be the superclass - and have Answer_A subclass or compose it.</p>
<p>A 'Risk' is the same whether it's Answer_A or Answer_B. I also have other models that need to reference an 'Answer' regardless of it's sub-type. How can this be done? How can you reference a type regardless of it's sub-type?</p>
<p>Update:<br />
I was trying to avoid a join operation but I don't think I'm going to be able to. Would it be worth having the reference to 'Resident' in all 'Answer's and just nulling it where required? Or is that considered very bad practice? </p>
| 21 | 2008-12-15T04:16:33Z | 367,765 | <p>A <a href="https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations">generic relation</a> seems to be the solution. But it will complicate things even further.</p>
<p>It seems to me; your model structure is already more complex than necessary. I would simply merge all three <code>Answer</code> models into one. This way:</p>
<ul>
<li><code>Answer_Risk</code> would work without modification.</li>
<li>You can set <code>resident</code> to None (NULL) in case of an <code>Answer_A</code>.</li>
<li>You can return different string represantations depending on <code>resident == None</code>. (in other words; same functionality)</li>
</ul>
<p>One more thing; are your answers likely to have more than one risk? If they'll have none or one risk you should consider following alternative implementations:</p>
<ul>
<li>Using a <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#one-to-one-relationships">one-to-one relationship</a></li>
<li>Demoting risk as a field (or any number of fields) inside <code>Answer</code> class.</li>
</ul>
<p>My main concern is neither database structure nor performance (although these changes should improve performance) but <em>code maintainability</em>.</p>
| 15 | 2008-12-15T08:24:54Z | [
"python",
"django",
"inheritance",
"django-models"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def sum(nums):
"""Same as the built-in sum()... computes the sum of all the numbers passed in."""
</code></pre>
<p>How thoroughly do you check the input values before beginning computation, and how do you do your checking? Do you throw some kind of proprietary exception if input is faulty (BadInputException defined in the same module, for example)? Do you just start your calculation and figure it will throw an exception at some point if bad data was passed in ("asd" to factorial, for example)?</p>
<p>When the passed in value is supposed to be a container do you check not only the container but all the values inside it?</p>
<p>What about situations like factorial, where what's passed in might be convertible to an int (e.g. a float) but you might lose precision when doing so?</p>
| 15 | 2008-12-15T05:39:52Z | 367,568 | <p>I basically try to convert the variable to what it should be and pass up or throw the appropriate exception if that fails.</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
try:
num = int(num)
except ValueError, e:
print e
else:
...
</code></pre>
| 4 | 2008-12-15T05:45:11Z | [
"python",
"validation"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def sum(nums):
"""Same as the built-in sum()... computes the sum of all the numbers passed in."""
</code></pre>
<p>How thoroughly do you check the input values before beginning computation, and how do you do your checking? Do you throw some kind of proprietary exception if input is faulty (BadInputException defined in the same module, for example)? Do you just start your calculation and figure it will throw an exception at some point if bad data was passed in ("asd" to factorial, for example)?</p>
<p>When the passed in value is supposed to be a container do you check not only the container but all the values inside it?</p>
<p>What about situations like factorial, where what's passed in might be convertible to an int (e.g. a float) but you might lose precision when doing so?</p>
| 15 | 2008-12-15T05:39:52Z | 367,699 | <p>It rather depends on what I'm writing, and how the output gets there. Python doesn't have the public/private protections of other OO-languages. Instead there are conventions. For example, external code should only call object methods that are not prefixed by an underscore.</p>
<p>Therefore, if I'm writing a module, I'd validate anything that is not generated from my own code, i.e. any calls to publicly-accessible methods/functions. Sometimes, if I know the validation is expensive, I make it togglable with a kwarg:</p>
<pre><code>def publicly_accessible_function(arg1, validate=False):
if validate:
do_validation(arg1)
do_work
</code></pre>
<p>Internal methods can do validation via the <a href="http://docs.python.org/reference/simple_stmts.html#assert" rel="nofollow">assert</a> statement, which can be disabled altogether when the code goes out of development and into production.</p>
| 2 | 2008-12-15T07:42:11Z | [
"python",
"validation"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def sum(nums):
"""Same as the built-in sum()... computes the sum of all the numbers passed in."""
</code></pre>
<p>How thoroughly do you check the input values before beginning computation, and how do you do your checking? Do you throw some kind of proprietary exception if input is faulty (BadInputException defined in the same module, for example)? Do you just start your calculation and figure it will throw an exception at some point if bad data was passed in ("asd" to factorial, for example)?</p>
<p>When the passed in value is supposed to be a container do you check not only the container but all the values inside it?</p>
<p>What about situations like factorial, where what's passed in might be convertible to an int (e.g. a float) but you might lose precision when doing so?</p>
| 15 | 2008-12-15T05:39:52Z | 367,910 | <p>I'm trying to write docstring stating what type of parameter is expected and accepted, and I'm not checking it explicitly in my functions. </p>
<p>If someone wants to use my function with any other type its his responsibility to check if his type emulates one I accept well enough. Maybe your factorial can be used with some custom long-like type to obtain something you wouldn't think of? Or maybe your sum can be used to concatenate strings? Why should you disallow it by type checking? It's not C, anyway.</p>
| 5 | 2008-12-15T10:03:36Z | [
"python",
"validation"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def sum(nums):
"""Same as the built-in sum()... computes the sum of all the numbers passed in."""
</code></pre>
<p>How thoroughly do you check the input values before beginning computation, and how do you do your checking? Do you throw some kind of proprietary exception if input is faulty (BadInputException defined in the same module, for example)? Do you just start your calculation and figure it will throw an exception at some point if bad data was passed in ("asd" to factorial, for example)?</p>
<p>When the passed in value is supposed to be a container do you check not only the container but all the values inside it?</p>
<p>What about situations like factorial, where what's passed in might be convertible to an int (e.g. a float) but you might lose precision when doing so?</p>
| 15 | 2008-12-15T05:39:52Z | 368,054 | <p>I <code>assert</code> what's absolutely essential.</p>
<p>Important: What's <em>absolutely</em> essential. Some people over-test things.</p>
<pre><code>def factorial(num):
assert int(num)
assert num > 0
</code></pre>
<p>Isn't completely correct. long is also a legal possibility.</p>
<pre><code>def factorial(num):
assert type(num) in ( int, long )
assert num > 0
</code></pre>
<p>Is better, but still not perfect. Many Python types (like rational numbers, or number-like objects) can also work in a good factorial function. It's hard to assert that an object has basic integer-like properties without being too specific and eliminating future unthought-of classes from consideration.</p>
<p>I never define unique exceptions for individual functions. I define a unique exception for a significant module or package. Usually, however, just an <code>Error</code> class or something similar. That way the application says <code>except somelibrary.Error,e:</code> which is about all you need to know. Fine-grained exceptions get fussy and silly.</p>
<p>I've never done this, but I can see places where it might be necessary. </p>
<pre><code>assert all( type(i) in (int,long) for i in someList )
</code></pre>
<p>Generally, however, the ordinary Python built-in type checks work fine. They find almost all of the exceptional situations that matter almost all the time. When something isn't the right type, Python raises a TypeError that always points at the right line of code.</p>
<p>BTW. I only add asserts at design time if I'm absolutely certain the function will be abused. I sometimes add assertions later when I have a unit test that fails in an obscure way.</p>
| 10 | 2008-12-15T11:18:12Z | [
"python",
"validation"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def sum(nums):
"""Same as the built-in sum()... computes the sum of all the numbers passed in."""
</code></pre>
<p>How thoroughly do you check the input values before beginning computation, and how do you do your checking? Do you throw some kind of proprietary exception if input is faulty (BadInputException defined in the same module, for example)? Do you just start your calculation and figure it will throw an exception at some point if bad data was passed in ("asd" to factorial, for example)?</p>
<p>When the passed in value is supposed to be a container do you check not only the container but all the values inside it?</p>
<p>What about situations like factorial, where what's passed in might be convertible to an int (e.g. a float) but you might lose precision when doing so?</p>
| 15 | 2008-12-15T05:39:52Z | 368,072 | <p>For calculations like sum, factorial etc, pythons built-in type checks will do fine. The calculations will end upp calling <strong>add</strong>, <strong>mul</strong> etc for the types, and if they break, they will throw the correct exception anyway. By enforcing your own checks, you may invalidate otherwise working input.</p>
| 6 | 2008-12-15T11:28:48Z | [
"python",
"validation"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def sum(nums):
"""Same as the built-in sum()... computes the sum of all the numbers passed in."""
</code></pre>
<p>How thoroughly do you check the input values before beginning computation, and how do you do your checking? Do you throw some kind of proprietary exception if input is faulty (BadInputException defined in the same module, for example)? Do you just start your calculation and figure it will throw an exception at some point if bad data was passed in ("asd" to factorial, for example)?</p>
<p>When the passed in value is supposed to be a container do you check not only the container but all the values inside it?</p>
<p>What about situations like factorial, where what's passed in might be convertible to an int (e.g. a float) but you might lose precision when doing so?</p>
| 15 | 2008-12-15T05:39:52Z | 368,705 | <p>I almost never enforce any kind of a check, unless I think there's a possibility that someone might think they can pass some X which would produce completely crazy results.</p>
<p>The other time I check is when I accept several types for an argument, for example a function that takes a list, might accept an arbitrary object and just wrap it in a list (if it's not already a list). So in that case I check for the type -not to enforce anything- just because I want the function to be flexible in how it's used.</p>
| 1 | 2008-12-15T15:29:09Z | [
"python",
"validation"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def sum(nums):
"""Same as the built-in sum()... computes the sum of all the numbers passed in."""
</code></pre>
<p>How thoroughly do you check the input values before beginning computation, and how do you do your checking? Do you throw some kind of proprietary exception if input is faulty (BadInputException defined in the same module, for example)? Do you just start your calculation and figure it will throw an exception at some point if bad data was passed in ("asd" to factorial, for example)?</p>
<p>When the passed in value is supposed to be a container do you check not only the container but all the values inside it?</p>
<p>What about situations like factorial, where what's passed in might be convertible to an int (e.g. a float) but you might lose precision when doing so?</p>
| 15 | 2008-12-15T05:39:52Z | 3,932,371 | <p>Only bother to check if you have a failing unit-test that forces you to.</p>
<p>Also consider "<a href="http://docs.python.org/glossary.html#term-eafp" rel="nofollow">EAFP</a>"... It's the Python way!</p>
| 0 | 2010-10-14T10:54:00Z | [
"python",
"validation"
] |
How much input validation should I be doing on my python functions/methods? | 367,560 | <p>I'm interested in how much up front validation people do in the Python they write.</p>
<p>Here are a few examples of simple functions:</p>
<pre><code>def factorial(num):
"""Computes the factorial of num."""
def isPalindrome(inputStr):
"""Tests to see if inputStr is the same backwards and forwards."""
def sum(nums):
"""Same as the built-in sum()... computes the sum of all the numbers passed in."""
</code></pre>
<p>How thoroughly do you check the input values before beginning computation, and how do you do your checking? Do you throw some kind of proprietary exception if input is faulty (BadInputException defined in the same module, for example)? Do you just start your calculation and figure it will throw an exception at some point if bad data was passed in ("asd" to factorial, for example)?</p>
<p>When the passed in value is supposed to be a container do you check not only the container but all the values inside it?</p>
<p>What about situations like factorial, where what's passed in might be convertible to an int (e.g. a float) but you might lose precision when doing so?</p>
| 15 | 2008-12-15T05:39:52Z | 7,608,953 | <p>A bit of perspective on how another language handles it might add some value. For Perl, I remember using this module - <a href="http://search.cpan.org/dist/Params-Validate/" rel="nofollow">http://search.cpan.org/dist/Params-Validate/</a> which offloads a lot of parameter validation from the developer. I was searching for something similar in python and came across this: <a href="http://www.voidspace.org.uk/python/validate.html" rel="nofollow">http://www.voidspace.org.uk/python/validate.html</a> I haven't tried it out. But I guess aiming for a standard way of validating params across the entire codebase leads to upfront setting of parameter validation expectations across the entire team. </p>
| 0 | 2011-09-30T10:16:01Z | [
"python",
"validation"
] |
How do I build a numpy array from a generator? | 367,565 | <p>How can I build a numpy array out of a generator object?</p>
<p>Let me illustrate the problem:</p>
<pre><code>>>> import numpy
>>> def gimme():
... for x in xrange(10):
... yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numpy.array(xrange(10))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> numpy.array(gimme())
array(<generator object at 0x28a1758>, dtype=object)
>>> numpy.array(list(gimme()))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
</code></pre>
<p>In this instance, gimme() is the generator whose output I'd like to turn into an array. However, the array constructor does not iterate over the generator, it simply stores the generator itself. The behaviour I desire is that from numpy.array(list(gimme())), but I don't want to pay the memory overhead of having the intermediate list and the final array in memory at the same time. Is there a more space-efficient way?</p>
| 81 | 2008-12-15T05:44:31Z | 367,599 | <p>Numpy arrays require their length to be set explicitly at creation time, unlike python lists. This is necessary so that space for each item can be consecutively allocated in memory. Consecutive allocation is the key feature of numpy arrays: this combined with native code implementation let operations on them execute much quicker than regular lists.</p>
<p>Keeping this in mind, it is technically impossible to take a generator object and turn it into an array unless you either:</p>
<p>(a) can predict how many elements it will yield when run:</p>
<pre><code>my_array = numpy.zeros(predict_length())
for i, el in enumerate(gimme()): my_array[i] = el
</code></pre>
<p>(b) are willing to store its elements in an intermediate list :</p>
<pre><code>my_array = numpy.array(list(gimme()))
</code></pre>
<p>(c) can make two identical generators, run through the first one to find the total length, initialize the array, and then run through the generator again to find each element:</p>
<pre><code>length = sum(1 for el in gimme())
my_array = numpy.zeros(length)
for i, el in enumerate(gimme()): my_array[i] = el
</code></pre>
<p>(a) is probably what you're looking for. (b) is space inefficient, and (c) is time inefficient (you have to go through the generator twice).</p>
| 72 | 2008-12-15T06:31:12Z | [
"python",
"numpy",
"generator"
] |
How do I build a numpy array from a generator? | 367,565 | <p>How can I build a numpy array out of a generator object?</p>
<p>Let me illustrate the problem:</p>
<pre><code>>>> import numpy
>>> def gimme():
... for x in xrange(10):
... yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numpy.array(xrange(10))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> numpy.array(gimme())
array(<generator object at 0x28a1758>, dtype=object)
>>> numpy.array(list(gimme()))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
</code></pre>
<p>In this instance, gimme() is the generator whose output I'd like to turn into an array. However, the array constructor does not iterate over the generator, it simply stores the generator itself. The behaviour I desire is that from numpy.array(list(gimme())), but I don't want to pay the memory overhead of having the intermediate list and the final array in memory at the same time. Is there a more space-efficient way?</p>
| 81 | 2008-12-15T05:44:31Z | 580,416 | <p>One google behind this stackoverflow result, I found that there is a <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html"><code>numpy.fromiter(data, dtype, count)</code></a>. The default <code>count=-1</code> takes all elements from the iterable. It requires a <code>dtype</code> to be set explicitly. In my case, this worked:</p>
<p><code>numpy.fromiter(something.generate(from_this_input), float)</code></p>
| 115 | 2009-02-24T03:53:18Z | [
"python",
"numpy",
"generator"
] |
How do I build a numpy array from a generator? | 367,565 | <p>How can I build a numpy array out of a generator object?</p>
<p>Let me illustrate the problem:</p>
<pre><code>>>> import numpy
>>> def gimme():
... for x in xrange(10):
... yield x
...
>>> gimme()
<generator object at 0x28a1758>
>>> list(gimme())
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> numpy.array(xrange(10))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> numpy.array(gimme())
array(<generator object at 0x28a1758>, dtype=object)
>>> numpy.array(list(gimme()))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
</code></pre>
<p>In this instance, gimme() is the generator whose output I'd like to turn into an array. However, the array constructor does not iterate over the generator, it simply stores the generator itself. The behaviour I desire is that from numpy.array(list(gimme())), but I don't want to pay the memory overhead of having the intermediate list and the final array in memory at the same time. Is there a more space-efficient way?</p>
| 81 | 2008-12-15T05:44:31Z | 854,732 | <p>Somewhat tangential, but if your generator is a list comprehension, you can use <code>numpy.where</code> to more effectively get your result (I discovered this in my own code after seeing this post)</p>
| 5 | 2009-05-12T20:33:33Z | [
"python",
"numpy",
"generator"
] |
Generating random text strings of a given pattern | 367,586 | <p>I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>. </p>
| 11 | 2008-12-15T06:03:40Z | 367,594 | <p>See an example - <a href="http://code.activestate.com/recipes/59873/">Recipe 59873: Random Password Generation </a>.</p>
<p>Building on the recipe, here is a solution to your question :</p>
<pre><code>from random import choice
import string
def GenPasswd2(length=8, chars=string.letters + string.digits):
return ''.join([choice(chars) for i in range(length)])
>>> GenPasswd2(8,string.digits) + GenPasswd2(15,string.ascii_letters)
'28605495YHlCJfMKpRPGyAw'
>>>
</code></pre>
| 12 | 2008-12-15T06:18:07Z | [
"python",
"string",
"random"
] |
Generating random text strings of a given pattern | 367,586 | <p>I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>. </p>
| 11 | 2008-12-15T06:03:40Z | 367,596 | <pre><code>#!/usr/bin/python
import random
import string
digits = "".join( [random.choice(string.digits) for i in xrange(8)] )
chars = "".join( [random.choice(string.letters) for i in xrange(15)] )
print digits + chars
</code></pre>
<p>EDIT: liked the idea of using random.choice better than randint() so I've updated the code to reflect that. </p>
<p>Note: this assumes lowercase and uppercase characters are desired. If lowercase only then change the second list comprehension to read:</p>
<pre><code>chars = "".join( [random.choice(string.letters[:26]) for i in xrange(15)] )
</code></pre>
<p>Obviously for uppercase only you can just flip that around so the slice is [26:] instead of the other way around.</p>
| 37 | 2008-12-15T06:19:22Z | [
"python",
"string",
"random"
] |
Generating random text strings of a given pattern | 367,586 | <p>I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>. </p>
| 11 | 2008-12-15T06:03:40Z | 14,195,441 | <p><code>random.sample</code> is an alternative choice. The difference, as can be found in the <a href="http://docs.python.org/2/library/random.html" rel="nofollow">python.org documentation</a>, is that <code>random.sample</code> samples without replacement. Thus, <code>random.sample(string.letters, 53)</code> would result in a <code>ValueError</code>. Then if you wanted to generate your random string of eight digits and fifteen characters, you would write</p>
<pre><code>import random, string
digits = ''.join(random.sample(string.digits, 8))
chars = ''.join(random.sample(string.letters, 15))
</code></pre>
| 2 | 2013-01-07T11:56:05Z | [
"python",
"string",
"random"
] |
Generating random text strings of a given pattern | 367,586 | <p>I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>. </p>
| 11 | 2008-12-15T06:03:40Z | 30,010,270 | <p>Here's a simpler version:</p>
<pre><code>import random
import string
digits = "".join( [random.choice(string.digits+string.letters) for i in xrange(10)] )
print digits
</code></pre>
| 0 | 2015-05-03T04:36:47Z | [
"python",
"string",
"random"
] |
Get Data from OpenGL glReadPixels(using Pyglet) | 367,684 | <p>I'm using Pyglet(and OpenGL) in Python on an application, I'm trying to use glReadPixels to get the RGBA values for a set of pixels. It's my understanding that OpenGL returns the data as packed integers, since that's how they are stored on the hardware. However for obvious reasons I'd like to get it into a normal format for working with. Based on some reading I've come up with this: <a href="http://dpaste.com/99206/" rel="nofollow">http://dpaste.com/99206/</a> , however it fails with an IndexError. How would I go about doing this?</p>
| 0 | 2008-12-15T07:30:59Z | 367,769 | <p>If you read the snippet you link to you can understand that the simplest and way to get the "normal" values is just accessing the array in the right order.<br />
That snippet looks like it's supposed to do the job. If it doesn't, debug it and see what's the problem.</p>
| 0 | 2008-12-15T08:30:21Z | [
"python",
"opengl",
"graphics",
"pyglet",
"glreadpixels"
] |
Get Data from OpenGL glReadPixels(using Pyglet) | 367,684 | <p>I'm using Pyglet(and OpenGL) in Python on an application, I'm trying to use glReadPixels to get the RGBA values for a set of pixels. It's my understanding that OpenGL returns the data as packed integers, since that's how they are stored on the hardware. However for obvious reasons I'd like to get it into a normal format for working with. Based on some reading I've come up with this: <a href="http://dpaste.com/99206/" rel="nofollow">http://dpaste.com/99206/</a> , however it fails with an IndexError. How would I go about doing this?</p>
| 0 | 2008-12-15T07:30:59Z | 368,224 | <p>You can use the PIL library, here is a code snippet which I use to capture such an image:</p>
<pre><code> buffer = gl.glReadPixels(0, 0, width, height, gl.GL_RGB,
gl.GL_UNSIGNED_BYTE)
image = Image.fromstring(mode="RGB", size=(width, height),
data=buffer)
image = image.transpose(Image.FLIP_TOP_BOTTOM)
</code></pre>
<p>I guess including the alpha channel should be pretty straight forward (probably just replacing RGB with RGBA, but I have not tried that).</p>
<p>Edit: I wasn't aware that the pyglet OpenGL API is different from the PyOpenGL one. I guess one has to change the above code to use the buffer as the seventh argument (conforming to the less pythonic pyglet style).</p>
| 1 | 2008-12-15T12:31:41Z | [
"python",
"opengl",
"graphics",
"pyglet",
"glreadpixels"
] |
Get Data from OpenGL glReadPixels(using Pyglet) | 367,684 | <p>I'm using Pyglet(and OpenGL) in Python on an application, I'm trying to use glReadPixels to get the RGBA values for a set of pixels. It's my understanding that OpenGL returns the data as packed integers, since that's how they are stored on the hardware. However for obvious reasons I'd like to get it into a normal format for working with. Based on some reading I've come up with this: <a href="http://dpaste.com/99206/" rel="nofollow">http://dpaste.com/99206/</a> , however it fails with an IndexError. How would I go about doing this?</p>
| 0 | 2008-12-15T07:30:59Z | 369,328 | <p>On further review I believe my original code was based on some C specific code that worked because the array is just a pointer, so my using pointer arithmetic you could get at specific bytes, that obviously doesn't translate to Python. Does anyone how to extract that data using a different method(I assume it's just a matter of bit shifting the data).</p>
| 0 | 2008-12-15T18:47:00Z | [
"python",
"opengl",
"graphics",
"pyglet",
"glreadpixels"
] |
Get Data from OpenGL glReadPixels(using Pyglet) | 367,684 | <p>I'm using Pyglet(and OpenGL) in Python on an application, I'm trying to use glReadPixels to get the RGBA values for a set of pixels. It's my understanding that OpenGL returns the data as packed integers, since that's how they are stored on the hardware. However for obvious reasons I'd like to get it into a normal format for working with. Based on some reading I've come up with this: <a href="http://dpaste.com/99206/" rel="nofollow">http://dpaste.com/99206/</a> , however it fails with an IndexError. How would I go about doing this?</p>
| 0 | 2008-12-15T07:30:59Z | 525,483 | <p>You must first create an array of the correct type, then pass it to glReadPixels:</p>
<pre><code>a = (GLuint * 1)(0)
glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_INT, a)
</code></pre>
<p>To test this, insert the following in the Pyglet "opengl.py" example:</p>
<pre><code>@window.event
def on_mouse_press(x, y, button, modifiers):
a = (GLuint * 1)(0)
glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_INT, a)
print a[0]
</code></pre>
<p>Now you should see the color code for the pixel under the mouse cursor whenever you click somewhere in the app window.</p>
| 3 | 2009-02-08T10:01:06Z | [
"python",
"opengl",
"graphics",
"pyglet",
"glreadpixels"
] |
Get Data from OpenGL glReadPixels(using Pyglet) | 367,684 | <p>I'm using Pyglet(and OpenGL) in Python on an application, I'm trying to use glReadPixels to get the RGBA values for a set of pixels. It's my understanding that OpenGL returns the data as packed integers, since that's how they are stored on the hardware. However for obvious reasons I'd like to get it into a normal format for working with. Based on some reading I've come up with this: <a href="http://dpaste.com/99206/" rel="nofollow">http://dpaste.com/99206/</a> , however it fails with an IndexError. How would I go about doing this?</p>
| 0 | 2008-12-15T07:30:59Z | 4,122,290 | <p>I was able to obtain the entire frame buffer using <code>glReadPixels(...)</code>, then used the PIL to write out to a file:</p>
<pre><code># Capture image from the OpenGL buffer
buffer = ( GLubyte * (3*window.width*window.height) )(0)
glReadPixels(0, 0, window.width, window.height, GL_RGB, GL_UNSIGNED_BYTE, buffer)
# Use PIL to convert raw RGB buffer and flip the right way up
image = Image.fromstring(mode="RGB", size=(window.width, window.height), data=buffer)
image = image.transpose(Image.FLIP_TOP_BOTTOM)
# Save image to disk
image.save('jpap.png')
</code></pre>
<p>I was not interested in alpha, but I'm sure you could easily add it in.</p>
<p>I was forced to use <code>glReadPixels(...)</code>, instead of the Pyglet code</p>
<pre><code>pyglet.image.get_buffer_manager().get_color_buffer().save('jpap.png')
</code></pre>
<p>because the output using <code>save(...)</code> was not identical to what I saw in the Window. (Multisampling buffers missed?)</p>
| 1 | 2010-11-08T08:36:50Z | [
"python",
"opengl",
"graphics",
"pyglet",
"glreadpixels"
] |
How can I reorder an mbox file chronologically? | 368,003 | <p>I have a single spool mbox file that was created with evolution, containing a selection of emails that I wish to print. My problem is that the emails are not placed into the mbox file chronologically. I would like to know the best way to place order the files from first to last using bash, perl or python. I would like to oder by received for files addressed to me, and sent for files sent by me. Would it perhaps be easier to use maildir files or such?</p>
<p>The emails currently exist in the format:</p>
<pre><code>From [email protected] Fri Aug 12 09:34:09 2005
Message-ID: <[email protected]>
Date: Fri, 12 Aug 2005 09:34:09 +0900
From: me <[email protected]>
User-Agent: Mozilla Thunderbird 1.0.6 (Windows/20050716)
X-Accept-Language: en-us, en
MIME-Version: 1.0
To: someone <[email protected]>
Subject: Re: (no subject)
References: <[email protected]>
In-Reply-To: <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 8bit
Status: RO
X-Status:
X-Keywords:
X-UID: 371
X-Evolution-Source: imap://[email protected]/
X-Evolution: 00000002-0010
Hey
the actual content of the email
someone wrote:
> lines of quotedtext
</code></pre>
<p>I am wondering if there is a way to use this information to easily reorganize the file, perhaps with perl or such.</p>
| 2 | 2008-12-15T10:51:38Z | 368,013 | <p>What's the point in rewriting the mbox whereas you can reorder the mails in memory when loading up the mailbox? Which time is the one you want to order on? Receive date? Sent date? Anyway, all the Ruby/Python/Perl modules for playing with mboxes can do that.</p>
| -2 | 2008-12-15T10:57:36Z | [
"python",
"email",
"sorting",
"mbox"
] |
How can I reorder an mbox file chronologically? | 368,003 | <p>I have a single spool mbox file that was created with evolution, containing a selection of emails that I wish to print. My problem is that the emails are not placed into the mbox file chronologically. I would like to know the best way to place order the files from first to last using bash, perl or python. I would like to oder by received for files addressed to me, and sent for files sent by me. Would it perhaps be easier to use maildir files or such?</p>
<p>The emails currently exist in the format:</p>
<pre><code>From [email protected] Fri Aug 12 09:34:09 2005
Message-ID: <[email protected]>
Date: Fri, 12 Aug 2005 09:34:09 +0900
From: me <[email protected]>
User-Agent: Mozilla Thunderbird 1.0.6 (Windows/20050716)
X-Accept-Language: en-us, en
MIME-Version: 1.0
To: someone <[email protected]>
Subject: Re: (no subject)
References: <[email protected]>
In-Reply-To: <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 8bit
Status: RO
X-Status:
X-Keywords:
X-UID: 371
X-Evolution-Source: imap://[email protected]/
X-Evolution: 00000002-0010
Hey
the actual content of the email
someone wrote:
> lines of quotedtext
</code></pre>
<p>I am wondering if there is a way to use this information to easily reorganize the file, perhaps with perl or such.</p>
| 2 | 2008-12-15T10:51:38Z | 368,067 | <p>This is how you could do it in python:</p>
<pre><code>#!/usr/bin/python2.5
from email.utils import parsedate
import mailbox
def extract_date(email):
date = email.get('Date')
return parsedate(date)
the_mailbox = mailbox.mbox('/path/to/mbox')
sorted_mails = sorted(the_mailbox, key=extract_date)
the_mailbox.update(enumerate(sorted_mails))
the_mailbox.flush()
</code></pre>
| 6 | 2008-12-15T11:27:26Z | [
"python",
"email",
"sorting",
"mbox"
] |
How can I reorder an mbox file chronologically? | 368,003 | <p>I have a single spool mbox file that was created with evolution, containing a selection of emails that I wish to print. My problem is that the emails are not placed into the mbox file chronologically. I would like to know the best way to place order the files from first to last using bash, perl or python. I would like to oder by received for files addressed to me, and sent for files sent by me. Would it perhaps be easier to use maildir files or such?</p>
<p>The emails currently exist in the format:</p>
<pre><code>From [email protected] Fri Aug 12 09:34:09 2005
Message-ID: <[email protected]>
Date: Fri, 12 Aug 2005 09:34:09 +0900
From: me <[email protected]>
User-Agent: Mozilla Thunderbird 1.0.6 (Windows/20050716)
X-Accept-Language: en-us, en
MIME-Version: 1.0
To: someone <[email protected]>
Subject: Re: (no subject)
References: <[email protected]>
In-Reply-To: <[email protected]>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 8bit
Status: RO
X-Status:
X-Keywords:
X-UID: 371
X-Evolution-Source: imap://[email protected]/
X-Evolution: 00000002-0010
Hey
the actual content of the email
someone wrote:
> lines of quotedtext
</code></pre>
<p>I am wondering if there is a way to use this information to easily reorganize the file, perhaps with perl or such.</p>
| 2 | 2008-12-15T10:51:38Z | 2,749,746 | <p>Python solution wont work if mail messages was imported into mbox using Thunderbird's ImportExportTools addon.
There are a bug: messages shall prefix with 'from' line in format:</p>
<pre><code>From - Tue Apr 27 19:42:22 2010
</code></pre>
<p>but ImportExportTools prefix with such 'from' line:</p>
<pre><code>From - Sat May 01 2010 15:07:31 GMT+0400 (Russian Daylight Time)
</code></pre>
<p>So there are two errors:</p>
<ol>
<li>sequence 'time year' broken into
'year time' </li>
<li>extra trash with GMT
info along with time zone name</li>
</ol>
<p>Since Python's mailbox.py/UnixMailbox has hardcoded regexp for 'from' line matching, some of messages can't parsed.</p>
<p>I wrote the error message to the author, but there are many mistakenly imported messages :(.</p>
| 1 | 2010-05-01T11:35:32Z | [
"python",
"email",
"sorting",
"mbox"
] |
Making a virtual package available via sys.modules | 368,057 | <p>Say I have a package "mylibrary".</p>
<p>I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace.</p>
<p>I.e., I do:</p>
<pre><code>import sys, types
sys.modules['mylibrary.config'] = types.ModuleType('config')
</code></pre>
<p>Given that setup:</p>
<pre><code>>>> import mylibrary.config # -> works
>>> from mylibrary import config
<type 'exceptions.ImportError'>: cannot import name config
</code></pre>
<p>Even stranger:</p>
<pre><code>>>> import mylibrary.config as X
<type 'exceptions.ImportError'>: cannot import name config
</code></pre>
<p>So it seems that using the direct import works, the other forms do not. Is it possible to make those work as well?</p>
| 9 | 2008-12-15T11:20:14Z | 368,178 | <p>You need to monkey-patch the module not only into sys.modules, but also into its parent module:</p>
<pre><code>>>> import sys,types,xml
>>> xml.config = sys.modules['xml.config'] = types.ModuleType('xml.config')
>>> import xml.config
>>> from xml import config
>>> from xml import config as x
>>> x
<module 'xml.config' (built-in)>
</code></pre>
| 13 | 2008-12-15T12:13:05Z | [
"python",
"import",
"module"
] |
Making a virtual package available via sys.modules | 368,057 | <p>Say I have a package "mylibrary".</p>
<p>I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace.</p>
<p>I.e., I do:</p>
<pre><code>import sys, types
sys.modules['mylibrary.config'] = types.ModuleType('config')
</code></pre>
<p>Given that setup:</p>
<pre><code>>>> import mylibrary.config # -> works
>>> from mylibrary import config
<type 'exceptions.ImportError'>: cannot import name config
</code></pre>
<p>Even stranger:</p>
<pre><code>>>> import mylibrary.config as X
<type 'exceptions.ImportError'>: cannot import name config
</code></pre>
<p>So it seems that using the direct import works, the other forms do not. Is it possible to make those work as well?</p>
| 9 | 2008-12-15T11:20:14Z | 368,247 | <p>You can try something like this:</p>
<pre><code>class VirtualModule(object):
def __init__(self, modname, subModules):
try:
import sys
self._mod = __import__(modname)
sys.modules[modname] = self
__import__(modname)
self._modname = modname
self._subModules = subModules
except ImportError, err:
pass # please signal error in some useful way :-)
def __repr__(self):
return "Virtual module for " + self._modname
def __getattr__(self, attrname):
if attrname in self._subModules.keys():
import sys
__import__(self._subModules[attrname])
return sys.modules[self._subModules[attrname]]
else:
return self._mod.__dict__[attrname]
VirtualModule('mylibrary', {'config': 'actual_module_for_config'})
import mylibrary
mylibrary.config
mylibrary.some_function
</code></pre>
| 1 | 2008-12-15T12:41:41Z | [
"python",
"import",
"module"
] |
Making a virtual package available via sys.modules | 368,057 | <p>Say I have a package "mylibrary".</p>
<p>I want to make "mylibrary.config" available for import, either as a dynamically created module, or a module imported from an entirely different place that would then basically be "mounted" inside the "mylibrary" namespace.</p>
<p>I.e., I do:</p>
<pre><code>import sys, types
sys.modules['mylibrary.config'] = types.ModuleType('config')
</code></pre>
<p>Given that setup:</p>
<pre><code>>>> import mylibrary.config # -> works
>>> from mylibrary import config
<type 'exceptions.ImportError'>: cannot import name config
</code></pre>
<p>Even stranger:</p>
<pre><code>>>> import mylibrary.config as X
<type 'exceptions.ImportError'>: cannot import name config
</code></pre>
<p>So it seems that using the direct import works, the other forms do not. Is it possible to make those work as well?</p>
| 9 | 2008-12-15T11:20:14Z | 368,910 | <p>As well as the following:</p>
<pre><code>import sys, types
config = types.ModuleType('config')
sys.modules['mylibrary.config'] = config
</code></pre>
<p>You also need to do: </p>
<pre><code>import mylibrary
mylibrary.config = config
</code></pre>
| 1 | 2008-12-15T16:28:24Z | [
"python",
"import",
"module"
] |
How can I stop a While loop? | 368,545 | <p>I wrote a <code>while loop</code> in a function, but don't know how to stop it. When it doesn't meet its final condition, the loop just go for ever. How can I stop it?</p>
<pre><code>def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
break #i want the loop to stop and return 0 if the
#period is bigger than 12
if period>12: #i wrote this line to stop it..but seems it
#doesnt work....help..
return 0
else:
return period
</code></pre>
| 3 | 2008-12-15T14:35:02Z | 368,550 | <p>just indent your code correctly:</p>
<pre><code>def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
return period
if period>12: #i wrote this line to stop it..but seems its doesnt work....help..
return 0
else:
return period
</code></pre>
<p>You need to understand that the <code>break</code> statement in your example will exit the infinite loop you've created with <code>while True</code>. So when the break condition is True, the program will quit the infinite loop and continue to the next indented block. Since there is no following block in your code, the function ends and don't return anything. So I've fixed your code by replacing the <code>break</code> statement by a <code>return</code> statement.</p>
<p>Following your idea to use an infinite loop, this is the best way to write it:</p>
<pre><code>def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
break
if period>12: #i wrote this line to stop it..but seems its doesnt work....help..
period = 0
break
return period
</code></pre>
| 8 | 2008-12-15T14:37:59Z | [
"python",
"while-loop"
] |
How can I stop a While loop? | 368,545 | <p>I wrote a <code>while loop</code> in a function, but don't know how to stop it. When it doesn't meet its final condition, the loop just go for ever. How can I stop it?</p>
<pre><code>def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
break #i want the loop to stop and return 0 if the
#period is bigger than 12
if period>12: #i wrote this line to stop it..but seems it
#doesnt work....help..
return 0
else:
return period
</code></pre>
| 3 | 2008-12-15T14:35:02Z | 368,554 | <pre><code>def determine_period(universe_array):
period=0
tmp=universe_array
while period<12:
tmp=apply_rules(tmp)#aplly_rules is a another function
if numpy.array_equal(tmp,universe_array) is True:
break
period+=1
return period
</code></pre>
| 7 | 2008-12-15T14:38:42Z | [
"python",
"while-loop"
] |
How can I stop a While loop? | 368,545 | <p>I wrote a <code>while loop</code> in a function, but don't know how to stop it. When it doesn't meet its final condition, the loop just go for ever. How can I stop it?</p>
<pre><code>def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
break #i want the loop to stop and return 0 if the
#period is bigger than 12
if period>12: #i wrote this line to stop it..but seems it
#doesnt work....help..
return 0
else:
return period
</code></pre>
| 3 | 2008-12-15T14:35:02Z | 369,204 | <p>The <code>is</code> operator in Python probably doesn't do what you expect. Instead of this:</p>
<pre><code> if numpy.array_equal(tmp,universe_array) is True:
break
</code></pre>
<p>I would write it like this:</p>
<pre><code> if numpy.array_equal(tmp,universe_array):
break
</code></pre>
<p>The <code>is</code> operator tests object identity, which is something quite different from equality.</p>
| 1 | 2008-12-15T18:03:02Z | [
"python",
"while-loop"
] |
How can I stop a While loop? | 368,545 | <p>I wrote a <code>while loop</code> in a function, but don't know how to stop it. When it doesn't meet its final condition, the loop just go for ever. How can I stop it?</p>
<pre><code>def determine_period(universe_array):
period=0
tmp=universe_array
while True:
tmp=apply_rules(tmp)#aplly_rules is a another function
period+=1
if numpy.array_equal(tmp,universe_array) is True:
break #i want the loop to stop and return 0 if the
#period is bigger than 12
if period>12: #i wrote this line to stop it..but seems it
#doesnt work....help..
return 0
else:
return period
</code></pre>
| 3 | 2008-12-15T14:35:02Z | 372,313 | <p>I would do it using a for loop as shown below :</p>
<pre><code>def determine_period(universe_array):
tmp = universe_array
for period in xrange(1, 13):
tmp = apply_rules(tmp)
if numpy.array_equal(tmp, universe_array):
return period
return 0
</code></pre>
| 0 | 2008-12-16T19:03:27Z | [
"python",
"while-loop"
] |
Questions about Setuptools and alternatives | 368,636 | <p>I've seen a good bit of setuptools bashing on the internets lately. Most recently, I read James Bennett's <a href="http://www.b-list.org/weblog/2008/dec/14/packaging/">On packaging</a> post on why no one should be using setuptools. From my time in #python on Freenode, I know that there are a few souls there who absolutely detest it. I would count myself among them, but I do actually use it.</p>
<p>I've used setuptools for enough projects to be aware of its deficiencies, and I would prefer something better. I don't particularly like the egg format and how it's deployed. With all of setuptools' problems, I haven't found a better alternative.</p>
<p>My understanding of tools like <a href="http://pip.openplans.org/">pip</a> is that it's meant to be an easy_install replacement (not setuptools). In fact, pip uses some setuptools components, right?</p>
<p>Most of my packages make use of a setuptools-aware setup.py, which declares all of the dependencies. When they're ready, I'll build an sdist, bdist, and bdist_egg, and upload them to pypi.</p>
<p>If I wanted to switch to using pip, what kind of changes would I need to make to rid myself of easy_install dependencies? Where are the dependencies declared? I'm guessing that I would need to get away from using the egg format, and provide just source distributions. If so, how do i generate the egg-info directories? or do I even need to?</p>
<p>How would this change my usage of virtualenv? Doesn't virtualenv use easy_install to manage the environments?</p>
<p>How would this change my usage of the setuptools provided "develop" command? Should I not use that? What's the alternative?</p>
<p>I'm basically trying to get a picture of what my development workflow will look like.</p>
<p>Before anyone suggests it, I'm not looking for an OS-dependent solution. I'm mainly concerned with debian linux, but deb packages are not an option, for the reasons Ian Bicking outlines <a href="http://blog.ianbicking.org/2008/12/14/a-few-corrections-to-on-packaging/">here</a>.</p>
| 20 | 2008-12-15T15:06:49Z | 369,264 | <p>For starters, pip is really new. New, incomplete and largely un-tested in the real world. </p>
<p>It shows great promise but until such time as it can do everything that easy_install/setuptools can do it's not likely to catch on in a big way, certainly not in the corporation. </p>
<p>Easy_install/setuptools is big and complex - and that offends a lot of people. Unfortunately there's a really good reason for that complexity which is that it caters for a huge number of different use-cases. My own is supporting a large ( > 300 ) pool of desktop users, plus a similar sized grid with a frequently updated application. The notion that we could do this by allowing every user to install from source is ludicrous - eggs have proved themselves a reliable way to distribute my project.</p>
<p>My advice: Learn to use setuptools - it's really a wonderful thing. Most of the people who hate it do not understand it, or simply do not have the use-case for as full-featured distribution system.</p>
<p>:-)</p>
| 2 | 2008-12-15T18:24:26Z | [
"python",
"packaging",
"setuptools",
"pip"
] |
Questions about Setuptools and alternatives | 368,636 | <p>I've seen a good bit of setuptools bashing on the internets lately. Most recently, I read James Bennett's <a href="http://www.b-list.org/weblog/2008/dec/14/packaging/">On packaging</a> post on why no one should be using setuptools. From my time in #python on Freenode, I know that there are a few souls there who absolutely detest it. I would count myself among them, but I do actually use it.</p>
<p>I've used setuptools for enough projects to be aware of its deficiencies, and I would prefer something better. I don't particularly like the egg format and how it's deployed. With all of setuptools' problems, I haven't found a better alternative.</p>
<p>My understanding of tools like <a href="http://pip.openplans.org/">pip</a> is that it's meant to be an easy_install replacement (not setuptools). In fact, pip uses some setuptools components, right?</p>
<p>Most of my packages make use of a setuptools-aware setup.py, which declares all of the dependencies. When they're ready, I'll build an sdist, bdist, and bdist_egg, and upload them to pypi.</p>
<p>If I wanted to switch to using pip, what kind of changes would I need to make to rid myself of easy_install dependencies? Where are the dependencies declared? I'm guessing that I would need to get away from using the egg format, and provide just source distributions. If so, how do i generate the egg-info directories? or do I even need to?</p>
<p>How would this change my usage of virtualenv? Doesn't virtualenv use easy_install to manage the environments?</p>
<p>How would this change my usage of the setuptools provided "develop" command? Should I not use that? What's the alternative?</p>
<p>I'm basically trying to get a picture of what my development workflow will look like.</p>
<p>Before anyone suggests it, I'm not looking for an OS-dependent solution. I'm mainly concerned with debian linux, but deb packages are not an option, for the reasons Ian Bicking outlines <a href="http://blog.ianbicking.org/2008/12/14/a-few-corrections-to-on-packaging/">here</a>.</p>
| 20 | 2008-12-15T15:06:49Z | 370,062 | <p>pip uses Setuptools, and doesn't require any changes to packages. It actually installs packages with Setuptools, using:</p>
<pre><code>python -c 'import setuptools; __file__="setup.py"; execfile(__file__)' \
install \
--single-version-externally-managed
</code></pre>
<p>Because it uses that option (<code>--single-version-externally-managed</code>) it doesn't ever install eggs as zip files, doesn't support multiple simultaneously installed versions of software, and the packages are installed flat (like <code>python setup.py install</code> works if you use only distutils). Egg metadata is still installed. pip also, like easy_install, downloads and installs all the requirements of a package. </p>
<p><em>In addition</em> you can also use a requirements file to add other packages that should be installed in a batch, and to make version requirements more exact (without putting those exact requirements in your <code>setup.py</code> files). But if you don't make requirements files then you'd use it just like easy_install.</p>
<p>For your <code>install_requires</code> I don't recommend any changes, unless you have been trying to create very exact requirements there that are known to be good. I think there's a limit to how exact you can usefully be in <code>setup.py</code> files about versions, because you can't really know what the future compatibility of new libraries will be like, and I don't recommend you try to predict this. Requirement files are an alternate place to lay out conservative version requirements.</p>
<p>You can still use <code>python setup.py develop</code>, and in fact if you do <code>pip install -e svn+http://mysite/svn/Project/trunk#egg=Project</code> it will check that out (into <code>src/project</code>) and run <code>setup.py develop</code> on it. So that workflow isn't any different really.</p>
<p>If you run pip verbosely (like <code>pip install -vv</code>) you'll see a lot of the commands that are run, and you'll probably recognize most of them.</p>
| 24 | 2008-12-15T23:29:35Z | [
"python",
"packaging",
"setuptools",
"pip"
] |
Questions about Setuptools and alternatives | 368,636 | <p>I've seen a good bit of setuptools bashing on the internets lately. Most recently, I read James Bennett's <a href="http://www.b-list.org/weblog/2008/dec/14/packaging/">On packaging</a> post on why no one should be using setuptools. From my time in #python on Freenode, I know that there are a few souls there who absolutely detest it. I would count myself among them, but I do actually use it.</p>
<p>I've used setuptools for enough projects to be aware of its deficiencies, and I would prefer something better. I don't particularly like the egg format and how it's deployed. With all of setuptools' problems, I haven't found a better alternative.</p>
<p>My understanding of tools like <a href="http://pip.openplans.org/">pip</a> is that it's meant to be an easy_install replacement (not setuptools). In fact, pip uses some setuptools components, right?</p>
<p>Most of my packages make use of a setuptools-aware setup.py, which declares all of the dependencies. When they're ready, I'll build an sdist, bdist, and bdist_egg, and upload them to pypi.</p>
<p>If I wanted to switch to using pip, what kind of changes would I need to make to rid myself of easy_install dependencies? Where are the dependencies declared? I'm guessing that I would need to get away from using the egg format, and provide just source distributions. If so, how do i generate the egg-info directories? or do I even need to?</p>
<p>How would this change my usage of virtualenv? Doesn't virtualenv use easy_install to manage the environments?</p>
<p>How would this change my usage of the setuptools provided "develop" command? Should I not use that? What's the alternative?</p>
<p>I'm basically trying to get a picture of what my development workflow will look like.</p>
<p>Before anyone suggests it, I'm not looking for an OS-dependent solution. I'm mainly concerned with debian linux, but deb packages are not an option, for the reasons Ian Bicking outlines <a href="http://blog.ianbicking.org/2008/12/14/a-few-corrections-to-on-packaging/">here</a>.</p>
| 20 | 2008-12-15T15:06:49Z | 23,160,495 | <p>I'm writing this in April 2014. Be conscious of the date on anything written about Python packaging, distribution or installation. It looks like there's been some lessening of factiousness, improvement in implementations, PEP-standardizing and unifying of fronts in the last, say, three years.</p>
<p>For instance, the <a href="http://packaging.python.org/en/latest/glossary.html#term-python-packaging-authority-pypa" rel="nofollow">Python Packaging Authority</a> is "a working group that maintains many of the relevant projects in Python packaging." </p>
<p>The <code>python.org</code> <a href="http://packaging.python.org/en/latest/" rel="nofollow">Python Packaging User Guide</a> has <a href="http://packaging.python.org/en/latest/current.html" rel="nofollow">Tool Recommendations</a> and <a href="http://packaging.python.org/en/latest/future.html" rel="nofollow">The Future of Python Packaging</a> sections.</p>
<p><code>distribute</code> was a branch of <code>setuptools</code> that was remerged in June 2013. The guide says, "Use <code>setuptools</code> to define projects and create Source Distributions."</p>
<p>As of PEP 453 and Python 3.4, the guide recommends, "Use <code>pip</code> to install Python packages from PyPI," and <code>pip</code> is included with Python 3.4 and installed in virtualenvs by <code>pyvenv</code>, which is also included. You might find the <a href="http://legacy.python.org/dev/peps/pep-0453/#rationale" rel="nofollow">PEP 453 "rationale" section</a> interesting.</p>
<p>There are also new and newish tools mentioned in the guide, including <a href="http://packaging.python.org/en/latest/glossary.html#term-wheel" rel="nofollow"><code>wheel</code></a> and <a href="http://packaging.python.org/en/latest/projects.html#buildout" rel="nofollow"><code>buildout</code></a>.</p>
<p>I'm glad I read both of the following technical/semi-political histories.</p>
<p>By Martijn Faassen in 2009: <a href="http://blog.startifact.com/posts/older/a-history-of-python-packaging.html" rel="nofollow">A History of Python Packaging</a>.</p>
<p>And by Armin Ronacher in June 2013 (the title is not serious): <a href="https://lucumr.pocoo.org/2012/6/22/hate-hate-hate-everywhere/" rel="nofollow">Python Packaging: Hate, hate, hate everywhere</a>.</p>
| 2 | 2014-04-18T19:00:46Z | [
"python",
"packaging",
"setuptools",
"pip"
] |
Python UnicodeDecodeError - Am I misunderstanding encode? | 368,805 | <p>Any thoughts on why this isn't working? I really thought 'ignore' would do the right thing.</p>
<pre><code>>>> 'add \x93Monitoring\x93 to list '.encode('latin-1','ignore')
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 4: ordinal not in range(128)
</code></pre>
| 49 | 2008-12-15T15:57:24Z | 368,828 | <p>encode is available to unicode strings, but the string you have there does not seems unicode (try with u'add \x93Monitoring\x93 to list ')</p>
<pre><code>>>> u'add \x93Monitoring\x93 to list '.encode('latin-1','ignore')
'add \x93Monitoring\x93 to list '
</code></pre>
| 2 | 2008-12-15T16:02:02Z | [
"python",
"unicode",
"ascii",
"encode",
"ignore"
] |
Python UnicodeDecodeError - Am I misunderstanding encode? | 368,805 | <p>Any thoughts on why this isn't working? I really thought 'ignore' would do the right thing.</p>
<pre><code>>>> 'add \x93Monitoring\x93 to list '.encode('latin-1','ignore')
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 4: ordinal not in range(128)
</code></pre>
| 49 | 2008-12-15T15:57:24Z | 368,859 | <p>This seems to work:</p>
<pre><code>'add \x93Monitoring\x93 to list '.decode('latin-1').encode('latin-1')
</code></pre>
<p>Any issues with that? I wonder when 'ignore', 'replace' and other such encode error handling comes in?</p>
| -3 | 2008-12-15T16:10:11Z | [
"python",
"unicode",
"ascii",
"encode",
"ignore"
] |
Python UnicodeDecodeError - Am I misunderstanding encode? | 368,805 | <p>Any thoughts on why this isn't working? I really thought 'ignore' would do the right thing.</p>
<pre><code>>>> 'add \x93Monitoring\x93 to list '.encode('latin-1','ignore')
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 4: ordinal not in range(128)
</code></pre>
| 49 | 2008-12-15T15:57:24Z | 370,199 | <p>â¦there's a reason they're called "encodings"â¦</p>
<p>A little preamble: think of unicode as the norm, or the ideal state. Unicode is just a table of characters. â65 is latin capital A. â937 is greek capital omega. Just that.</p>
<p>In order for a computer to store and-or manipulate Unicode, it has to <em>encode</em> it into bytes. The most straightforward <em>encoding</em> of Unicode is UCS-4; every character occupies 4 bytes, and all ~1000000 characters are available. The 4 bytes contain the number of the character in the Unicode tables as a 4-byte integer. Another very useful encoding is UTF-8, which can encode any Unicode character with one to four bytes. But there also are some limited encodings, like "latin1", which include a very limited range of characters, mostly used by Western countries. Such <em>encodings</em> use only one byte per character.</p>
<p>Basically, Unicode can be <em>encoded</em> with many encodings, and encoded strings can be <em>decoded</em> to Unicode. The thing is, Unicode came quite late, so all of us that grew up using an 8-bit <em>character set</em> learned too late that all this time we worked with <em>encoded</em> strings. The encoding could be ISO8859-1, or windows CP437, or CP850, or, or, or, depending on our system default.</p>
<p>So when, in your source code, you enter the string "add âMonitoringâ to list" (and I think you wanted the string "add âMonitoringâ to list", note the second quote), you actually are using a string already <em>encoded</em> according to your system's default codepage (by the byte \x93 I assume you use Windows codepage 1252, âWesternâ). If you want to get Unicode from that, you need to <em>decode</em> the string from the "cp1252" encoding.</p>
<p>So, what you meant to do, was:</p>
<pre><code>"add \x93Monitoring\x94 to list".decode("cp1252", "ignore")
</code></pre>
<p>It's unfortunate that Python 2.x includes an <code>.encode</code> method for strings too; this is a convenience function for "special" encodings, like the "zip" or "rot13" or "base64" ones, which have nothing to do with Unicode.</p>
<p>Anyway, all you have to remember for your to-and-fro Unicode conversions is:</p>
<ul>
<li>a Unicode string gets <em>encoded</em> to a Python 2.x string (actually, a sequence of bytes)</li>
<li>a Python 2.x string gets <em>decoded</em> to a Unicode string</li>
</ul>
<p>In both cases, you need to specify the <em>encoding</em> that will be used.</p>
<p>I'm not very clear, I'm sleepy, but I sure hope I help.</p>
<p>PS A humorous side note: Mayans didn't have Unicode; ancient Romans, ancient Greeks, ancient Egyptians didn't too. They all had their own "encodings", and had little to no respect for other cultures. All these civilizations crumbled to dust. Think about it people! Make your apps Unicode-aware, for the good of mankind. :)</p>
<p>PS2 Please don't spoil the previous message by saying "But the Chineseâ¦". If you feel inclined or obligated to do so, though, delay it by thinking that the Unicode BMP is populated mostly by chinese ideograms, ergo Chinese is the basis of Unicode. I can go on inventing outrageous lies, as long as people develop Unicode-aware applications. Cheers!</p>
| 190 | 2008-12-16T00:45:11Z | [
"python",
"unicode",
"ascii",
"encode",
"ignore"
] |
Python UnicodeDecodeError - Am I misunderstanding encode? | 368,805 | <p>Any thoughts on why this isn't working? I really thought 'ignore' would do the right thing.</p>
<pre><code>>>> 'add \x93Monitoring\x93 to list '.encode('latin-1','ignore')
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 4: ordinal not in range(128)
</code></pre>
| 49 | 2008-12-15T15:57:24Z | 425,517 | <p>I also wrote a long blog about this subject: </p>
<p><a href="http://writeonly.wordpress.com/2008/12/10/the-hassle-of-unicode-and-getting-on-with-it-in-python/" rel="nofollow">The Hassle of Unicode and Getting on With It</a></p>
| 0 | 2009-01-08T19:20:32Z | [
"python",
"unicode",
"ascii",
"encode",
"ignore"
] |
Passing a Python array to a C++ vector using Swig | 368,980 | <p>I have an array of objects in Python </p>
<pre><code>[obj1, obj2, obj3]
</code></pre>
<p>and I want to pass them to off to a C++ function to perform some computation. I'm using SWIG to write my interface. The class type of the passed object is already defined in C++. </p>
<p>What's the best way to do this?</p>
| 3 | 2008-12-15T16:45:43Z | 369,891 | <p>It depends on if your function is already written and cannot be changed, in which case you may need to check Swig docs to see if there is already a typemap from PyList to std::vector (I think there is). If not, taking PyObject* as the argument to the function and using the Python C API for manipulating lists should work fine. I haven't had any problems with it so far. For self-documentation, I recommend typedef'ing PyObject* to some kind of expected type, like "PythonList" so that the parameters have some meaning.</p>
<p>This may also be useful:</p>
<p><a href="http://stackoverflow.com/questions/276769/how-to-expose-stdvectorint-as-a-python-list-using-swig">http://stackoverflow.com/questions/276769/how-to-expose-stdvectorint-as-a-python-list-using-swig</a></p>
| 2 | 2008-12-15T22:17:57Z | [
"c++",
"python",
"swig"
] |
What is the best way to serialize a ModelForm object in Django? | 369,230 | <p>I am using Django and the Google Web Toolkit (GWT) for my current project. I would like to pass a ModelForm instance to GWT via an Http response so that I can "chop" it up and render it as I please. My goal is to keep the form in sync with changes to my models.py file, yet increase control I have over the look of the form. However, the django classes for serialization, serializers and simplejson, cannot serialize a ModelForm. Neither can cPickle. What are my alternatives? </p>
| 1 | 2008-12-15T18:12:22Z | 372,371 | <p>If your problem is just to serialze a ModelForm to json, just write your own simplejson serializer subclass.</p>
| 0 | 2008-12-16T19:24:10Z | [
"python",
"xml",
"django",
"json",
"serialization"
] |
What is the best way to serialize a ModelForm object in Django? | 369,230 | <p>I am using Django and the Google Web Toolkit (GWT) for my current project. I would like to pass a ModelForm instance to GWT via an Http response so that I can "chop" it up and render it as I please. My goal is to keep the form in sync with changes to my models.py file, yet increase control I have over the look of the form. However, the django classes for serialization, serializers and simplejson, cannot serialize a ModelForm. Neither can cPickle. What are my alternatives? </p>
| 1 | 2008-12-15T18:12:22Z | 372,985 | <p>If you were using pure Django, you'd pass the form to your template, and could then call individual fields on the form for more precise rendering, rather than using ModelForm.to_table. You can use the following to iterate over each field and render it exactly how you want:</p>
<pre><code>{% for field in form.fields %}
<div class="form-field">{{ field }}</div>
{% endfor %}
</code></pre>
<p>This also affords you the ability to do conditional checks using {% if %} blocks inside the loop should you want to exclude certain fields.</p>
| 1 | 2008-12-16T22:21:23Z | [
"python",
"xml",
"django",
"json",
"serialization"
] |
using existing rrule to generate a further set of occurrences | 369,261 | <p>I have an rrule instance e.g.</p>
<pre><code> r = rrule(WEEKLY, byweekday=SA, count=10, dtstart=parse('20081001'))
</code></pre>
<p>where dtstart and byweekday may change.</p>
<p>If I then want to generate the ten dates that follow on from this
rrule, what's the best way of doing it? Can I assign a new value to
the _dtstart member of r? That seems to work but I'm not sure.</p>
<p>e.g. </p>
<pre><code> r._dtstart = list(r)[-1] or something like that
</code></pre>
<p>Otherwise I guess I'll create a new rrule and access _dtstart, _count, _byweekday etc. of the original instance.</p>
<p>EDIT:</p>
<p>I've thought about it more, and I think what I should be doing is omitting the 'count' argument when I create the first rrule instance. I can still get ten occurrences the first time I use the rrule</p>
<pre><code>instances = list(r[0:10])
</code></pre>
<p>and then afterwards I can get more </p>
<pre><code>more = list(r[10:20])
</code></pre>
<p>I think that solves my problem without any ugliness</p>
| 2 | 2008-12-15T18:23:35Z | 370,418 | <p>Firstly, <code>r._dtstart = list(r)[-1]</code> will give you the last date in the original sequence of dates. If you use that, without modification, for the beginning of a new sequence, you will end up with a duplicate date, i.e. the last date of the first sequence will be the same as the first date of the new sequence, which is probably not what you want:</p>
<pre><code>>>> from dateutil.rrule import *
>>> import datetime
>>> r = rrule(WEEKLY, byweekday=SA, count=10, dtstart=datetime.datetime(2008,10,01))
>>> print list(r)
[datetime.datetime(2008, 10, 4, 0, 0), datetime.datetime(2008, 10, 11, 0, 0), datetime.datetime(2008, 10, 18, 0, 0), datetime.datetime(2008, 10, 25, 0, 0), datetime.datetime(2008, 11, 1, 0, 0), datetime.datetime(2008, 11, 8, 0, 0), datetime.datetime(2008, 11, 15, 0, 0), datetime.datetime(2008, 11, 22, 0, 0), datetime.datetime(2008, 11, 29, 0, 0), datetime.datetime(2008, 12, 6, 0, 0)]
>>> r._dtstart = r[-1]
>>> print list(r)
[datetime.datetime(2008, 12, 6, 0, 0), datetime.datetime(2008, 12, 13, 0, 0), datetime.datetime(2008, 12, 20, 0, 0), datetime.datetime(2008, 12, 27, 0, 0), datetime.datetime(2009, 1, 3, 0, 0), datetime.datetime(2009, 1, 10, 0, 0), datetime.datetime(2009, 1, 17, 0, 0), datetime.datetime(2009, 1, 24, 0, 0), datetime.datetime(2009, 1, 31, 0, 0), datetime.datetime(2009, 2, 7, 0, 0)]
</code></pre>
<p>Furthermore, it is considered poor form to manipulate r._dtstart as it is clearly intended to be a private attribute.</p>
<p>Instead, do something like this:</p>
<pre><code>>>> r = rrule(WEEKLY, byweekday=SA, count=10, dtstart=datetime.datetime(2008,10,01))
>>> r2 = rrule(WEEKLY, byweekday=SA, count=r.count(), dtstart=r[-1] + datetime.timedelta(days=1))
>>> print list(r)
[datetime.datetime(2008, 10, 4, 0, 0), datetime.datetime(2008, 10, 11, 0, 0), datetime.datetime(2008, 10, 18, 0, 0), datetime.datetime(2008, 10, 25, 0, 0), datetime.datetime(2008, 11, 1, 0, 0), datetime.datetime(2008, 11, 8, 0, 0), datetime.datetime(2008, 11, 15, 0, 0), datetime.datetime(2008, 11, 22, 0, 0), datetime.datetime(2008, 11, 29, 0, 0), datetime.datetime(2008, 12, 6, 0, 0)]
>>> print list(r2)
[datetime.datetime(2008, 12, 13, 0, 0), datetime.datetime(2008, 12, 20, 0, 0), datetime.datetime(2008, 12, 27, 0, 0), datetime.datetime(2009, 1, 3, 0, 0), datetime.datetime(2009, 1, 10, 0, 0), datetime.datetime(2009, 1, 17, 0, 0), datetime.datetime(2009, 1, 24, 0, 0), datetime.datetime(2009, 1, 31, 0, 0), datetime.datetime(2009, 2, 7, 0, 0), datetime.datetime(2009, 2, 14, 0, 0)]
</code></pre>
<p>This codes does not access any private attributes of rrule (although you might have to look at <code>_byweekday</code>).</p>
| 1 | 2008-12-16T03:57:33Z | [
"python",
"python-dateutil"
] |
Is there anyone who has managed to compile mod_wsgi for apache on Mac OS X Leopard? | 369,305 | <p>I'm working on a Django project that requires debugging on a multithreaded server. I've found mod_wsgi 2.0+ to be the easiest to work with, because of easy workarounds for python module reloading. Problem is can't get it to compile on Leopard. Is there anyone who has managed to do it so far, either for the builtin Apache or MAMP. I'd be grateful if someone posts a link to a precompiled binary (for intel, python 2.5, apache 2.2 or 2.0).</p>
<p><hr /></p>
<p>After 3 hours of trial and error I've managed to compile mod_wsgi 2.3 for the Apache that comes with Leopard. Here are the instructions in case anyone else needs this.</p>
<ol>
<li>./configure</li>
<li><p>Change 2 lines in the Makefile</p>
<p>CFLAGS = -Wc,'-arch i386'</p>
<p>LDFLAGS = -arch i386 -Wl,-F/Library/Frameworks -framework Python -u _PyMac_Error</p></li>
<li><p>make && sudo make install</p></li>
<li><p>Make a thin binary of the original httpd</p>
<p>cd /usr/sbin </p>
<p>sudo mv ./httpd ./httpd.fat </p>
<p>sudo lipo ./httpd.fat -thin i386 -output ./httpd.i386 </p>
<p>sudo ln -s ./httpd.i386 ./httpd</p></li>
</ol>
<p>This should work on intel macbook, macbook pro, imac and mac mini. As I understood the problem is modwsgi won't compile against MacPython 2.5.2 because of some weird architecture missmatch problem. But, if you compile it as a thin binary it won't play with the Apache fat binary. So this hack solves the problem. The rest is pretty standard configuration, like on any other platform.</p>
| 4 | 2008-12-15T18:39:13Z | 392,945 | <p>This doesn't directly answer your question, but have you thought about using something like MacPorts for this sort of thing? If you're compiling a lot of software like this, MacPorts can really make your life easier, since building software and dependencies is practically automatic.</p>
| 2 | 2008-12-25T16:34:18Z | [
"python",
"django",
"apache"
] |
Is there an OpenSource BASIC interpreter in Ruby/Python? | 369,391 | <p>I want something simple in order to experiment/hack. I've created a lot interpreters/compilers for c and I just want something simple. A basic BASIC :D</p>
<p>If you don't know any (I've done my google search...), yacc/bison is the only way?</p>
<p>Thx</p>
| 1 | 2008-12-15T19:12:11Z | 369,443 | <p>None of these listed in <a href="http://www.thefreecountry.com/compilers/basic.shtml" rel="nofollow">TheFreeCountry</a> are acceptable? None of them are in Python, but I should think that starting from <a href="http://www.xblite.com/" rel="nofollow">XBLite</a> might be more helpful than starting from Yacc/Bison/<a href="http://www.dabeaz.com/ply/" rel="nofollow">PLY</a>.</p>
<p>Also, <a href="http://vb2py.sourceforge.net/" rel="nofollow">Vb2py</a> might be a better starting position than PLY.</p>
<p>If you must go the PLY route, however, consider the <a href="http://www.xs4all.nl/~merty/mole/" rel="nofollow">MOLE Basic</a> grammar as a starting point rather than trying to roll your own from scratch.</p>
| 3 | 2008-12-15T19:28:45Z | [
"python",
"ruby",
"interpreter"
] |
Is there an OpenSource BASIC interpreter in Ruby/Python? | 369,391 | <p>I want something simple in order to experiment/hack. I've created a lot interpreters/compilers for c and I just want something simple. A basic BASIC :D</p>
<p>If you don't know any (I've done my google search...), yacc/bison is the only way?</p>
<p>Thx</p>
| 1 | 2008-12-15T19:12:11Z | 369,809 | <p>I also don't know a basic interpreter under ruby, but given enough time and interest ruby easily "supports" writing an interpreter for any language you like: <a href="http://obiefernandez.com/presentations/obie_fernandez-agile_dsl_development_in_ruby.pdf" rel="nofollow">Agile DSL Development
in Ruby</a> . I must admit that this approach comes with some investment of time. :(
At the end of the presentation are some links to further readings regarding DSLs. </p>
| 1 | 2008-12-15T21:44:43Z | [
"python",
"ruby",
"interpreter"
] |
Is there an OpenSource BASIC interpreter in Ruby/Python? | 369,391 | <p>I want something simple in order to experiment/hack. I've created a lot interpreters/compilers for c and I just want something simple. A basic BASIC :D</p>
<p>If you don't know any (I've done my google search...), yacc/bison is the only way?</p>
<p>Thx</p>
| 1 | 2008-12-15T19:12:11Z | 370,209 | <p>You may wish to also examine <a href="http://en.wikipedia.org/wiki/Parrot_virtual_machine" rel="nofollow">the Parrot virtual machine</a> which, according to wikipedia today, has some BASIC support.</p>
| 1 | 2008-12-16T00:51:10Z | [
"python",
"ruby",
"interpreter"
] |
Is there an OpenSource BASIC interpreter in Ruby/Python? | 369,391 | <p>I want something simple in order to experiment/hack. I've created a lot interpreters/compilers for c and I just want something simple. A basic BASIC :D</p>
<p>If you don't know any (I've done my google search...), yacc/bison is the only way?</p>
<p>Thx</p>
| 1 | 2008-12-15T19:12:11Z | 372,133 | <p><a href="http://www.dabeaz.com/ply/" rel="nofollow">PLY</a> is a great parser-creation library for Python. It has a simple BASIC interpreter as one of its example scripts. You could start there.</p>
| 4 | 2008-12-16T18:02:36Z | [
"python",
"ruby",
"interpreter"
] |
Is there an OpenSource BASIC interpreter in Ruby/Python? | 369,391 | <p>I want something simple in order to experiment/hack. I've created a lot interpreters/compilers for c and I just want something simple. A basic BASIC :D</p>
<p>If you don't know any (I've done my google search...), yacc/bison is the only way?</p>
<p>Thx</p>
| 1 | 2008-12-15T19:12:11Z | 372,216 | <p>a miniBasic in ruby is available <a href="http://rockit.sourceforge.net/" rel="nofollow">here</a>. Rockit seems WAY more fun that racc.</p>
| 0 | 2008-12-16T18:31:49Z | [
"python",
"ruby",
"interpreter"
] |
Is there an OpenSource BASIC interpreter in Ruby/Python? | 369,391 | <p>I want something simple in order to experiment/hack. I've created a lot interpreters/compilers for c and I just want something simple. A basic BASIC :D</p>
<p>If you don't know any (I've done my google search...), yacc/bison is the only way?</p>
<p>Thx</p>
| 1 | 2008-12-15T19:12:11Z | 12,280,987 | <p>There is pybasic (python basic), rockit-minibasic (rubybasic).</p>
<p>To make these able to use the gui, then one has to develop extensions with kivy and shoes gui toolkits for pybasic and rockit-minibasic respectively and similarly prima gui for perlbasic if ever exists.</p>
| -1 | 2012-09-05T12:02:03Z | [
"python",
"ruby",
"interpreter"
] |
Python: os.environ.get('SSH_ORIGINAL_COMMAND') returns None | 369,414 | <p>Trying to follow a technique found at <code>bzr</code> and <code>gitosis</code> I did the following:</p>
<p>added to <code>~/.ssh/authorized_keys</code> the <code>command="my_parser"</code> parameter
which point to a python script file named 'my_parser' and located in
<code>/usr/local/bin</code> (file was chmoded as 777)</p>
<p>in that script file <code>'/usr/local/bin/my_parser'</code> I got the following
lines:</p>
<pre><code>#!/usr/bin/env python
import os
print os.environ.get('SSH_ORIGINAL_COMMAND', None)
</code></pre>
<p>When trying to ssh e.g. <code>ssh localhost</code>
I get <code>None</code> on the terminal and then the connection is closed.</p>
<p>I wonder if anyone have done such or alike in the past and can help me
with this.</p>
<p>Is there anything I should do in my python file in order to get that
environment variable? </p>
| 2 | 2008-12-15T19:19:50Z | 369,576 | <p><code>$SSH_ORIGINAL_COMMAND</code> is set when you connect to a host with ssh to execute a single command:</p>
<pre><code>$ ssh username@host 'some command'
</code></pre>
<p>Your "my_parser" would then return "some command".</p>
<p>Unless you invoke a shell with my_parser, it will then exit, and the connection will close. You can use this to control the environment of the remotely executed commands, but you lose the ability to have an interactive session </p>
| 1 | 2008-12-15T20:19:40Z | [
"python",
"ssh"
] |
How to discover the type of the NAT a given interface is behind | 369,664 | <p>I would like to discover the type of the NAT (FullCone, Restricted Cone, Port Restricted cone, Symmetric) a given network interface is behind. </p>
<p>I've tested different tools (<a href="http://freshmeat.net/projects/jstun/" rel="nofollow">http://freshmeat.net/projects/jstun/</a>, <a href="http://code.google.com/p/boogu/" rel="nofollow">http://code.google.com/p/boogu/</a>) but they report different results for the same interface. </p>
<p>I'm looking for a definitive answer in Python (or other languages, 2nd choice being Java, if nothing else is available).</p>
| 4 | 2008-12-15T20:53:50Z | 369,763 | <p><a href="http://en.wikipedia.org/wiki/STUN" rel="nofollow">http://en.wikipedia.org/wiki/STUN</a></p>
<blockquote>
<p>NAT devices are implemented in a
number of different types of address
and port mapping schemes. STUN does
not work correctly with all of them.</p>
</blockquote>
<p>Is that definitive enough? It's only a wikipedia quote, but from this it looks like your request is physically impossible.</p>
| 3 | 2008-12-15T21:25:30Z | [
"java",
"python",
"nat",
"discovery"
] |
How to discover the type of the NAT a given interface is behind | 369,664 | <p>I would like to discover the type of the NAT (FullCone, Restricted Cone, Port Restricted cone, Symmetric) a given network interface is behind. </p>
<p>I've tested different tools (<a href="http://freshmeat.net/projects/jstun/" rel="nofollow">http://freshmeat.net/projects/jstun/</a>, <a href="http://code.google.com/p/boogu/" rel="nofollow">http://code.google.com/p/boogu/</a>) but they report different results for the same interface. </p>
<p>I'm looking for a definitive answer in Python (or other languages, 2nd choice being Java, if nothing else is available).</p>
| 4 | 2008-12-15T20:53:50Z | 9,662,635 | <p>As @S.Lott 's say, STUN is your first choice protocol .</p>
<p>And then, STUN is just a protocol.Here is my advice:</p>
<p>1 <strong>STUN</strong> now has two version : the old version is <a href="http://www.ietf.org/rfc/rfc3489.txt" rel="nofollow">RFC3489</a> - this is a lightweight protocol that allows applications to discover the presence and types of NATs and firewalls between them and the public Internet (so it's mainly and only for detecting NAT type ); and the new version is <a href="http://www.ietf.org/rfc/rfc5389.txt" rel="nofollow">RFC5389</a> - this is a tool for other protocols in dealing with NAT traversal . </p>
<p>2 Also there is a relay extension to STUN named <strong>TURN</strong> <a href="http://www.ietf.org/rfc/rfc5766.txt" rel="nofollow">RFC5766</a>. TURN allows the host to control the operation of the relay and to exchange packets with its peers using the relay. TURN differs from some other relay control protocols in that it allows a client to communicate with multiple peers using a single relay address.</p>
<p>The tools:</p>
<ul>
<li>STUN server (RFC3489) : <a href="http://sourceforge.net/projects/stun" rel="nofollow">stund</a> By c++ </li>
<li><p>STUN client (RFC3489) : <a href="http://code.google.com/p/pystun/" rel="nofollow">pystun</a> By python</p></li>
<li><p>TURN server (RFC5766) : <a href="http://turnserver.sourceforge.net" rel="nofollow">turnserver</a> By c</p></li>
<li>TURN client (RFC5766) : <a href="https://github.com/node/turn-client" rel="nofollow">turn-client</a> By c and python </li>
</ul>
<p>Note:
Because TURN is the extension of new version STUN, the TURN server also support new STUN request by RFC5389 .</p>
| 0 | 2012-03-12T06:30:48Z | [
"java",
"python",
"nat",
"discovery"
] |
How to discover the type of the NAT a given interface is behind | 369,664 | <p>I would like to discover the type of the NAT (FullCone, Restricted Cone, Port Restricted cone, Symmetric) a given network interface is behind. </p>
<p>I've tested different tools (<a href="http://freshmeat.net/projects/jstun/" rel="nofollow">http://freshmeat.net/projects/jstun/</a>, <a href="http://code.google.com/p/boogu/" rel="nofollow">http://code.google.com/p/boogu/</a>) but they report different results for the same interface. </p>
<p>I'm looking for a definitive answer in Python (or other languages, 2nd choice being Java, if nothing else is available).</p>
| 4 | 2008-12-15T20:53:50Z | 18,139,611 | <p>I second the answer from @S.Lott: It is not possible to use STUN (or any other protocol) to determine with 100% certainty what type of NAT you're behind.</p>
<p>The problem is (as I witnessed recently) that the NAT may sometimes act as <a href="http://tools.ietf.org/html/rfc4787#section-4.1" rel="nofollow">Address-Dependent</a> (Symmetric) and sometimes as <a href="http://tools.ietf.org/html/rfc4787#section-4.1" rel="nofollow">Endpoint-Independent</a> (Full, Restricted or Port Restricted cone).</p>
<p>When you think about it, being Address-Dependent means that when you send packets from one socket on a client behind the NAT to two distinct servers, then the NAT will create two custom public address:port tuples for each of the servers. In my case, these bindings seemed completely random, but if the range is small, it sometimes happened that these tuples were actually equal! Which confused the test.</p>
<p>I was using <a href="http://www.stunprotocol.org/" rel="nofollow">this library</a> at the time and sometimes it told me the NAT's behavior was Address-Dependent and other times it was Endpoint-Independent (the switch between the two also seemed completely random, sometimes it happened after I restarted the device, sometimes after a time period,...).</p>
<p>This happened to me on a mobile device with <a href="http://en.wikipedia.org/wiki/Slovak_Telekom" rel="nofollow">Slovak Telekom</a>, a company mostly owned by <a href="http://en.wikipedia.org/wiki/Deutsche_Telekom" rel="nofollow">Deutsche Telekom</a> so I think the problem will be at least Europe-wide.</p>
<p>I would say that the rule here is this: If STUN test tells you that you're behind a Symmetric NAT than that is the case, but if it tells you otherwise, then you can not be 100% sure.</p>
<p>One last note, an easy way to check your NAT's behavior with respect to TCP is to type "what is my IP address" into google and then open first (say) five pages. If the pages are <strong>not</strong> consistent about your IP address, your NAT's behavior is Address-Dependent or Address-and-Port-Dependent (Symmetric). But again, if they do correspond, you just can't be sure.</p>
| 3 | 2013-08-09T03:23:17Z | [
"java",
"python",
"nat",
"discovery"
] |
IPv6 decoder for pcapy/impacket | 369,764 | <p>I use the <a href="http://oss.coresecurity.com/projects/pcapy.html" rel="nofollow">pcapy</a>/<a href="http://oss.coresecurity.com/projects/impacket.html" rel="nofollow">impacket</a> library to decode network packets in Python. It has an IP decoder which knows about the syntax of IPv4 packets but apparently no IPv6 decoder.</p>
<p>Does anyone get one? </p>
<p>In a private correspondance, the Impacket maintainers say it may be better to start with <a href="http://www.secdev.org/projects/scapy/" rel="nofollow">Scapy</a></p>
| 2 | 2008-12-15T21:25:32Z | 384,375 | <p>I have never used pcapy before, but I do have used libpcap in C projects. As the pcapy page states it is not statically linked to libcap, so you can upgrade to a newer one with IPv6 support.</p>
<p>According to <a href="http://www.tcpdump.org/libpcap-changes.txt" rel="nofollow">libpcap changelog</a>, version 1.0 released on October 27, 2008, has default IPv6 support (it is supposed to have IPv6 from much longer but it is now default compiled with that option), so you should be able to capture IPv6 traffic with this version. Latest pcapy release is from March 27, 2007, so at most it should include a 0.9.8 version of libcap released on September 10, 2007.</p>
<p>I don't know if that would be enough for you to be able to capture IPv6 traffic since pcapy API would probably requiere some changes to support it, and that's on pcapy developer's roof.</p>
<p><strong>Update</strong>: Apparently <a href="http://sourceforge.net/projects/pylibpcap" rel="nofollow">pylibpcap</a>, a python wrapper to libpcap, has newer releases than pcapy, so newer libpcap features should be better supported.</p>
<p>More information about PCAP (libpcap) in general <a href="http://en.wikipedia.org/wiki/Pcap" rel="nofollow">here</a>.</p>
| -1 | 2008-12-21T12:05:34Z | [
"python",
"ipv6",
"packet-capture",
"pcap"
] |
IPv6 decoder for pcapy/impacket | 369,764 | <p>I use the <a href="http://oss.coresecurity.com/projects/pcapy.html" rel="nofollow">pcapy</a>/<a href="http://oss.coresecurity.com/projects/impacket.html" rel="nofollow">impacket</a> library to decode network packets in Python. It has an IP decoder which knows about the syntax of IPv4 packets but apparently no IPv6 decoder.</p>
<p>Does anyone get one? </p>
<p>In a private correspondance, the Impacket maintainers say it may be better to start with <a href="http://www.secdev.org/projects/scapy/" rel="nofollow">Scapy</a></p>
| 2 | 2008-12-15T21:25:32Z | 386,496 | <p>Scapy, recommended by the Impacket maintainers, has no IPv6 decoding at this time. But there is an <a href="http://namabiiru.hongo.wide.ad.jp/scapy6/" rel="nofollow">unofficial extension</a> to do so.</p>
<p>With this extension, it works:</p>
<pre><code>for packet in traffic:
if packet.type == ETH_P_IPV6 or packet.type == ETH_P_IP:
ip = packet.payload
if (ip.version == 4 and ip.proto == UDP_PROTO) or \
(ip.version == 6 and ip.nh == UDP_PROTO):
if ip.dport == DNS_PORT and ip.dst == ns:
all_queries = all_queries + 1
</code></pre>
<p>but it is awfully slow for large traces. So, I may have to try Impacket nevertheless or even go back to C.</p>
| 1 | 2008-12-22T15:21:28Z | [
"python",
"ipv6",
"packet-capture",
"pcap"
] |
IPv6 decoder for pcapy/impacket | 369,764 | <p>I use the <a href="http://oss.coresecurity.com/projects/pcapy.html" rel="nofollow">pcapy</a>/<a href="http://oss.coresecurity.com/projects/impacket.html" rel="nofollow">impacket</a> library to decode network packets in Python. It has an IP decoder which knows about the syntax of IPv4 packets but apparently no IPv6 decoder.</p>
<p>Does anyone get one? </p>
<p>In a private correspondance, the Impacket maintainers say it may be better to start with <a href="http://www.secdev.org/projects/scapy/" rel="nofollow">Scapy</a></p>
| 2 | 2008-12-15T21:25:32Z | 1,053,476 | <p>You can use a really useful one-file library from google from </p>
<p><a href="http://code.google.com/p/ipaddr-py/" rel="nofollow">http://code.google.com/p/ipaddr-py/</a></p>
<p>that supports IPv4, IPv6, ip validation, netmask and prefix managements, etc. It's well coded and documented.</p>
<p>Good luck<br />
Emilio</p>
| -1 | 2009-06-27T19:43:23Z | [
"python",
"ipv6",
"packet-capture",
"pcap"
] |
IPv6 decoder for pcapy/impacket | 369,764 | <p>I use the <a href="http://oss.coresecurity.com/projects/pcapy.html" rel="nofollow">pcapy</a>/<a href="http://oss.coresecurity.com/projects/impacket.html" rel="nofollow">impacket</a> library to decode network packets in Python. It has an IP decoder which knows about the syntax of IPv4 packets but apparently no IPv6 decoder.</p>
<p>Does anyone get one? </p>
<p>In a private correspondance, the Impacket maintainers say it may be better to start with <a href="http://www.secdev.org/projects/scapy/" rel="nofollow">Scapy</a></p>
| 2 | 2008-12-15T21:25:32Z | 1,076,725 | <p>You may want to look into <a href="http://code.google.com/p/dpkt/" rel="nofollow"><code>dpkt</code></a>, yet another packet parsing/building library. It was written by the author of <a href="http://code.google.com/p/pypcap/" rel="nofollow"><code>pypcap</code></a>, a different libpcap wrapper, but it shouldn't be too difficult to get it working with pcapy to see if it's faster for your purposes than Scapy.</p>
| 1 | 2009-07-02T21:15:57Z | [
"python",
"ipv6",
"packet-capture",
"pcap"
] |
Difference between dict.clear() and assigning {} in Python | 369,898 | <p>In python, is there a difference between calling <code>clear()</code> and assigning <code>{}</code> to a dictionary? If yes, what is it?
Example:<pre><code>d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
</code></pre></p>
| 104 | 2008-12-15T22:23:18Z | 369,925 | <p>If you have another variable also referring to the same dictionary, there is a big difference:</p>
<pre><code>>>> d = {"stuff": "things"}
>>> d2 = d
>>> d = {}
>>> d2
{'stuff': 'things'}
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d.clear()
>>> d2
{}
</code></pre>
<p>This is because assigning <code>d = {}</code> creates a new, empty dictionary and assigns it to the <code>d</code> variable. This leaves <code>d2</code> pointing at the old dictionary with items still in it. However, <code>d.clear()</code> clears the same dictionary that <code>d</code> and <code>d2</code> both point at.</p>
| 187 | 2008-12-15T22:30:29Z | [
"python",
"dictionary"
] |
Difference between dict.clear() and assigning {} in Python | 369,898 | <p>In python, is there a difference between calling <code>clear()</code> and assigning <code>{}</code> to a dictionary? If yes, what is it?
Example:<pre><code>d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
</code></pre></p>
| 104 | 2008-12-15T22:23:18Z | 369,928 | <p><code>d = {}</code> will create a new instance for <code>d</code> but all other references will still point to the old contents.
<code>d.clear()</code> will reset the contents, but all references to the same instance will still be correct.</p>
| 21 | 2008-12-15T22:32:02Z | [
"python",
"dictionary"
] |
Difference between dict.clear() and assigning {} in Python | 369,898 | <p>In python, is there a difference between calling <code>clear()</code> and assigning <code>{}</code> to a dictionary? If yes, what is it?
Example:<pre><code>d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
</code></pre></p>
| 104 | 2008-12-15T22:23:18Z | 371,045 | <p>In addition to the differences mentioned in other answers, there also is a speed difference. d = {} is over twice as fast:</p>
<pre><code>python -m timeit -s "d = {}" "for i in xrange(500000): d.clear()"
10 loops, best of 3: 127 msec per loop
python -m timeit -s "d = {}" "for i in xrange(500000): d = {}"
10 loops, best of 3: 53.6 msec per loop
</code></pre>
| 13 | 2008-12-16T11:31:10Z | [
"python",
"dictionary"
] |
Difference between dict.clear() and assigning {} in Python | 369,898 | <p>In python, is there a difference between calling <code>clear()</code> and assigning <code>{}</code> to a dictionary? If yes, what is it?
Example:<pre><code>d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
</code></pre></p>
| 104 | 2008-12-15T22:23:18Z | 8,428,220 | <p>As an illustration for the things already mentioned before:</p>
<pre><code>>>> a = {1:2}
>>> id(a)
3073677212L
>>> a.clear()
>>> id(a)
3073677212L
>>> a = {}
>>> id(a)
3073675716L
</code></pre>
| 4 | 2011-12-08T08:34:25Z | [
"python",
"dictionary"
] |
Difference between dict.clear() and assigning {} in Python | 369,898 | <p>In python, is there a difference between calling <code>clear()</code> and assigning <code>{}</code> to a dictionary? If yes, what is it?
Example:<pre><code>d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
</code></pre></p>
| 104 | 2008-12-15T22:23:18Z | 14,029,061 | <p>In addition to @odano 's answer, it seems using <code>d.clear()</code> is faster if you would like to clear the dict for many times.</p>
<pre><code>import timeit
p1 = '''
d = {}
for i in xrange(1000):
d[i] = i * i
for j in xrange(100):
d = {}
for i in xrange(1000):
d[i] = i * i
'''
p2 = '''
d = {}
for i in xrange(1000):
d[i] = i * i
for j in xrange(100):
d.clear()
for i in xrange(1000):
d[i] = i * i
'''
print timeit.timeit(p1, number=1000)
print timeit.timeit(p2, number=1000)
</code></pre>
<p>The result is:</p>
<pre><code>20.0367929935
19.6444659233
</code></pre>
| 6 | 2012-12-25T08:41:33Z | [
"python",
"dictionary"
] |
Difference between dict.clear() and assigning {} in Python | 369,898 | <p>In python, is there a difference between calling <code>clear()</code> and assigning <code>{}</code> to a dictionary? If yes, what is it?
Example:<pre><code>d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
</code></pre></p>
| 104 | 2008-12-15T22:23:18Z | 18,435,585 | <p>One thing not mentioned is scoping issues. Not a great example, but here's the case where I ran into the problem:</p>
<pre><code>def conf_decorator(dec):
"""Enables behavior like this:
@threaded
def f(): ...
or
@threaded(thread=KThread)
def f(): ...
(assuming threaded is wrapped with this function.)
Sends any accumulated kwargs to threaded.
"""
c_kwargs = {}
@wraps(dec)
def wrapped(f=None, **kwargs):
if f:
r = dec(f, **c_kwargs)
c_kwargs = {}
return r
else:
c_kwargs.update(kwargs) #<- UnboundLocalError: local variable 'c_kwargs' referenced before assignment
return wrapped
return wrapped
</code></pre>
<p>The solution is to replace <code>c_kwargs = {}</code> with <code>c_kwargs.clear()</code></p>
<p>If someone thinks up a more practical example, feel free to edit this post.</p>
| 2 | 2013-08-26T01:53:11Z | [
"python",
"dictionary"
] |
Difference between dict.clear() and assigning {} in Python | 369,898 | <p>In python, is there a difference between calling <code>clear()</code> and assigning <code>{}</code> to a dictionary? If yes, what is it?
Example:<pre><code>d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
</code></pre></p>
| 104 | 2008-12-15T22:23:18Z | 33,914,011 | <p><em>Mutating</em> methods are always useful if the original object is not in scope:</p>
<pre><code>def fun(d):
d.clear()
d["b"] = 2
d={"a": 2}
fun(d)
d # {'b': 2}
</code></pre>
<p>Re-assigning the dictionary would create a new object and wouldn't modify the original one.</p>
| 2 | 2015-11-25T10:27:12Z | [
"python",
"dictionary"
] |
command-line world clock? | 370,075 | <p>Is there a script to display a simple world clock (time in various places around the world) on a *nix terminal?</p>
<p>I was thinking of writing a quick Python script, but I have a feeling that's gonna be more work than I think (e.g. due to config and output format) - not to mention reinventing the wheel...</p>
| 4 | 2008-12-15T23:39:23Z | 370,100 | <p>If you do still want to write it in Python, consider Pytz:</p>
<p><a href="http://pytz.sourceforge.net/" rel="nofollow">http://pytz.sourceforge.net/</a></p>
<p>Their front page shows you many simple ways to accomplish what you're looking for.</p>
<p>That said, I'm sure if you spent a few minutes on Google you'd find tons of scripts, some that even launch graphical programs for *nix. The first list of results for "python world clock" seem to suggest this alone.</p>
| 1 | 2008-12-15T23:48:56Z | [
"python",
"timezone",
"command-line-interface"
] |
command-line world clock? | 370,075 | <p>Is there a script to display a simple world clock (time in various places around the world) on a *nix terminal?</p>
<p>I was thinking of writing a quick Python script, but I have a feeling that's gonna be more work than I think (e.g. due to config and output format) - not to mention reinventing the wheel...</p>
| 4 | 2008-12-15T23:39:23Z | 370,105 | <p>I have this bourne shell script:</p>
<pre><code>#!/bin/sh
PT=`env TZ=US/Pacific date`
CT=`env TZ=US/Central date`
AT=`env TZ=Australia/Melbourne date`
echo "Santa Clara $PT"
echo "Central $CT"
echo "Melbourne $AT"
</code></pre>
| 13 | 2008-12-15T23:50:55Z | [
"python",
"timezone",
"command-line-interface"
] |
command-line world clock? | 370,075 | <p>Is there a script to display a simple world clock (time in various places around the world) on a *nix terminal?</p>
<p>I was thinking of writing a quick Python script, but I have a feeling that's gonna be more work than I think (e.g. due to config and output format) - not to mention reinventing the wheel...</p>
| 4 | 2008-12-15T23:39:23Z | 370,121 | <p>Never thought of it, but not dreadfully hard to do.</p>
<pre><code>#!/bin/sh
# Command-line world clock
: ${WORLDCLOCK_ZONES:=$HOME/etc/worldclock.zones}
: ${WORLDCLOCK_FORMAT:='+%Y-%m-%d %H:%M:%S %Z'}
while read zone
do echo $zone '!' $(TZ=$zone date "$WORLDCLOCK_FORMAT")
done < $WORLDCLOCK_ZONES |
awk -F '!' '{ printf "%-20s %s\n", $1, $2;}'
</code></pre>
<p>Given the input file:</p>
<pre><code>US/Pacific
Europe/London
Europe/Paris
Asia/Kolkatta
Africa/Johannesburg
Asia/Tokyo
Asia/Shanghai
</code></pre>
<p>I got the output:</p>
<pre><code>US/Pacific 2008-12-15 15:58:57 PST
Europe/London 2008-12-15 23:58:57 GMT
Europe/Paris 2008-12-16 00:58:57 CET
Asia/Kolkatta 2008-12-15 23:58:57 GMT
Africa/Johannesburg 2008-12-16 01:58:57 SAST
Asia/Tokyo 2008-12-16 08:58:57 JST
Asia/Shanghai 2008-12-16 07:58:57 CST
</code></pre>
<p>I was fortunate that this took less than a second to run and didn't cross a 1-second boundary.</p>
<p>(<em>I didn't notice that Kolkatta failed and defaulted to GMT. My system still has Asia/Calcutta as the entry for India.</em>)</p>
| 6 | 2008-12-15T23:59:24Z | [
"python",
"timezone",
"command-line-interface"
] |
command-line world clock? | 370,075 | <p>Is there a script to display a simple world clock (time in various places around the world) on a *nix terminal?</p>
<p>I was thinking of writing a quick Python script, but I have a feeling that's gonna be more work than I think (e.g. due to config and output format) - not to mention reinventing the wheel...</p>
| 4 | 2008-12-15T23:39:23Z | 618,313 | <p>I use this, which is basically the same as the other suggestions, except it filters on specific zones you want to see:</p>
<pre><code>#!/bin/sh
# Show date and time in other time zones
search=$1
zoneinfo=/usr/share/zoneinfo/posix/
format='%a %F %T'
find $zoneinfo -type f \
| grep -i "$search" \
| while read z
do
d=$(TZ=$z date +"$format")
printf "%-34s %23s\n" ${z#$zoneinfo} "$d"
done
</code></pre>
<p>Sample output:</p>
<pre><code>$ /usr/local/bin/wdate bang
Africa/Bangui Fri 2009-03-06 11:04:24
Asia/Bangkok Fri 2009-03-06 17:04:24
</code></pre>
| 1 | 2009-03-06T10:10:01Z | [
"python",
"timezone",
"command-line-interface"
] |
command-line world clock? | 370,075 | <p>Is there a script to display a simple world clock (time in various places around the world) on a *nix terminal?</p>
<p>I was thinking of writing a quick Python script, but I have a feeling that's gonna be more work than I think (e.g. due to config and output format) - not to mention reinventing the wheel...</p>
| 4 | 2008-12-15T23:39:23Z | 31,997,386 | <p>I like the script <a href="http://stackoverflow.com/users/111036/mivk">mivk</a> provided.
As I want to be able to specify multiple zones without regex, I adapted the script to use bash when I couldn't get bourne shell to deal with arrays.
Anyway, enjoy and thanks for a great forum:</p>
<pre><code>#!/usr/bin/env bash
# Show date and time in other time zones, with multiple args
elements=$@
zoneinfo=/usr/share/zoneinfo
format='%a %F %T'
for search in ${elements[@]}; do
find $zoneinfo -type f \
| grep -i "$search" \
| while read z
do
d=$(TZ=$z date +"$format")
printf "%-34s %23s\n" ${z#$zoneinfo} "$d"
done
done
</code></pre>
<p>Sample output:</p>
<p><code>/usr/local/bin/wdate Sydney Stockholm
/Australia/Sydney Fri 2015-08-14 05:54:26
/Europe/Stockholm Thu 2015-08-13 21:54:26</code></p>
| 0 | 2015-08-13T20:02:00Z | [
"python",
"timezone",
"command-line-interface"
] |
command-line world clock? | 370,075 | <p>Is there a script to display a simple world clock (time in various places around the world) on a *nix terminal?</p>
<p>I was thinking of writing a quick Python script, but I have a feeling that's gonna be more work than I think (e.g. due to config and output format) - not to mention reinventing the wheel...</p>
| 4 | 2008-12-15T23:39:23Z | 32,000,263 | <p>There is <a href="https://hg.python.org/cpython/file/2.7/Demo/curses/tclock.py" rel="nofollow">./cpython-2.7/Demo/curses/tclock.py</a> that is a port of <code>tclock.c</code> -- 1994 ASCII analog/digital clock for <code>curses</code>, from ncurses-examples. Usage:</p>
<pre><code>$ TZ=Europe/Paris python tclock.py
</code></pre>
<p>Here's <a href="https://youtu.be/AnEETGuJ-4Q?t=35s" rel="nofollow">video</a>.</p>
| 1 | 2015-08-13T23:52:02Z | [
"python",
"timezone",
"command-line-interface"
] |
How do I put a SQLAlchemy label on the result of an arithmetic expression? | 370,077 | <p>How do I translate something like this into SQLAlchemy?</p>
<pre><code>select x - y as difference...
</code></pre>
<p>I know how to do:</p>
<pre><code>x.label('foo')
</code></pre>
<p>...but I'm not sure where to put the ".label()" method call below:</p>
<pre><code>select ([table.c.x - table.c.y], ...
</code></pre>
| 2 | 2008-12-15T23:39:59Z | 370,600 | <p>The <code>ColumnElement</code> method is just a helper; <a href="http://docs.sqlalchemy.org/en/latest/core/expression_api.html#sqlalchemy.sql.expression.label" rel="nofollow">label()</a> can be used following way:</p>
<pre><code>select([sql.expression.label('foo', table.c.x - table.c.y), ...])
</code></pre>
| 6 | 2008-12-16T06:52:24Z | [
"python",
"sqlalchemy"
] |
How do I ORDER BY an arithmetic express in SQLAlchemy? | 370,160 | <p>How do I translate something like this into SQLAlchemy?</p>
<pre><code>SELECT (a * b) - (x + y) / z AS result
FROM table
ORDER BY result
</code></pre>
| 3 | 2008-12-16T00:16:41Z | 370,640 | <p>Just pass the label in as a string argument to <code>order_by</code>:</p>
<pre><code>result_exp = sqlalchemy.sql.expression.label('result',
((test2_table.c.a * test2_table.c.b)
- (test2_table.c.x + test2_table.c.y)
/ test2_table.c.z))
select([result_exp], from_obj=[test2_table], order_by="result")
</code></pre>
| 3 | 2008-12-16T07:17:42Z | [
"python",
"sqlalchemy"
] |
SQLAlchemy with count, group_by and order_by using the ORM | 370,174 | <p>I've got several function where I need to do a one-to-many join, using count(), group_by, and order_by. I'm using the sqlalchemy.select function to produce a query that will return me a set of id's, which I then iterate over to do an ORM select on the individual records. What I'm wondering is if there is a way to do what I need using the ORM in a single query so that I can avoid having to do the iteration.</p>
<p>Here's an example of what I'm doing now. In this case the entities are Location and Guide, mapped one-to-many. I'm trying get a list of the top locations sorted by how many guides they are related to.</p>
<pre><code>def popular_world_cities(self):
query = select([locations.c.id, func.count(Guide.location_id).label('count')],
from_obj=[locations, guides],
whereclause="guides.location_id = locations.id AND (locations.type = 'city' OR locations.type = 'custom')",
group_by=[Location.id],
order_by='count desc',
limit=10)
return map(lambda x: meta.Session.query(Location).filter_by(id=x[0]).first(), meta.engine.execute(query).fetchall())
</code></pre>
<p><strong>Solution</strong></p>
<p>I've found the best way to do this. Simply supply a <code>from_statement</code> instead of a <code>filter_by</code> or some such. Like so:</p>
<pre><code>meta.Session.query(Location).from_statement(query).all()
</code></pre>
| 3 | 2008-12-16T00:27:41Z | 370,654 | <p>What you're trying to do maps directly to a SQLAlchemy join between a subquery [made from your current select call] and a table. You'll want to move the ordering out of the subselect and create a separate, labeled column with count(desc); order the outer select by that column.</p>
<p>Other than that, I don't see much that's nonobvious.</p>
| 1 | 2008-12-16T07:30:29Z | [
"python",
"sqlalchemy"
] |
SQLAlchemy with count, group_by and order_by using the ORM | 370,174 | <p>I've got several function where I need to do a one-to-many join, using count(), group_by, and order_by. I'm using the sqlalchemy.select function to produce a query that will return me a set of id's, which I then iterate over to do an ORM select on the individual records. What I'm wondering is if there is a way to do what I need using the ORM in a single query so that I can avoid having to do the iteration.</p>
<p>Here's an example of what I'm doing now. In this case the entities are Location and Guide, mapped one-to-many. I'm trying get a list of the top locations sorted by how many guides they are related to.</p>
<pre><code>def popular_world_cities(self):
query = select([locations.c.id, func.count(Guide.location_id).label('count')],
from_obj=[locations, guides],
whereclause="guides.location_id = locations.id AND (locations.type = 'city' OR locations.type = 'custom')",
group_by=[Location.id],
order_by='count desc',
limit=10)
return map(lambda x: meta.Session.query(Location).filter_by(id=x[0]).first(), meta.engine.execute(query).fetchall())
</code></pre>
<p><strong>Solution</strong></p>
<p>I've found the best way to do this. Simply supply a <code>from_statement</code> instead of a <code>filter_by</code> or some such. Like so:</p>
<pre><code>meta.Session.query(Location).from_statement(query).all()
</code></pre>
| 3 | 2008-12-16T00:27:41Z | 468,869 | <p>I've found the best way to do this. Simply supply a <code>from_statement</code> instead of a <code>filter_by</code> or some such. Like so:</p>
<pre><code>meta.Session.query(Location).from_statement(query).all()
</code></pre>
| 0 | 2009-01-22T12:03:15Z | [
"python",
"sqlalchemy"
] |
SQLAlchemy with count, group_by and order_by using the ORM | 370,174 | <p>I've got several function where I need to do a one-to-many join, using count(), group_by, and order_by. I'm using the sqlalchemy.select function to produce a query that will return me a set of id's, which I then iterate over to do an ORM select on the individual records. What I'm wondering is if there is a way to do what I need using the ORM in a single query so that I can avoid having to do the iteration.</p>
<p>Here's an example of what I'm doing now. In this case the entities are Location and Guide, mapped one-to-many. I'm trying get a list of the top locations sorted by how many guides they are related to.</p>
<pre><code>def popular_world_cities(self):
query = select([locations.c.id, func.count(Guide.location_id).label('count')],
from_obj=[locations, guides],
whereclause="guides.location_id = locations.id AND (locations.type = 'city' OR locations.type = 'custom')",
group_by=[Location.id],
order_by='count desc',
limit=10)
return map(lambda x: meta.Session.query(Location).filter_by(id=x[0]).first(), meta.engine.execute(query).fetchall())
</code></pre>
<p><strong>Solution</strong></p>
<p>I've found the best way to do this. Simply supply a <code>from_statement</code> instead of a <code>filter_by</code> or some such. Like so:</p>
<pre><code>meta.Session.query(Location).from_statement(query).all()
</code></pre>
| 3 | 2008-12-16T00:27:41Z | 679,479 | <p>Guys, I found this the hard way but SQL Alchemy does support group_by. The documentation under Query doesn't say so but it does support it - I have used it!!</p>
<p>And, you can also use order_by. I was going to create a special class/query like you did but then I found out there is a group_by() function.</p>
<p>Hope this will help someone!!</p>
| 1 | 2009-03-24T22:17:06Z | [
"python",
"sqlalchemy"
] |
Python variable scope error | 370,357 | <p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p>
<pre><code>a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
</code></pre>
<p>However, when I uncomment line <strong>(B)</strong>, I get an <em>UnboundLocalError: 'c' not assigned</em> at line <strong>(A)</strong>. The values of <em>a</em> and <em>b</em> are printed correctly. This has me completely baffled for two reasons:</p>
<ol>
<li><p>Why is there a runtime error thrown at line <strong>(A)</strong> because of a later statement on line <strong>(B)</strong>?</p></li>
<li><p>Why are variables <em>a</em> and <em>b</em> printed as expected, while <em>c</em> raises an error?</p></li>
</ol>
<p>The only explanation I can come up with is that a <strong>local</strong> variable <em>c</em> is created by the assignment <code>c+=1</code>, which takes precedent over the "global" variable <em>c</em> even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists.</p>
<p>Could someone please explain this behavior?</p>
| 136 | 2008-12-16T03:06:52Z | 370,363 | <p>Python treats variables in functions differently depending on whether you assign values to them from within the function or not. If you assign any value to a variable, it is treated by default as a local variable. Therefore, when you uncomment the line, you are attempting to reference a local variable before any value has been assigned to it.</p>
<p>If you want the variable c to refer to the global c put</p>
<pre><code>global c
</code></pre>
<p>as the first line of the function.</p>
<p>As of python 3, there is now</p>
<pre><code>nonlocal c
</code></pre>
<p>that you can use to refer to the nearest enclosing (not necessarily global) scope.</p>
| 150 | 2008-12-16T03:12:56Z | [
"python",
"variables",
"scope"
] |
Python variable scope error | 370,357 | <p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p>
<pre><code>a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
</code></pre>
<p>However, when I uncomment line <strong>(B)</strong>, I get an <em>UnboundLocalError: 'c' not assigned</em> at line <strong>(A)</strong>. The values of <em>a</em> and <em>b</em> are printed correctly. This has me completely baffled for two reasons:</p>
<ol>
<li><p>Why is there a runtime error thrown at line <strong>(A)</strong> because of a later statement on line <strong>(B)</strong>?</p></li>
<li><p>Why are variables <em>a</em> and <em>b</em> printed as expected, while <em>c</em> raises an error?</p></li>
</ol>
<p>The only explanation I can come up with is that a <strong>local</strong> variable <em>c</em> is created by the assignment <code>c+=1</code>, which takes precedent over the "global" variable <em>c</em> even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists.</p>
<p>Could someone please explain this behavior?</p>
| 136 | 2008-12-16T03:06:52Z | 370,364 | <p>Python has rather interesting behavior when you try traditional global variable semantics. I don't remember the details, but you can read the value of a variable declared in 'global' scope just fine, if you want to modify it, you have to use the global keyword. Try changing test() to this:</p>
<pre><code>def test():
global c
print(a)
print(b)
print(c) # (A)
c+=1 # (B)
</code></pre>
<p>Also, the reason you are getting this error is because you can also declare a new variable inside that function with the same name as a 'global' one, and it would be completely separate. The interpreter thinks you are trying to make a new variable in this scope called 'c' and modify it all in one operation, which isn't allowed in python because this new 'c' wasn't initialized.</p>
| 8 | 2008-12-16T03:12:59Z | [
"python",
"variables",
"scope"
] |
Python variable scope error | 370,357 | <p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p>
<pre><code>a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
</code></pre>
<p>However, when I uncomment line <strong>(B)</strong>, I get an <em>UnboundLocalError: 'c' not assigned</em> at line <strong>(A)</strong>. The values of <em>a</em> and <em>b</em> are printed correctly. This has me completely baffled for two reasons:</p>
<ol>
<li><p>Why is there a runtime error thrown at line <strong>(A)</strong> because of a later statement on line <strong>(B)</strong>?</p></li>
<li><p>Why are variables <em>a</em> and <em>b</em> printed as expected, while <em>c</em> raises an error?</p></li>
</ol>
<p>The only explanation I can come up with is that a <strong>local</strong> variable <em>c</em> is created by the assignment <code>c+=1</code>, which takes precedent over the "global" variable <em>c</em> even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists.</p>
<p>Could someone please explain this behavior?</p>
| 136 | 2008-12-16T03:06:52Z | 370,380 | <p>okay, here's the deal. Python is a little weird, in that it keeps everything in a dictionary for the various scopes. The original a,b,c are in the uppermost scope and so in that uppermost dictionary. The function has its own dictionary. When you reach the <code>print(a)</code> and <code>print(b)</code> statements, there's nothing by that name in the dictionary, so Python looks up the list and finds them in the clobal dictionary.</p>
<p>Now we get to <code>c+=1</code>, which is, of course, equivalent to <code>c=c+1</code>. When Python scans that line, it says "ahah, there's a variable named c, I'll put it into my local scope dictionary." Then when it goes looking for a value for c for the c on the right hand side of the assignment, it finds its <em>local variable named c</em>, which has no value yet, and so throws the error.</p>
<p>The statement <code>global c</code> mentioned above simply tells the parser that it uses the c from the global scope and so doesn't need a new one.</p>
<p>The reason it says there's an issue on the line it does is because it is effectively looking for the names before it tries to generate code, and so in some sense doesn't think it's really doing that line yet. I'd argue that is a useability bug, but it's generally a good practice to just learn not to take a compiler's messages <em>too</em> seriously.</p>
<p>If it's any comfort, I spent probably a day digging and experimenting with this same issue before I found something Guido had written about the dictionaries that Explained Everything.</p>
<h3>Update, see comments:</h3>
<p>It doesn't scan the code twice, but it does scan the code in two phases, lexing and parsing.</p>
<p>Consider how the parse of this cline of code works. The lexer reads the source text and breaks it into lexemes, the "smallest components" of the grammar. So when it hits the line</p>
<pre><code>c+=1
</code></pre>
<p>it breaks it up into something like</p>
<pre><code>SYMBOL(c) OPERATOR(+=) DIGIT(1)
</code></pre>
<p>The parser eventually wants to make this into a parse tree and execute it, but since it's an assignment, before it does, it looks for the name c in the local dictionary, doesn't see it, and inserts it in the dictionary, marking it as uninitialized. In a fullly compiled language, it would just go into the symbol table and wait for the parse, but since it WON'T have the luxury of a second pass, the lexer does a little extra work to make life easier later on. Only, then it sees the OPERATOR, sees that the rules say "if you have an operator += the left hand side must have been initialized" and says "whoops!"</p>
<p>The point here is that it <em>hasn't really started the parse of the line yet</em>. This is all happening sort of preparatory to the actual parse, so the line counter hasn't advanced to the next line. Thus when it signals the error, it still thinks its on the previous line.</p>
<p>As I say, you could argue it's a usability bug, but its actually a fairly common thing. Some compilers are more honest about it and say "error on or around line XXX", but this one doesn't.</p>
| 54 | 2008-12-16T03:25:29Z | [
"python",
"variables",
"scope"
] |
Python variable scope error | 370,357 | <p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p>
<pre><code>a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
</code></pre>
<p>However, when I uncomment line <strong>(B)</strong>, I get an <em>UnboundLocalError: 'c' not assigned</em> at line <strong>(A)</strong>. The values of <em>a</em> and <em>b</em> are printed correctly. This has me completely baffled for two reasons:</p>
<ol>
<li><p>Why is there a runtime error thrown at line <strong>(A)</strong> because of a later statement on line <strong>(B)</strong>?</p></li>
<li><p>Why are variables <em>a</em> and <em>b</em> printed as expected, while <em>c</em> raises an error?</p></li>
</ol>
<p>The only explanation I can come up with is that a <strong>local</strong> variable <em>c</em> is created by the assignment <code>c+=1</code>, which takes precedent over the "global" variable <em>c</em> even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists.</p>
<p>Could someone please explain this behavior?</p>
| 136 | 2008-12-16T03:06:52Z | 370,752 | <p>The Python interpreter will read a function as a complete unit. I think of it as reading it in two passes, once to gather its closure (the local variables), then again to turn it into byte-code.</p>
<p>As I'm sure you were already aware, any name used on the left of a '=' is implicitly a local variable. More than once I've been caught out by changing a variable access to a += and it's suddenly a different variable.</p>
<p>I also wanted to point out it's not really anything to do with global scope specifically. You get the same behaviour with nested functions.</p>
| 0 | 2008-12-16T08:58:10Z | [
"python",
"variables",
"scope"
] |
Python variable scope error | 370,357 | <p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p>
<pre><code>a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
</code></pre>
<p>However, when I uncomment line <strong>(B)</strong>, I get an <em>UnboundLocalError: 'c' not assigned</em> at line <strong>(A)</strong>. The values of <em>a</em> and <em>b</em> are printed correctly. This has me completely baffled for two reasons:</p>
<ol>
<li><p>Why is there a runtime error thrown at line <strong>(A)</strong> because of a later statement on line <strong>(B)</strong>?</p></li>
<li><p>Why are variables <em>a</em> and <em>b</em> printed as expected, while <em>c</em> raises an error?</p></li>
</ol>
<p>The only explanation I can come up with is that a <strong>local</strong> variable <em>c</em> is created by the assignment <code>c+=1</code>, which takes precedent over the "global" variable <em>c</em> even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists.</p>
<p>Could someone please explain this behavior?</p>
| 136 | 2008-12-16T03:06:52Z | 370,830 | <p>Taking a look at the disassembly may clarify what is happening:</p>
<pre><code>>>> def f():
... print a
... print b
... a = 1
>>> import dis
>>> dis.dis(f)
2 0 LOAD_FAST 0 (a)
3 PRINT_ITEM
4 PRINT_NEWLINE
3 5 LOAD_GLOBAL 0 (b)
8 PRINT_ITEM
9 PRINT_NEWLINE
4 10 LOAD_CONST 1 (1)
13 STORE_FAST 0 (a)
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
</code></pre>
<p>As you can see, the bytecode for accessing a is <code>LOAD_FAST</code>, and for b, <code>LOAD_GLOBAL</code>. This is because the compiler has identified that a is assigned to within the function, and classified it as a local variable. The access mechanism for locals is fundamentally different for globals - they are statically assigned an offset in the frame's variables table, meaning lookup is a quick index, rather than the more expensive dict lookup as for globals. Because of this, Python is reading the <code>print a</code> line as "get the value of local variable 'a' held in slot 0, and print it", and when it detects that this variable is still uninitialised, raises an exception.</p>
| 38 | 2008-12-16T09:49:28Z | [
"python",
"variables",
"scope"
] |
Python variable scope error | 370,357 | <p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p>
<pre><code>a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
</code></pre>
<p>However, when I uncomment line <strong>(B)</strong>, I get an <em>UnboundLocalError: 'c' not assigned</em> at line <strong>(A)</strong>. The values of <em>a</em> and <em>b</em> are printed correctly. This has me completely baffled for two reasons:</p>
<ol>
<li><p>Why is there a runtime error thrown at line <strong>(A)</strong> because of a later statement on line <strong>(B)</strong>?</p></li>
<li><p>Why are variables <em>a</em> and <em>b</em> printed as expected, while <em>c</em> raises an error?</p></li>
</ol>
<p>The only explanation I can come up with is that a <strong>local</strong> variable <em>c</em> is created by the assignment <code>c+=1</code>, which takes precedent over the "global" variable <em>c</em> even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists.</p>
<p>Could someone please explain this behavior?</p>
| 136 | 2008-12-16T03:06:52Z | 476,123 | <p>This is not a direct answer to your question, but it is closely related, as it's another gotcha caused by the relationship between augmented assignment and function scopes.</p>
<p>In most cases, you tend to think of augmented assignment (a += b) as exactly equivalent to simple assignment (a = a + b). It is possible to get into some trouble with this though, in one corner case. Let me explain:</p>
<p>The way python's simple assignment works means that if a is passed into a function (like func(a); note that python is always pass-by-reference), then a = a + b will not modify the a that is passed in. Instead, it will just modify the local pointer to a. </p>
<p>But if you use a += b, then it is sometimes implemented as:</p>
<pre><code>a = a + b
</code></pre>
<p>or sometimes (if the method exists) as:</p>
<pre><code>a.__iadd__(b)
</code></pre>
<p>In the first case (as long as a is not declared global), there are no side-effects outside local scope, as the assignment to "a" is just a pointer update.</p>
<p>In the second case, a will actually modify itself, so all references to a will point to the modified version. This is demonstrated by the following code:</p>
<pre><code>def copy_on_write(a):
a = a + a
def inplace_add(a):
a += a
a = [1]
copy_on_write(a)
print a # [1]
inplace_add(a)
print a # [1, 1]
b = 1
copy_on_write(b)
print b # [1]
inplace_add(b)
print b # 1
</code></pre>
<p>So the trick is to avoid augmented assignment on function arguments (I try to only use it for local/loop variables). Use simple assignment, and you will be safe from ambiguous behaviour. </p>
| 2 | 2009-01-24T15:13:11Z | [
"python",
"variables",
"scope"
] |
Python variable scope error | 370,357 | <p>I've been programming for many years, and recently started learning Python. The following code works as expected in both python 2.5 and 3.0 (on OS X if that matters):</p>
<pre><code>a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
</code></pre>
<p>However, when I uncomment line <strong>(B)</strong>, I get an <em>UnboundLocalError: 'c' not assigned</em> at line <strong>(A)</strong>. The values of <em>a</em> and <em>b</em> are printed correctly. This has me completely baffled for two reasons:</p>
<ol>
<li><p>Why is there a runtime error thrown at line <strong>(A)</strong> because of a later statement on line <strong>(B)</strong>?</p></li>
<li><p>Why are variables <em>a</em> and <em>b</em> printed as expected, while <em>c</em> raises an error?</p></li>
</ol>
<p>The only explanation I can come up with is that a <strong>local</strong> variable <em>c</em> is created by the assignment <code>c+=1</code>, which takes precedent over the "global" variable <em>c</em> even before the local variable is created. Of course, it doesn't make sense for a variable to "steal" scope before it exists.</p>
<p>Could someone please explain this behavior?</p>
| 136 | 2008-12-16T03:06:52Z | 1,745,180 | <p>Here are two links that may help</p>
<p>1: <a href="http://docs.python.org/3.1/faq/programming.html?highlight=nonlocal#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" rel="nofollow">docs.python.org/3.1/faq/programming.html?highlight=nonlocal#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value</a></p>
<p>2: <a href="http://docs.python.org/3.1/faq/programming.html?highlight=nonlocal#how-do-i-write-a-function-with-output-parameters-call-by-reference" rel="nofollow">docs.python.org/3.1/faq/programming.html?highlight=nonlocal#how-do-i-write-a-function-with-output-parameters-call-by-reference</a></p>
<p>link one describes the error UnboundLocalError. Link two can help with with re-writing your test function. Based on link two, the original problem could be rewritten as:</p>
<pre><code>>>> a, b, c = (1, 2, 3)
>>> print (a, b, c)
(1, 2, 3)
>>> def test (a, b, c):
... print (a)
... print (b)
... print (c)
... c += 1
... return a, b, c
...
>>> a, b, c = test (a, b, c)
1
2
3
>>> print (a, b ,c)
(1, 2, 4)
</code></pre>
| 3 | 2009-11-16T22:12:19Z | [
"python",
"variables",
"scope"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.