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
listlengths
1
5
python csv help
1,565,566
<p>Sometimes I need to parse string that is CSV, but I am having trouble whit quoted comas. As this code demonstrated. I am using python 2.4 </p> <pre><code>import csv for row in csv.reader(['one",f",two,three']): print row </code></pre> <p>i get 4 elements ['one"', 'f"', 'two', 'three'] but I would like to get this ['one", f"', 'two', 'three'] or 3 elements even if I try to use quotechar = '"' option (this is according to documentation default) still the same, how can I ignore coma in quotes?</p> <p>Edit: Thank you all for answers obviously I mistaken my input for CSV, et the end I parsed strig for key values (NAME,DESCR...)</p> <p>This is input</p> <blockquote> <p>NAME: "2801 chassis", DESCR: "2801 chassis, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx</p> </blockquote>
0
2009-10-14T10:53:18Z
1,565,603
<p>You can get the csv module to tell you, just feed your desired output into the writer</p> <pre><code>In [1]: import sys,csv In [2]: csv.writer(sys.stdout).writerow(['one", f"', 'two', 'three']) "one"", f""",two,three In [3]: csv.reader(['"one"", f""",two,three']).next() Out[3]: ['one", f"', 'two', 'three'] </code></pre>
3
2009-10-14T11:02:12Z
[ "python", "csv" ]
python csv help
1,565,566
<p>Sometimes I need to parse string that is CSV, but I am having trouble whit quoted comas. As this code demonstrated. I am using python 2.4 </p> <pre><code>import csv for row in csv.reader(['one",f",two,three']): print row </code></pre> <p>i get 4 elements ['one"', 'f"', 'two', 'three'] but I would like to get this ['one", f"', 'two', 'three'] or 3 elements even if I try to use quotechar = '"' option (this is according to documentation default) still the same, how can I ignore coma in quotes?</p> <p>Edit: Thank you all for answers obviously I mistaken my input for CSV, et the end I parsed strig for key values (NAME,DESCR...)</p> <p>This is input</p> <blockquote> <p>NAME: "2801 chassis", DESCR: "2801 chassis, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx</p> </blockquote>
0
2009-10-14T10:53:18Z
1,565,605
<p>Actually the result you get is correct—your CSV syntax is wrong.</p> <p>If you want to quote commas or other characters in a CSV value, you have to use quotes surrounding the whole value, not parts of it. If a value does not start with the quote character, Python's CSV implementation does not assume the value is quoted.</p> <p>So, instead of using</p> <pre><code>one",f",two,three </code></pre> <p>you should be using</p> <pre><code>"one,f",two,three </code></pre>
6
2009-10-14T11:02:44Z
[ "python", "csv" ]
python csv help
1,565,566
<p>Sometimes I need to parse string that is CSV, but I am having trouble whit quoted comas. As this code demonstrated. I am using python 2.4 </p> <pre><code>import csv for row in csv.reader(['one",f",two,three']): print row </code></pre> <p>i get 4 elements ['one"', 'f"', 'two', 'three'] but I would like to get this ['one", f"', 'two', 'three'] or 3 elements even if I try to use quotechar = '"' option (this is according to documentation default) still the same, how can I ignore coma in quotes?</p> <p>Edit: Thank you all for answers obviously I mistaken my input for CSV, et the end I parsed strig for key values (NAME,DESCR...)</p> <p>This is input</p> <blockquote> <p>NAME: "2801 chassis", DESCR: "2801 chassis, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx</p> </blockquote>
0
2009-10-14T10:53:18Z
1,566,303
<p>Your input string is not really CSV. Instead your input contains the column name in each row. If your input looks like this:</p> <pre><code>NAME: "2801 chassis", DESCR: "2801 chassis, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx NAME: "2802 wroomer", DESCR: "2802 wroomer, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx NAME: "2803 foobars", DESCR: "2803 foobars, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx </code></pre> <p>The simplest you can do is probably to filter out the column names first, in the whole file. That would then give you a CSV file you can parse. But that assumes each line has the same columns in the same order.</p> <p>However, if the data is not that consistent, you might want to parse it based on the names. Perhaps it looks like this:</p> <pre><code>NAME: "2801 chassis", PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx, DESCR: "2801 chassis, Hw Serial#: xxxxxxx, Hw Revision: 6.0" NAME: "2802 wroomer", DESCR: "2802 wroomer, Hw Serial#: xxxxxxx, Hw Revision: 6.0",PID: CISCO2801 , VID: V03 , SN: xxxxxxxxx NAME: "2803 foobars", VID: V03 ,PID: CISCO2801 ,SN: xxxxxxxxx </code></pre> <p>Or something. In that case I'd parse each line by looking for the first ':', split out the column head from that, then parse the value (including looking for quotes), and then continue with the rest of the line. Something like this (completely untested code):</p> <pre><code>def parseline(line): result = {} while ':' in line: column, rest = line.split(':',1) column = column.strip() rest = rest.strip() if rest[0] in ('"', '"'): # It's quoted. quotechar = rest[0] end = rest.find(quotechar, 1) # Find the end of the quote value = rest[1:end] end = rest.find(',', end) # Find the next comma else: #Not quoted, just find the next comma: end = rest.find(',', 1) # Find the end of the value value = rest[0:end] result[column] = value line = rest[end+1:] line.strip() return result </code></pre>
1
2009-10-14T13:39:53Z
[ "python", "csv" ]
Where to find documentation to python's library's inner workings
1,565,602
<p>Couldn't think of a better wording for the title. See for instance the answer to <a href="http://stackoverflow.com/questions/1564501/add-timeout-argument-to-pythons-queue-join">http://stackoverflow.com/questions/1564501/add-timeout-argument-to-pythons-queue-join</a></p> <p>The answer to that question uses an attribute of the Queue class called <code>all_tasks_done</code> (accidentally wrote <code>join_with_timeout</code> here in the original post).</p> <p>However, in <a href="http://docs.python.org/library/queue.html#module-Queue" rel="nofollow">http://docs.python.org/library/queue.html#module-Queue</a> that attribute is never mentioned. Where can someone who wants, for instance, to subclass <code>Queue</code> could find the documentation of the inner workings, other than reading the source code? </p> <p>EDIT: A lot of answers to this question state that it's best to just read the source. I'll try to explain my problem(s) with that:</p> <ol> <li>As much as I love python, it is still not a natural language, and reading english is easier than reading source code</li> <li>It is hard to infer some things from the source by itself, for instance something as "this variable must be locked before any calls to get() or put()". If the variable is commented then I am once again reading english and not the source code, so why not put it in the documentation document and not just in the source?</li> <li>(this is the most important reason IMO) It seems the decision what should be in the documentation and what shouldn't are made almost arbitrarily - can you really give me a good reason to why <code>all_tasks_done</code> <b>shouldn't</b> be mentioned?</li> </ol>
1
2009-10-14T11:01:41Z
1,565,627
<p>I know you said you don't want to read the <a href="http://svn.python.org/projects/python/trunk/Lib/Queue.py" rel="nofollow">source code</a>, but why not? it:</p> <ul> <li>Looks straightforward to understand;</li> <li>Is the definitive reference for how <code>Queue</code> works.</li> </ul> <p>In the example you gave (subclassing <code>Queue</code>), you shouldn't need to know the internal workings anyway. What if they change? Your subclass of <code>Queue</code> may end up breaking even though neither the interface nor observable behaviour of <code>Queue</code> has changed.</p>
2
2009-10-14T11:07:35Z
[ "python", "documentation" ]
Where to find documentation to python's library's inner workings
1,565,602
<p>Couldn't think of a better wording for the title. See for instance the answer to <a href="http://stackoverflow.com/questions/1564501/add-timeout-argument-to-pythons-queue-join">http://stackoverflow.com/questions/1564501/add-timeout-argument-to-pythons-queue-join</a></p> <p>The answer to that question uses an attribute of the Queue class called <code>all_tasks_done</code> (accidentally wrote <code>join_with_timeout</code> here in the original post).</p> <p>However, in <a href="http://docs.python.org/library/queue.html#module-Queue" rel="nofollow">http://docs.python.org/library/queue.html#module-Queue</a> that attribute is never mentioned. Where can someone who wants, for instance, to subclass <code>Queue</code> could find the documentation of the inner workings, other than reading the source code? </p> <p>EDIT: A lot of answers to this question state that it's best to just read the source. I'll try to explain my problem(s) with that:</p> <ol> <li>As much as I love python, it is still not a natural language, and reading english is easier than reading source code</li> <li>It is hard to infer some things from the source by itself, for instance something as "this variable must be locked before any calls to get() or put()". If the variable is commented then I am once again reading english and not the source code, so why not put it in the documentation document and not just in the source?</li> <li>(this is the most important reason IMO) It seems the decision what should be in the documentation and what shouldn't are made almost arbitrarily - can you really give me a good reason to why <code>all_tasks_done</code> <b>shouldn't</b> be mentioned?</li> </ol>
1
2009-10-14T11:01:41Z
1,565,638
<p>This problem isn't unique to just the Python library. It's often worth looking at the source if you have read the docs and are still stuck</p>
7
2009-10-14T11:10:03Z
[ "python", "documentation" ]
Where to find documentation to python's library's inner workings
1,565,602
<p>Couldn't think of a better wording for the title. See for instance the answer to <a href="http://stackoverflow.com/questions/1564501/add-timeout-argument-to-pythons-queue-join">http://stackoverflow.com/questions/1564501/add-timeout-argument-to-pythons-queue-join</a></p> <p>The answer to that question uses an attribute of the Queue class called <code>all_tasks_done</code> (accidentally wrote <code>join_with_timeout</code> here in the original post).</p> <p>However, in <a href="http://docs.python.org/library/queue.html#module-Queue" rel="nofollow">http://docs.python.org/library/queue.html#module-Queue</a> that attribute is never mentioned. Where can someone who wants, for instance, to subclass <code>Queue</code> could find the documentation of the inner workings, other than reading the source code? </p> <p>EDIT: A lot of answers to this question state that it's best to just read the source. I'll try to explain my problem(s) with that:</p> <ol> <li>As much as I love python, it is still not a natural language, and reading english is easier than reading source code</li> <li>It is hard to infer some things from the source by itself, for instance something as "this variable must be locked before any calls to get() or put()". If the variable is commented then I am once again reading english and not the source code, so why not put it in the documentation document and not just in the source?</li> <li>(this is the most important reason IMO) It seems the decision what should be in the documentation and what shouldn't are made almost arbitrarily - can you really give me a good reason to why <code>all_tasks_done</code> <b>shouldn't</b> be mentioned?</li> </ol>
1
2009-10-14T11:01:41Z
1,565,694
<p>Use the source, Luke.</p>
2
2009-10-14T11:27:29Z
[ "python", "documentation" ]
Where to find documentation to python's library's inner workings
1,565,602
<p>Couldn't think of a better wording for the title. See for instance the answer to <a href="http://stackoverflow.com/questions/1564501/add-timeout-argument-to-pythons-queue-join">http://stackoverflow.com/questions/1564501/add-timeout-argument-to-pythons-queue-join</a></p> <p>The answer to that question uses an attribute of the Queue class called <code>all_tasks_done</code> (accidentally wrote <code>join_with_timeout</code> here in the original post).</p> <p>However, in <a href="http://docs.python.org/library/queue.html#module-Queue" rel="nofollow">http://docs.python.org/library/queue.html#module-Queue</a> that attribute is never mentioned. Where can someone who wants, for instance, to subclass <code>Queue</code> could find the documentation of the inner workings, other than reading the source code? </p> <p>EDIT: A lot of answers to this question state that it's best to just read the source. I'll try to explain my problem(s) with that:</p> <ol> <li>As much as I love python, it is still not a natural language, and reading english is easier than reading source code</li> <li>It is hard to infer some things from the source by itself, for instance something as "this variable must be locked before any calls to get() or put()". If the variable is commented then I am once again reading english and not the source code, so why not put it in the documentation document and not just in the source?</li> <li>(this is the most important reason IMO) It seems the decision what should be in the documentation and what shouldn't are made almost arbitrarily - can you really give me a good reason to why <code>all_tasks_done</code> <b>shouldn't</b> be mentioned?</li> </ol>
1
2009-10-14T11:01:41Z
1,566,309
<p>I'm looking at Alex Martelli's Python in a Nutshell (2nd edition). On page 344 is section "Customizing Class Queue by Subclassing". Just a couple of paragraphs, but it doesn't mention anything about how to do "join_with_timeout".</p> <p>I also checked the Python Cookbook -- nothing there either on "all_tasks_done" of the Queue module.</p> <p>In general, those two are good places to check if you're doing something special with builtin classes or modules.</p> <p>But I believe that subclassing is the problem here. It depends on the implementation details of the superclass. If you look in the other thread that you mentioned, someone has come up with <a href="http://stackoverflow.com/questions/1564501/add-timeout-argument-to-pythons-queue-join/1564777#1564777">a solution that doesn't involve subclassing</a>. That solution seems correct to me.</p>
2
2009-10-14T13:41:37Z
[ "python", "documentation" ]
Strange numpy.float96 behaviour
1,565,731
<p>What am I missing:</p> <pre><code>In [66]: import numpy as np In [67]: np.float(7.0 / 8) Out[67]: 0.875 #OK In [68]: np.float32(7.0 / 8) Out[68]: 0.875 #OK In [69]: np.float96(7.0 / 8) Out[69]: -2.6815615859885194e+154 #WTF In [70]: sys.version Out[70]: '2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)]' </code></pre> <p>Edit. On cygwin the above code works OK:</p> <pre><code>$ python Python 2.5.2 (r252:60911, Dec 2 2008, 09:26:14) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.float(7.0 / 8) 0.875 &gt;&gt;&gt; np.float96(7.0 / 8) 0.875 </code></pre> <p>For the completeness, I checked this code in plain python (not Ipython):</p> <pre><code>C:\temp&gt;python Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.float(7.0 / 8) 0.875 &gt;&gt;&gt; np.float96(7.0 / 8) -2.6815615859885194e+154 &gt;&gt;&gt; </code></pre> <p><strong>EDIT</strong></p> <p>I saw three bug reports on Numpy's trac site (<a href="http://projects.scipy.org/numpy/ticket/976" rel="nofollow">976</a>, <a href="http://projects.scipy.org/numpy/ticket/902" rel="nofollow">902</a>, and <a href="http://projects.scipy.org/numpy/ticket/884" rel="nofollow">884</a>), but this one doesn't seem to be related to string representation. Therefore I have opened a new bug (<a href="http://projects.scipy.org/numpy/ticket/1263" rel="nofollow">1263</a>). Will update here the progress</p>
4
2009-10-14T11:36:56Z
1,566,168
<p>This works fine for me:</p> <pre><code>In [1]: import numpy as np In [2]: np.float(7.0/8) Out[2]: 0.875 In [3]: np.float96(7.0/8) Out[3]: 0.875 </code></pre> <p>What Numpy are you using? I'm using Python 2.6.2 and Numpy 1.3.0 and I'm on 64 bit Vista.</p> <p>I tried this same thing on another computer that is running 32 bit XP with Python 2.5.2 and Numpy 1.2.1 and to my surprise I get:</p> <pre><code>In [2]: np.float96(7.0/8) Out[2]: -2.6815615859885194e+154 </code></pre> <p>After some investigation, installing Python 2.6.3 and Numpy 1.3.0 on 32 bit XP, I've found:</p> <pre><code>In [2]: np.float96(7.0/8) Out[2]: 0.875 </code></pre> <p>So it must be a bug in either the old version of Numpy or a bug in the old version of Python...</p>
2
2009-10-14T13:17:49Z
[ "python", "numpy" ]
Strange numpy.float96 behaviour
1,565,731
<p>What am I missing:</p> <pre><code>In [66]: import numpy as np In [67]: np.float(7.0 / 8) Out[67]: 0.875 #OK In [68]: np.float32(7.0 / 8) Out[68]: 0.875 #OK In [69]: np.float96(7.0 / 8) Out[69]: -2.6815615859885194e+154 #WTF In [70]: sys.version Out[70]: '2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)]' </code></pre> <p>Edit. On cygwin the above code works OK:</p> <pre><code>$ python Python 2.5.2 (r252:60911, Dec 2 2008, 09:26:14) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.float(7.0 / 8) 0.875 &gt;&gt;&gt; np.float96(7.0 / 8) 0.875 </code></pre> <p>For the completeness, I checked this code in plain python (not Ipython):</p> <pre><code>C:\temp&gt;python Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.float(7.0 / 8) 0.875 &gt;&gt;&gt; np.float96(7.0 / 8) -2.6815615859885194e+154 &gt;&gt;&gt; </code></pre> <p><strong>EDIT</strong></p> <p>I saw three bug reports on Numpy's trac site (<a href="http://projects.scipy.org/numpy/ticket/976" rel="nofollow">976</a>, <a href="http://projects.scipy.org/numpy/ticket/902" rel="nofollow">902</a>, and <a href="http://projects.scipy.org/numpy/ticket/884" rel="nofollow">884</a>), but this one doesn't seem to be related to string representation. Therefore I have opened a new bug (<a href="http://projects.scipy.org/numpy/ticket/1263" rel="nofollow">1263</a>). Will update here the progress</p>
4
2009-10-14T11:36:56Z
1,574,704
<p>There were a few fixes for long double formatting issues on Windows in 1.3.0; at least <a href="http://projects.scipy.org/numpy/changeset/6219" rel="nofollow">http://projects.scipy.org/numpy/changeset/6219</a> <a href="http://projects.scipy.org/numpy/changeset/6218" rel="nofollow">http://projects.scipy.org/numpy/changeset/6218</a> <a href="http://projects.scipy.org/numpy/changeset/6217" rel="nofollow">http://projects.scipy.org/numpy/changeset/6217</a></p>
1
2009-10-15T20:03:14Z
[ "python", "numpy" ]
Strange numpy.float96 behaviour
1,565,731
<p>What am I missing:</p> <pre><code>In [66]: import numpy as np In [67]: np.float(7.0 / 8) Out[67]: 0.875 #OK In [68]: np.float32(7.0 / 8) Out[68]: 0.875 #OK In [69]: np.float96(7.0 / 8) Out[69]: -2.6815615859885194e+154 #WTF In [70]: sys.version Out[70]: '2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)]' </code></pre> <p>Edit. On cygwin the above code works OK:</p> <pre><code>$ python Python 2.5.2 (r252:60911, Dec 2 2008, 09:26:14) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.float(7.0 / 8) 0.875 &gt;&gt;&gt; np.float96(7.0 / 8) 0.875 </code></pre> <p>For the completeness, I checked this code in plain python (not Ipython):</p> <pre><code>C:\temp&gt;python Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.float(7.0 / 8) 0.875 &gt;&gt;&gt; np.float96(7.0 / 8) -2.6815615859885194e+154 &gt;&gt;&gt; </code></pre> <p><strong>EDIT</strong></p> <p>I saw three bug reports on Numpy's trac site (<a href="http://projects.scipy.org/numpy/ticket/976" rel="nofollow">976</a>, <a href="http://projects.scipy.org/numpy/ticket/902" rel="nofollow">902</a>, and <a href="http://projects.scipy.org/numpy/ticket/884" rel="nofollow">884</a>), but this one doesn't seem to be related to string representation. Therefore I have opened a new bug (<a href="http://projects.scipy.org/numpy/ticket/1263" rel="nofollow">1263</a>). Will update here the progress</p>
4
2009-10-14T11:36:56Z
1,797,862
<p>The problem is caused by incompatibilities between mingw compiler (the one used for the official numpy binary) and the MS runtime (the one printf is coming from).</p> <p>MS compiler consider long double and double to be equivalent types, and so does the MS C runtime (printf included). Mingw, for some reason, define long double as big enough to hold 80 bits extended precision numbers, but of course the MS printf does not know about it, and cannot print long double correctly.</p> <p>We circumvented around some problems by using our own formatting functions, but I think the real fix is to force long double to be a synonym to double when built with mingw. This will be done for numpy 1.5.0, I think.</p>
2
2009-11-25T15:51:13Z
[ "python", "numpy" ]
Why is Python's "append" not "push"?
1,566,266
<p>Does anyone know why Python's <code>list.append</code> function is not called <code>list.push</code> given that there's already a <code>list.pop</code> that removes and returns the last element (that indexed at -1) and <code>list.append</code> semantic is consistent with that use?</p>
176
2009-10-14T13:34:26Z
1,566,285
<p>Because it appends; it doesn't push. "Appending" adds to the end of a list, "pushing" adds to the front.</p> <p>Think of a queue vs. a stack.</p> <p><a href="http://docs.python.org/tutorial/datastructures.html">http://docs.python.org/tutorial/datastructures.html</a></p> <p><strong>Edit:</strong> To reword my second sentence more exactly, "Appending" very clearly implies adding something to the <em>end</em> of a list, regardless of the underlying implementation. Where a new element gets added when it's "pushed" is less clear. Pushing onto a stack is putting something on "top," but where it actually goes in the underlying data structure completely depends on implementation. On the other hand, pushing onto a queue implies adding it to the end.</p>
18
2009-10-14T13:36:55Z
[ "python" ]
Why is Python's "append" not "push"?
1,566,266
<p>Does anyone know why Python's <code>list.append</code> function is not called <code>list.push</code> given that there's already a <code>list.pop</code> that removes and returns the last element (that indexed at -1) and <code>list.append</code> semantic is consistent with that use?</p>
176
2009-10-14T13:34:26Z
1,566,287
<p>Because it appends an element to a list? Push is usually used when referring to stacks.</p>
9
2009-10-14T13:37:03Z
[ "python" ]
Why is Python's "append" not "push"?
1,566,266
<p>Does anyone know why Python's <code>list.append</code> function is not called <code>list.push</code> given that there's already a <code>list.pop</code> that removes and returns the last element (that indexed at -1) and <code>list.append</code> semantic is consistent with that use?</p>
176
2009-10-14T13:34:26Z
1,566,293
<p>Probably because the original version of Python (<strong>C</strong>Python) was written in C, not C++.</p> <p>The idea that a list is formed by pushing things onto the back of something is probably not as well-known as the thought of appending them.</p>
0
2009-10-14T13:38:01Z
[ "python" ]
Why is Python's "append" not "push"?
1,566,266
<p>Does anyone know why Python's <code>list.append</code> function is not called <code>list.push</code> given that there's already a <code>list.pop</code> that removes and returns the last element (that indexed at -1) and <code>list.append</code> semantic is consistent with that use?</p>
176
2009-10-14T13:34:26Z
1,566,294
<p>Because "append" intuitively means "add at the end of the list". If it was called "push", then it would be unclear whether we're adding stuff at the tail or at head of the list.</p>
9
2009-10-14T13:38:01Z
[ "python" ]
Why is Python's "append" not "push"?
1,566,266
<p>Does anyone know why Python's <code>list.append</code> function is not called <code>list.push</code> given that there's already a <code>list.pop</code> that removes and returns the last element (that indexed at -1) and <code>list.append</code> semantic is consistent with that use?</p>
176
2009-10-14T13:34:26Z
1,566,297
<p>Push is a defined <a href="http://en.wikipedia.org/wiki/Stack_%28data_structure%29" rel="nofollow">stack</a> behaviour; if you pushed A on to stack (B,C,D) you would get (A,B,C,D).</p> <p>If you used python append, the resulting dataset would look like (B,C,D,A)</p> <p>Edit: Wow, holy pedantry.</p> <p>I would assume that it would be clear from my example which part of the list is the top, and which part is the bottom. Assuming that most of us here read from left to right, the first element of any list is always going to be on the left.</p>
-1
2009-10-14T13:38:27Z
[ "python" ]
Why is Python's "append" not "push"?
1,566,266
<p>Does anyone know why Python's <code>list.append</code> function is not called <code>list.push</code> given that there's already a <code>list.pop</code> that removes and returns the last element (that indexed at -1) and <code>list.append</code> semantic is consistent with that use?</p>
176
2009-10-14T13:34:26Z
1,566,299
<p>Not an official answer by any means (just a guess based on using the language), but Python allows you to use lists as stacks (e.g., <a href="http://docs.python.org/tutorial/datastructures.html#using-lists-as-stacks">section 5.1.1 of the tutorial</a>). However, a list is still first of all a list, so the operations that are common to both use list terms (i.e., append) rather than stack terms (i.e., push). Since a pop operation isn't that common in lists (though 'removeLast' could have been used), they defined a pop() but not a push().</p>
6
2009-10-14T13:38:56Z
[ "python" ]
Why is Python's "append" not "push"?
1,566,266
<p>Does anyone know why Python's <code>list.append</code> function is not called <code>list.push</code> given that there's already a <code>list.pop</code> that removes and returns the last element (that indexed at -1) and <code>list.append</code> semantic is consistent with that use?</p>
176
2009-10-14T13:34:26Z
1,566,316
<p>Ok, personal opinion here, but Append and Prepend imply precise positions in a set.</p> <p>Push and Pop are really concepts that can be applied to either end of a set... Just as long as you're consistent... For some reason, to me, Push() seems like it should apply to the front of a set...</p>
3
2009-10-14T13:42:32Z
[ "python" ]
Why is Python's "append" not "push"?
1,566,266
<p>Does anyone know why Python's <code>list.append</code> function is not called <code>list.push</code> given that there's already a <code>list.pop</code> that removes and returns the last element (that indexed at -1) and <code>list.append</code> semantic is consistent with that use?</p>
176
2009-10-14T13:34:26Z
1,566,329
<p>FYI, it's not terribly difficult to make a list that has a push method:</p> <pre><code>&gt;&gt;&gt; class StackList(list): ... def push(self, item): ... self.append(item) ... &gt;&gt;&gt; x = StackList([1,2,3]) &gt;&gt;&gt; x [1, 2, 3] &gt;&gt;&gt; x.push(4) &gt;&gt;&gt; x [1, 2, 3, 4] </code></pre> <p>A stack is a somewhat abstract datatype. The idea of "pushing" and "popping" are largely independent of how the stack is actually implemented. For example, you could theoretically implement a stack like this (although I don't know why you would):</p> <pre><code>l = [1,2,3] l.insert(0, 1) l.pop(0) </code></pre> <p>...and I haven't gotten into using linked lists to implement a stack.</p>
3
2009-10-14T13:46:01Z
[ "python" ]
Why is Python's "append" not "push"?
1,566,266
<p>Does anyone know why Python's <code>list.append</code> function is not called <code>list.push</code> given that there's already a <code>list.pop</code> that removes and returns the last element (that indexed at -1) and <code>list.append</code> semantic is consistent with that use?</p>
176
2009-10-14T13:34:26Z
1,569,007
<p>Because "append" existed long before "pop" was thought of. <a href="http://www.dalkescientific.com/writings/diary/archive/2009/03/27/python%5F0%5F9%5F1p1.html">Python 0.9.1</a> supported list.append in early 1991. By comparison, here's part of a <a href="http://groups.google.com/group/comp.lang.python/browse%5Fthread/thread/48a26add2d996268/57ab953cb73bc9c7?q=list+pop+group%3Acomp.lang.python+author%3Aguido#">discussion on comp.lang.python</a> about adding pop in 1997. Guido wrote:</p> <blockquote> <p>To implement a stack, one would need to add a list.pop() primitive (and no, I'm not against this particular one on the basis of any principle). list.push() could be added for symmetry with list.pop() but I'm not a big fan of multiple names for the same operation -- sooner or later you're going to read code that uses the other one, so you need to learn both, which is more cognitive load.</p> </blockquote> <p>You can also see he discusses the idea of if push/pop/put/pull should be at element [0] or after element [-1] where he posts a reference to Icon's list:</p> <blockquote> <p>I stil think that all this is best left out of the list object implementation -- if you need a stack, or a queue, with particular semantics, write a little class that uses a lists</p> </blockquote> <p>In other words, for stacks implemented directly as Python lists, which already supports fast append(), and del list[-1], it makes sense that list.pop() work by default on the last element. Even if other languages do it differently.</p> <p>Implicit here is that most people need to append to a list, but many fewer have occasion to treat lists as stacks, which is why list.append came in so much earlier.</p>
168
2009-10-14T21:07:43Z
[ "python" ]
Why is Python's "append" not "push"?
1,566,266
<p>Does anyone know why Python's <code>list.append</code> function is not called <code>list.push</code> given that there's already a <code>list.pop</code> that removes and returns the last element (that indexed at -1) and <code>list.append</code> semantic is consistent with that use?</p>
176
2009-10-14T13:34:26Z
4,752,493
<p>Push and Pop make sense in terms of the metaphor of a stack of plates or trays in a cafeteria or buffet, specifically the ones in type of holder that has a spring underneath so the top plate is (more or less... in theory) in the same place no matter how many plates are under it. </p> <p>If you remove a tray, the weight on the spring is a little less and the stack "pops" up a little, if you put the plate back, it "push"es the stack down. So if you think about the list as a stack and the last element as being on top, then you shouldn't have much confusion. </p>
-1
2011-01-20T20:56:08Z
[ "python" ]
Why is Python's "append" not "push"?
1,566,266
<p>Does anyone know why Python's <code>list.append</code> function is not called <code>list.push</code> given that there's already a <code>list.pop</code> that removes and returns the last element (that indexed at -1) and <code>list.append</code> semantic is consistent with that use?</p>
176
2009-10-14T13:34:26Z
9,857,541
<p>Probably because you can change it yourself easily if you don't like it...</p> <pre><code>stack = type('stack', (list, ), dict([(k,v) if k!='append' else ('push',v) \ for k,v in list.__dict__.items()])) </code></pre>
-2
2012-03-25T02:47:55Z
[ "python" ]
Python newbie - Understanding class functions
1,566,314
<p>If you take the following simple class:</p> <pre><code>class AltString: def __init__(self, str = "", size = 0): self._contents = str self._size = size self._list = [str] def append(self, str): self._list.append(str) def output(self): return "".join(self._list) </code></pre> <p>And I successfully invoke the class instance using:</p> <pre><code>as = AltString("String1") as.append("String2") as.append("String3") </code></pre> <p>When I then invoke the <code>output</code> function using <code>as.output</code> instead of a string being returned, I get the following instead: </p> <pre><code>unbound method AltString.output </code></pre> <p>if I call it using <code>as.output()</code> I get the following error:</p> <pre><code>TypeError: unbound method output() must be called with AltString instance as first argument (got nothing instead) </code></pre> <p>What I am not doing right?</p>
0
2009-10-14T13:42:19Z
1,566,336
<p><code>as</code> is a bad variable name, it is reserved keyword in Python. don't name your variables like this. once you fix it, everything else will be alright. of course you should be doing: </p> <pre><code>alt_str.output() </code></pre> <p><strong>edit</strong>: I was able to replicate your error messages when trying to apply <code>output</code> to the class: <code>AltString.output</code>, then: <code>AltString.output()</code>. You should be applying the method to the instance of the class instead.</p> <pre><code>alt_str = AltString('spam') alt_str.output() </code></pre>
8
2009-10-14T13:46:40Z
[ "python" ]
Python newbie - Understanding class functions
1,566,314
<p>If you take the following simple class:</p> <pre><code>class AltString: def __init__(self, str = "", size = 0): self._contents = str self._size = size self._list = [str] def append(self, str): self._list.append(str) def output(self): return "".join(self._list) </code></pre> <p>And I successfully invoke the class instance using:</p> <pre><code>as = AltString("String1") as.append("String2") as.append("String3") </code></pre> <p>When I then invoke the <code>output</code> function using <code>as.output</code> instead of a string being returned, I get the following instead: </p> <pre><code>unbound method AltString.output </code></pre> <p>if I call it using <code>as.output()</code> I get the following error:</p> <pre><code>TypeError: unbound method output() must be called with AltString instance as first argument (got nothing instead) </code></pre> <p>What I am not doing right?</p>
0
2009-10-14T13:42:19Z
1,566,344
<p>'as' and 'str' are keywords, don't shadow them by defining variables with the same name.</p>
1
2009-10-14T13:47:29Z
[ "python" ]
Python newbie - Understanding class functions
1,566,314
<p>If you take the following simple class:</p> <pre><code>class AltString: def __init__(self, str = "", size = 0): self._contents = str self._size = size self._list = [str] def append(self, str): self._list.append(str) def output(self): return "".join(self._list) </code></pre> <p>And I successfully invoke the class instance using:</p> <pre><code>as = AltString("String1") as.append("String2") as.append("String3") </code></pre> <p>When I then invoke the <code>output</code> function using <code>as.output</code> instead of a string being returned, I get the following instead: </p> <pre><code>unbound method AltString.output </code></pre> <p>if I call it using <code>as.output()</code> I get the following error:</p> <pre><code>TypeError: unbound method output() must be called with AltString instance as first argument (got nothing instead) </code></pre> <p>What I am not doing right?</p>
0
2009-10-14T13:42:19Z
1,566,361
<p>Your example is confirmed to work as you expect in python 2.4</p> <pre><code>&gt;&gt;&gt; from x import * &gt;&gt;&gt; as = AltString("String1") &gt;&gt;&gt; as.append("bubu") &gt;&gt;&gt; &gt;&gt;&gt; as.output() 'String1bubu' </code></pre> <p>In python 2.5 it should also work, but will raise a warning about the use of as, which will become a reserved keyword in python 2.6. </p> <p>I don't really understand why you obtain such error messages. If you are using python 2.6 it should probably produce a syntax error.</p>
1
2009-10-14T13:50:27Z
[ "python" ]
Python newbie - Understanding class functions
1,566,314
<p>If you take the following simple class:</p> <pre><code>class AltString: def __init__(self, str = "", size = 0): self._contents = str self._size = size self._list = [str] def append(self, str): self._list.append(str) def output(self): return "".join(self._list) </code></pre> <p>And I successfully invoke the class instance using:</p> <pre><code>as = AltString("String1") as.append("String2") as.append("String3") </code></pre> <p>When I then invoke the <code>output</code> function using <code>as.output</code> instead of a string being returned, I get the following instead: </p> <pre><code>unbound method AltString.output </code></pre> <p>if I call it using <code>as.output()</code> I get the following error:</p> <pre><code>TypeError: unbound method output() must be called with AltString instance as first argument (got nothing instead) </code></pre> <p>What I am not doing right?</p>
0
2009-10-14T13:42:19Z
1,566,368
<p>I ran the following code :</p> <pre><code>class AltString: def __init__(self, str = "", size = 0): self._contents = str self._size = size self._list = [str] def append(self, str): self._list.append(str) def output(self): return "".join(self._list) a = AltString("String1") a.append("String2") a.append("String3") print a.output() </code></pre> <p>And it worked perfectly. The only flow I can see is that you use "as", which is a reserved keyword.</p>
0
2009-10-14T13:52:12Z
[ "python" ]
Python newbie - Understanding class functions
1,566,314
<p>If you take the following simple class:</p> <pre><code>class AltString: def __init__(self, str = "", size = 0): self._contents = str self._size = size self._list = [str] def append(self, str): self._list.append(str) def output(self): return "".join(self._list) </code></pre> <p>And I successfully invoke the class instance using:</p> <pre><code>as = AltString("String1") as.append("String2") as.append("String3") </code></pre> <p>When I then invoke the <code>output</code> function using <code>as.output</code> instead of a string being returned, I get the following instead: </p> <pre><code>unbound method AltString.output </code></pre> <p>if I call it using <code>as.output()</code> I get the following error:</p> <pre><code>TypeError: unbound method output() must be called with AltString instance as first argument (got nothing instead) </code></pre> <p>What I am not doing right?</p>
0
2009-10-14T13:42:19Z
1,566,369
<p>Just tried your code in Python 2.6.2 and the line</p> <pre><code>as = AltString("String1") </code></pre> <p>doesn't work because "as" is a reserved keyword (see <a href="http://docs.python.org/reference/compound%5Fstmts.html#the-with-statement" rel="nofollow">here</a>) but if I use another name it works perfectly.</p>
0
2009-10-14T13:52:20Z
[ "python" ]
Should I keep my Python code at 2.x or migrate to 3.x if I plan to eventually use Jython?
1,566,411
<p>I have a large infrastructure that is written in Python 2.6, and I recently took a stab at porting to 3.1 (was much smoother than I expected) despite the lack of backwards compatibility.</p> <p>I eventually want to integrate some of this Python code with a lot of Java based code that we have, and was thinking about giving Jython a try. However, from looking at the Jython tutorials, all the examples are in 2.6 syntax (e.g., print is not yet a function).</p> <p>Does/will Jython support Python 3.x syntax at present or in the near future? Or should I roll back to 2.6 if I want to eventually use Jython?</p>
4
2009-10-14T14:00:13Z
1,566,453
<p>Jython will not support Python 3.x in the near future. For your code, I recommend to keep it in 2.x form, such that 3.x support becomes available by merely running 2to3 (i.e. with no further source changes). IOW, port to 3.x in a way so that the code remains compatible with 2.x.</p>
5
2009-10-14T14:05:38Z
[ "python", "jython" ]
Should I keep my Python code at 2.x or migrate to 3.x if I plan to eventually use Jython?
1,566,411
<p>I have a large infrastructure that is written in Python 2.6, and I recently took a stab at porting to 3.1 (was much smoother than I expected) despite the lack of backwards compatibility.</p> <p>I eventually want to integrate some of this Python code with a lot of Java based code that we have, and was thinking about giving Jython a try. However, from looking at the Jython tutorials, all the examples are in 2.6 syntax (e.g., print is not yet a function).</p> <p>Does/will Jython support Python 3.x syntax at present or in the near future? Or should I roll back to 2.6 if I want to eventually use Jython?</p>
4
2009-10-14T14:00:13Z
1,566,484
<p>I would expect that the developers will be working towards compatability with 3.0 at this point. Since they released 2.5 in june I'd hope for a 3.0 version no earlier than Jan.-Mar. 2010, but given their slow release cycle, it could be a while.</p>
0
2009-10-14T14:09:12Z
[ "python", "jython" ]
Should I keep my Python code at 2.x or migrate to 3.x if I plan to eventually use Jython?
1,566,411
<p>I have a large infrastructure that is written in Python 2.6, and I recently took a stab at porting to 3.1 (was much smoother than I expected) despite the lack of backwards compatibility.</p> <p>I eventually want to integrate some of this Python code with a lot of Java based code that we have, and was thinking about giving Jython a try. However, from looking at the Jython tutorials, all the examples are in 2.6 syntax (e.g., print is not yet a function).</p> <p>Does/will Jython support Python 3.x syntax at present or in the near future? Or should I roll back to 2.6 if I want to eventually use Jython?</p>
4
2009-10-14T14:00:13Z
1,567,742
<p>With time 2.x will be surpassed by the new features of his 3.x. If you wish to programming in Python in the future then "the sooner = the better"</p>
0
2009-10-14T17:19:12Z
[ "python", "jython" ]
Is there a dictionary that contains the function's parameters in Python?
1,566,878
<p>I'd like to be able to get a dictionary of all the parameters passed to a function.</p> <pre><code>def myfunc( param1, param2, param3 ): print 'Param1=%(param1)s, Param2=%(param2)s Param3=%(param3)' % __method_param_dict__ </code></pre> <p>So my question is does the dictionary <strong>method_param_dict</strong> exist, and if so what is it called.</p> <p>Thanks</p>
1
2009-10-14T14:59:48Z
1,566,909
<p>You can do:</p> <pre><code>def myfunc(*args, **kwargs): # Now "args" is a list containing the parameters passed print args[0], args[1], args[2] # And "kwargs" is a dictionary mapping the parameter names passed to their values for key, value in kwargs.items(): print key, value </code></pre>
1
2009-10-14T15:03:25Z
[ "python" ]
Is there a dictionary that contains the function's parameters in Python?
1,566,878
<p>I'd like to be able to get a dictionary of all the parameters passed to a function.</p> <pre><code>def myfunc( param1, param2, param3 ): print 'Param1=%(param1)s, Param2=%(param2)s Param3=%(param3)' % __method_param_dict__ </code></pre> <p>So my question is does the dictionary <strong>method_param_dict</strong> exist, and if so what is it called.</p> <p>Thanks</p>
1
2009-10-14T14:59:48Z
1,566,910
<p>If you need to do that, you should use <code>*args</code> and <code>**kwargs</code>.</p> <pre><code>def foo(*args, **kwargs): print args print kwargs foo(1,2,3,four=4,five=5) # prints [1,2,3] and {'four':4, 'five':5} </code></pre> <p>Using <code>locals()</code> is also a possibility and will allow you to iterate through the names of position arguments, but you must remember to access it before defining any new names in the scope, and you should be aware that it will include <code>self</code> for methods.</p>
3
2009-10-14T15:03:41Z
[ "python" ]
Is there a dictionary that contains the function's parameters in Python?
1,566,878
<p>I'd like to be able to get a dictionary of all the parameters passed to a function.</p> <pre><code>def myfunc( param1, param2, param3 ): print 'Param1=%(param1)s, Param2=%(param2)s Param3=%(param3)' % __method_param_dict__ </code></pre> <p>So my question is does the dictionary <strong>method_param_dict</strong> exist, and if so what is it called.</p> <p>Thanks</p>
1
2009-10-14T14:59:48Z
1,566,911
<p>A solution for your specific example:</p> <pre><code>def myfunc(param1, param2, param3): dict_param = locals() </code></pre> <p>But be sure to have a look at <a href="http://kbyanc.blogspot.com/2007/07/python-aggregating-function-arguments.html" rel="nofollow">this article</a> for a complete explanation of the possiblities (args, kwargs, mixed etc...)</p>
7
2009-10-14T15:03:53Z
[ "python" ]
Is there a dictionary that contains the function's parameters in Python?
1,566,878
<p>I'd like to be able to get a dictionary of all the parameters passed to a function.</p> <pre><code>def myfunc( param1, param2, param3 ): print 'Param1=%(param1)s, Param2=%(param2)s Param3=%(param3)' % __method_param_dict__ </code></pre> <p>So my question is does the dictionary <strong>method_param_dict</strong> exist, and if so what is it called.</p> <p>Thanks</p>
1
2009-10-14T14:59:48Z
1,566,920
<p>If you want to accept variable parameters, you can use <code>*args</code> and <code>**kwargs</code>. </p> <p><code>*args</code> is a list of all non-keyword parameters. <code>**kwargs</code> is a dictionary of all keyword parameters. So:</p> <pre><code>def myfunc(*args, **kwargs): if args: print args if kwargs: print kwargs &gt;&gt;&gt; myfunc('hello', 'goodbye') ('hello', 'goodbye') &gt;&gt;&gt; myfunc(param1='hello', param2='goodbye') {'param1': 'param2', 'param2': 'goodbye'} </code></pre>
0
2009-10-14T15:04:49Z
[ "python" ]
Easy pretty printing of floats in python?
1,566,936
<p>I have a list of floats. If I simply <code>print</code> it, it shows up like this:</p> <pre><code>[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] </code></pre> <p>I could use <code>print "%.2f"</code>, which would require a <code>for</code> loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)</p> <pre><code>&gt;&gt;&gt; import print_options &gt;&gt;&gt; print_options.set_float_precision(2) &gt;&gt;&gt; print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] [9.0, 0.05, 0.03, 0.01, 0.06, 0.08] </code></pre>
43
2009-10-14T15:07:38Z
1,566,957
<p>Note that you can also multiply a string like "%.2f" (example: "%.2f "*10).</p> <pre><code>&gt;&gt;&gt; print "%.2f "*len(yourlist) % tuple(yourlist) 2.00 33.00 4.42 0.31 </code></pre>
15
2009-10-14T15:10:43Z
[ "python", "printing", "formatting", "floating-point" ]
Easy pretty printing of floats in python?
1,566,936
<p>I have a list of floats. If I simply <code>print</code> it, it shows up like this:</p> <pre><code>[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] </code></pre> <p>I could use <code>print "%.2f"</code>, which would require a <code>for</code> loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)</p> <pre><code>&gt;&gt;&gt; import print_options &gt;&gt;&gt; print_options.set_float_precision(2) &gt;&gt;&gt; print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] [9.0, 0.05, 0.03, 0.01, 0.06, 0.08] </code></pre>
43
2009-10-14T15:07:38Z
1,566,964
<p>List comps are your friend.</p> <pre><code>print ", ".join("%.2f" % f for f in list_o_numbers) </code></pre> <p>Try it:</p> <pre><code>&gt;&gt;&gt; nums = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999] &gt;&gt;&gt; print ", ".join("%.2f" % f for f in nums) 9.00, 0.05, 0.03, 0.01 </code></pre>
1
2009-10-14T15:11:57Z
[ "python", "printing", "formatting", "floating-point" ]
Easy pretty printing of floats in python?
1,566,936
<p>I have a list of floats. If I simply <code>print</code> it, it shows up like this:</p> <pre><code>[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] </code></pre> <p>I could use <code>print "%.2f"</code>, which would require a <code>for</code> loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)</p> <pre><code>&gt;&gt;&gt; import print_options &gt;&gt;&gt; print_options.set_float_precision(2) &gt;&gt;&gt; print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] [9.0, 0.05, 0.03, 0.01, 0.06, 0.08] </code></pre>
43
2009-10-14T15:07:38Z
1,566,970
<p>You can do:</p> <pre><code>a = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] print ["%0.2f" % i for i in a] </code></pre>
36
2009-10-14T15:12:55Z
[ "python", "printing", "formatting", "floating-point" ]
Easy pretty printing of floats in python?
1,566,936
<p>I have a list of floats. If I simply <code>print</code> it, it shows up like this:</p> <pre><code>[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] </code></pre> <p>I could use <code>print "%.2f"</code>, which would require a <code>for</code> loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)</p> <pre><code>&gt;&gt;&gt; import print_options &gt;&gt;&gt; print_options.set_float_precision(2) &gt;&gt;&gt; print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] [9.0, 0.05, 0.03, 0.01, 0.06, 0.08] </code></pre>
43
2009-10-14T15:07:38Z
1,566,995
<p>I believe that Python 3.1 will print them nicer by default, without any code changing. But that is useless if you use any extensions that haven't been updated to work with Python 3.1</p>
4
2009-10-14T15:15:42Z
[ "python", "printing", "formatting", "floating-point" ]
Easy pretty printing of floats in python?
1,566,936
<p>I have a list of floats. If I simply <code>print</code> it, it shows up like this:</p> <pre><code>[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] </code></pre> <p>I could use <code>print "%.2f"</code>, which would require a <code>for</code> loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)</p> <pre><code>&gt;&gt;&gt; import print_options &gt;&gt;&gt; print_options.set_float_precision(2) &gt;&gt;&gt; print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] [9.0, 0.05, 0.03, 0.01, 0.06, 0.08] </code></pre>
43
2009-10-14T15:07:38Z
1,566,998
<p>I agree with SilentGhost's comment, the for loop isn't that bad. You can achieve what you want with:</p> <pre><code>l = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] for x in l: print "%0.2f" % (x) </code></pre>
-1
2009-10-14T15:16:18Z
[ "python", "printing", "formatting", "floating-point" ]
Easy pretty printing of floats in python?
1,566,936
<p>I have a list of floats. If I simply <code>print</code> it, it shows up like this:</p> <pre><code>[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] </code></pre> <p>I could use <code>print "%.2f"</code>, which would require a <code>for</code> loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)</p> <pre><code>&gt;&gt;&gt; import print_options &gt;&gt;&gt; print_options.set_float_precision(2) &gt;&gt;&gt; print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] [9.0, 0.05, 0.03, 0.01, 0.06, 0.08] </code></pre>
43
2009-10-14T15:07:38Z
1,567,031
<pre><code>print "[%s]"%", ".join(map(str,yourlist)) </code></pre> <p>This will avoid the rounding errors in the binary representation when printed, without introducing a fixed precision constraint (like formating with <code>"%.2f"</code>):</p> <pre><code>[9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.0793303] </code></pre>
6
2009-10-14T15:20:26Z
[ "python", "printing", "formatting", "floating-point" ]
Easy pretty printing of floats in python?
1,566,936
<p>I have a list of floats. If I simply <code>print</code> it, it shows up like this:</p> <pre><code>[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] </code></pre> <p>I could use <code>print "%.2f"</code>, which would require a <code>for</code> loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)</p> <pre><code>&gt;&gt;&gt; import print_options &gt;&gt;&gt; print_options.set_float_precision(2) &gt;&gt;&gt; print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] [9.0, 0.05, 0.03, 0.01, 0.06, 0.08] </code></pre>
43
2009-10-14T15:07:38Z
1,567,166
<p>As noone has added it, it should be noted that going forward from Python 2.6+ the recommended way to do <a href="http://docs.python.org/library/string.html#string-formatting">string formating</a> is with <a href="http://docs.python.org/library/string.html#string.Formatter.format"><code>format</code></a>, to get ready for Python 3+.</p> <pre><code>print ["{0:0.2f}".format(i) for i in a] </code></pre> <p><a href="http://www.python.org/dev/peps/pep-3101">The new</a> <a href="http://docs.python.org/library/string.html#format-string-syntax">string formating syntax</a> is not hard to use, and yet is quite powerfull.</p> <p>I though that may be <a href="http://docs.python.org/library/pprint.html"><code>pprint</code></a> could have something, but I haven't found anything.</p>
45
2009-10-14T15:41:43Z
[ "python", "printing", "formatting", "floating-point" ]
Easy pretty printing of floats in python?
1,566,936
<p>I have a list of floats. If I simply <code>print</code> it, it shows up like this:</p> <pre><code>[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] </code></pre> <p>I could use <code>print "%.2f"</code>, which would require a <code>for</code> loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)</p> <pre><code>&gt;&gt;&gt; import print_options &gt;&gt;&gt; print_options.set_float_precision(2) &gt;&gt;&gt; print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] [9.0, 0.05, 0.03, 0.01, 0.06, 0.08] </code></pre>
43
2009-10-14T15:07:38Z
1,567,378
<p>First, elements inside a collection print their repr. you should learn about <code>__repr__</code> and <code>__str__</code>.</p> <p>This is the difference between print repr(1.1) and print 1.1. Let's join all those strings instead of the representations:</p> <pre><code>numbers = [9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.07933] print "repr:", " ".join(repr(n) for n in numbers) print "str:", " ".join(str(n) for n in numbers) </code></pre>
2
2009-10-14T16:13:40Z
[ "python", "printing", "formatting", "floating-point" ]
Easy pretty printing of floats in python?
1,566,936
<p>I have a list of floats. If I simply <code>print</code> it, it shows up like this:</p> <pre><code>[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] </code></pre> <p>I could use <code>print "%.2f"</code>, which would require a <code>for</code> loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)</p> <pre><code>&gt;&gt;&gt; import print_options &gt;&gt;&gt; print_options.set_float_precision(2) &gt;&gt;&gt; print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] [9.0, 0.05, 0.03, 0.01, 0.06, 0.08] </code></pre>
43
2009-10-14T15:07:38Z
1,567,630
<p>A more permanent solution is to subclass <code>float</code>:</p> <pre><code>&gt;&gt;&gt; class prettyfloat(float): def __repr__(self): return "%0.2f" % self &gt;&gt;&gt; x [1.290192, 3.0002, 22.119199999999999, 3.4110999999999998] &gt;&gt;&gt; x = map(prettyfloat, x) &gt;&gt;&gt; x [1.29, 3.00, 22.12, 3.41] &gt;&gt;&gt; y = x[2] &gt;&gt;&gt; y 22.12 </code></pre> <p>The problem with subclassing <code>float</code> is that it breaks code that's explicitly looking for a variable's type. But so far as I can tell, that's the only problem with it. And a simple <code>x = map(float, x)</code> undoes the conversion to <code>prettyfloat</code>.</p> <p>Tragically, you can't just monkey-patch <code>float.__repr__</code>, because <code>float</code>'s immutable.</p> <p>If you don't want to subclass <code>float</code>, but don't mind defining a function, <code>map(f, x)</code> is a lot more concise than <code>[f(n) for n in x]</code></p>
44
2009-10-14T16:57:29Z
[ "python", "printing", "formatting", "floating-point" ]
Easy pretty printing of floats in python?
1,566,936
<p>I have a list of floats. If I simply <code>print</code> it, it shows up like this:</p> <pre><code>[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] </code></pre> <p>I could use <code>print "%.2f"</code>, which would require a <code>for</code> loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)</p> <pre><code>&gt;&gt;&gt; import print_options &gt;&gt;&gt; print_options.set_float_precision(2) &gt;&gt;&gt; print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] [9.0, 0.05, 0.03, 0.01, 0.06, 0.08] </code></pre>
43
2009-10-14T15:07:38Z
9,474,358
<p>I just ran into this problem while trying to use pprint to output a list of tuples of floats. Nested comprehensions might be a bad idea, but here's what I did:</p> <pre><code>tups = [ (12.0, 9.75, 23.54), (12.5, 2.6, 13.85), (14.77, 3.56, 23.23), (12.0, 5.5, 23.5) ] pprint([['{0:0.02f}'.format(num) for num in tup] for tup in tups]) </code></pre> <p>I used generator expressions at first, but pprint just repred the generator...</p>
2
2012-02-28T00:02:05Z
[ "python", "printing", "formatting", "floating-point" ]
Easy pretty printing of floats in python?
1,566,936
<p>I have a list of floats. If I simply <code>print</code> it, it shows up like this:</p> <pre><code>[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] </code></pre> <p>I could use <code>print "%.2f"</code>, which would require a <code>for</code> loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)</p> <pre><code>&gt;&gt;&gt; import print_options &gt;&gt;&gt; print_options.set_float_precision(2) &gt;&gt;&gt; print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] [9.0, 0.05, 0.03, 0.01, 0.06, 0.08] </code></pre>
43
2009-10-14T15:07:38Z
16,761,088
<p>You could use pandas. </p> <p>Here is an example with a list:</p> <pre><code>In: import pandas as P In: P.set_option('display.precision',3) In: L = [3.4534534, 2.1232131, 6.231212, 6.3423423, 9.342342423] In: P.Series(data=L) Out: 0 3.45 1 2.12 2 6.23 3 6.34 4 9.34 dtype: float64 </code></pre> <p>If you have a dict d, and you want its keys as rows:</p> <pre><code>In: d Out: {1: 0.453523, 2: 2.35423234234, 3: 3.423432432, 4: 4.132312312} In: P.DataFrame(index=d.keys(), data=d.values()) Out: 0 1 0.45 2 2.35 3 3.42 4 4.13 </code></pre> <p>And another way of giving dict to a DataFrame:</p> <pre><code>P.DataFrame.from_dict(d, orient='index') </code></pre>
3
2013-05-26T16:07:07Z
[ "python", "printing", "formatting", "floating-point" ]
Easy pretty printing of floats in python?
1,566,936
<p>I have a list of floats. If I simply <code>print</code> it, it shows up like this:</p> <pre><code>[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] </code></pre> <p>I could use <code>print "%.2f"</code>, which would require a <code>for</code> loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)</p> <pre><code>&gt;&gt;&gt; import print_options &gt;&gt;&gt; print_options.set_float_precision(2) &gt;&gt;&gt; print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] [9.0, 0.05, 0.03, 0.01, 0.06, 0.08] </code></pre>
43
2009-10-14T15:07:38Z
33,433,838
<p>I had this problem, but none of the solutions here did <em>exactly</em> what I wanted (I want the printed output to be a valid python expression), so how about this:</p> <pre><code>prettylist = lambda l : '[%s]' % ', '.join("%.2f" % f for f in l) </code></pre> <p>Usage:</p> <pre><code>&gt;&gt;&gt; ugly = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] &gt;&gt;&gt; prettylist = lambda l : '[%s]' % ', '.join("%.2f" % f for f in l) &gt;&gt;&gt; print prettylist(ugly) [9.00, 0.05, 0.03, 0.01, 0.06, 0.08] </code></pre> <p>(I know .format() is supposed to be the more standard solution, but I find this more readable)</p>
0
2015-10-30T10:29:59Z
[ "python", "printing", "formatting", "floating-point" ]
Easy pretty printing of floats in python?
1,566,936
<p>I have a list of floats. If I simply <code>print</code> it, it shows up like this:</p> <pre><code>[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] </code></pre> <p>I could use <code>print "%.2f"</code>, which would require a <code>for</code> loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)</p> <pre><code>&gt;&gt;&gt; import print_options &gt;&gt;&gt; print_options.set_float_precision(2) &gt;&gt;&gt; print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] [9.0, 0.05, 0.03, 0.01, 0.06, 0.08] </code></pre>
43
2009-10-14T15:07:38Z
34,882,846
<p>The code below works nice to me.</p> <pre><code>list = map (lambda x: float('%0.2f' % x), list) </code></pre>
0
2016-01-19T17:08:36Z
[ "python", "printing", "formatting", "floating-point" ]
Easy pretty printing of floats in python?
1,566,936
<p>I have a list of floats. If I simply <code>print</code> it, it shows up like this:</p> <pre><code>[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] </code></pre> <p>I could use <code>print "%.2f"</code>, which would require a <code>for</code> loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)</p> <pre><code>&gt;&gt;&gt; import print_options &gt;&gt;&gt; print_options.set_float_precision(2) &gt;&gt;&gt; print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] [9.0, 0.05, 0.03, 0.01, 0.06, 0.08] </code></pre>
43
2009-10-14T15:07:38Z
36,204,743
<pre><code>l = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006] </code></pre> <p>Python 2:</p> <pre><code>print ', '.join('{:0.2f}'.format(i) for i in l) </code></pre> <p>Python 3:</p> <pre><code>print(', '.join('{:0.2f}'.format(i) for i in l)) </code></pre> <p>Output:</p> <pre><code>9.00, 0.05, 0.03, 0.01, 0.06, 0.08 </code></pre>
1
2016-03-24T16:05:00Z
[ "python", "printing", "formatting", "floating-point" ]
validate xml against dtd using python on google app engine
1,566,951
<p>I've got validation working on client side using lxml, but I'm not quite sure how to get it work on google app engine, since it doesn't have the lxml package. I tried copying the whole lxml folder and place it in the root of my google application, but it seems like it cannot use it properly. I'm guessing it has to do with the compiled .so-files and such.</p> <p>Is there a way to get lxml to work on google app engine? If not, is there any other library that you can use to validate xml against dtd that works on google app engine?</p>
0
2009-10-14T15:09:43Z
1,567,515
<p>Compiled C extensions (like lxml) will not work on Google App Engine.</p> <p><a href="http://pyxml.sourceforge.net/topics/" rel="nofollow">PyXML</a> is no longer maintained, but it does have a pure-Python XML validator. See <a href="http://snipplr.com/view/3316/xml-dtd-validation-for-python/" rel="nofollow">this</a> code snippet for an example.</p>
1
2009-10-14T16:38:34Z
[ "python", "xml", "validation", "google-app-engine", "dtd" ]
Wrapping an interactive command line application in a python script
1,567,371
<p>I am interested in controlling an interactive CLI application from python calls.</p> <p>I guess at the most basic level I need a python script that will start a CLI application on the host OS. Pipe anything from stdin to the cli application, and then pipe any output from the cli application to stdout.</p> <p>From this base It should be pretty straightforward to do some processing on the input and output</p> <p>To be honest I probably just need a pointer on what the tecnique is called. I have no idea what I need to be searching for.</p>
12
2009-10-14T16:12:21Z
1,567,381
<p>Does <a href="http://sourceforge.net/projects/pexpect/" rel="nofollow">PExpect</a> fits your needs?</p>
2
2009-10-14T16:13:58Z
[ "python", "command-line" ]
Wrapping an interactive command line application in a python script
1,567,371
<p>I am interested in controlling an interactive CLI application from python calls.</p> <p>I guess at the most basic level I need a python script that will start a CLI application on the host OS. Pipe anything from stdin to the cli application, and then pipe any output from the cli application to stdout.</p> <p>From this base It should be pretty straightforward to do some processing on the input and output</p> <p>To be honest I probably just need a pointer on what the tecnique is called. I have no idea what I need to be searching for.</p>
12
2009-10-14T16:12:21Z
1,567,447
<p>Maybe you want something from <a href="http://docs.python.org/library/subprocess.html">Subprocess</a> (<a href="http://blog.doughellmann.com/2007/07/pymotw-subprocess.html">MOTW</a>).</p> <p>I use code like this to make calls out to the shell:</p> <pre><code>from subprocess import Popen, PIPE ## shell out, prompt def shell(args, input=''): ''' uses subprocess pipes to call out to the shell. args: args to the command input: stdin returns stdout, stderr ''' p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = p.communicate(input=input) return stdout, stderr </code></pre>
10
2009-10-14T16:29:12Z
[ "python", "command-line" ]
Why is BeautifulSoup modifying my self-closing elements?
1,567,402
<p>This is the script I have:</p> <pre><code>import BeautifulSoup if __name__ == "__main__": data = """ &lt;root&gt; &lt;obj id="3"/&gt; &lt;obj id="5"/&gt; &lt;obj id="3"/&gt; &lt;/root&gt; """ soup = BeautifulSoup.BeautifulStoneSoup(data) print soup </code></pre> <p>When ran, this prints:</p> <pre><code>&lt;root&gt; &lt;obj id="3"&gt;&lt;/obj&gt; &lt;obj id="5"&gt;&lt;/obj&gt; &lt;obj id="3"&gt;&lt;/obj&gt; &lt;/root&gt; </code></pre> <p>I'd like it to keep the same structure. How can I do that?</p>
2
2009-10-14T16:19:14Z
1,567,417
<p>From the <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing%20XML" rel="nofollow">Beautiful Soup documentation</a>:</p> <blockquote> <p>The most common shortcoming of <code>BeautifulStoneSoup</code> is that it doesn't know about self-closing tags. HTML has a fixed set of self-closing tags, but with XML it depends on what the DTD says. You can tell <code>BeautifulStoneSoup</code> that certain tags are self-closing by passing in their names as the <code>selfClosingTags</code> argument to the constructor</p> </blockquote>
7
2009-10-14T16:22:13Z
[ "python", "xml", "beautifulsoup" ]
Buildout and Virtualenv
1,567,494
<p>I am messing around with the combination of buildout and virtualenv to setup an <em>isolated</em> development environment in python that allows to do reproducible builds.</p> <p>There is a recipe for buildout that let's you integrate virtualenv into buildout:</p> <pre><code> tl.buildout_virtual_python </code></pre> <p>With this my buildout.cfg looks like this:</p> <pre><code>[buildout] develop = . parts = script virtualpython [virtualpython] recipe = tl.buildout_virtual_python headers = true executable-name = vp site-packages = false [script] recipe = zc.recipe.egg:scripts eggs = foo python = virtualpython </code></pre> <p>This will deploy two executables into ./bin/:</p> <pre><code>vp script </code></pre> <p>When I execute vp, I get an interactive, isolated python dialog, as expected (can't load any packages from the system). What I would expect now, is that if I run </p> <pre><code>./bin/script </code></pre> <p>that the isolated python interpreter is used. But it doesn't, it's not isolated as "vp" is (meaning I can import libraries from system level). However I can run:</p> <pre><code>./bin/vp ./bin/script </code></pre> <p>Which will run the script in an isolated environment as I wished. But there must be a way to specify this to do so without chaining commands otherwise buildout only solves half of the problems I hoped :)</p> <p>Thanks for your help! Patrick</p>
12
2009-10-14T16:35:42Z
1,567,620
<p>I've never used that recipe before, but the first thing I would try is this:</p> <pre><code>[buildout] develop = . parts = script virtualpython [virtualpython] recipe = tl.buildout_virtual_python headers = true executable-name = vp site-packages = false [script] recipe = zc.recipe.egg:scripts eggs = foo python = virtualpython interpreter = vp </code></pre> <p>If that doesn't work, you can usually open up the scripts (in this case vp and script) in a text editor and see the Python paths that they're using. If you're on windows there will usually be a file called <code>&lt;script_name&gt;-script.py</code>. In this case, that would be vp-script.py and script-script.py.</p>
0
2009-10-14T16:56:28Z
[ "python", "virtualenv", "buildout" ]
Buildout and Virtualenv
1,567,494
<p>I am messing around with the combination of buildout and virtualenv to setup an <em>isolated</em> development environment in python that allows to do reproducible builds.</p> <p>There is a recipe for buildout that let's you integrate virtualenv into buildout:</p> <pre><code> tl.buildout_virtual_python </code></pre> <p>With this my buildout.cfg looks like this:</p> <pre><code>[buildout] develop = . parts = script virtualpython [virtualpython] recipe = tl.buildout_virtual_python headers = true executable-name = vp site-packages = false [script] recipe = zc.recipe.egg:scripts eggs = foo python = virtualpython </code></pre> <p>This will deploy two executables into ./bin/:</p> <pre><code>vp script </code></pre> <p>When I execute vp, I get an interactive, isolated python dialog, as expected (can't load any packages from the system). What I would expect now, is that if I run </p> <pre><code>./bin/script </code></pre> <p>that the isolated python interpreter is used. But it doesn't, it's not isolated as "vp" is (meaning I can import libraries from system level). However I can run:</p> <pre><code>./bin/vp ./bin/script </code></pre> <p>Which will run the script in an isolated environment as I wished. But there must be a way to specify this to do so without chaining commands otherwise buildout only solves half of the problems I hoped :)</p> <p>Thanks for your help! Patrick</p>
12
2009-10-14T16:35:42Z
1,842,685
<p>You don't need virtualenv: buildout already provides an isolated environment, just like virtualenv.</p> <p>As an example, look at files buildout generates in the bin directory. They'll have something like:</p> <pre><code>import sys sys.path[0:0] = [ '/some/thing1.egg', # and other things ] </code></pre> <p>So the <code>sys.path</code> gets completely replaced with what buildout wants to have on the path: the same isolation method as virtualenv.</p>
8
2009-12-03T20:28:31Z
[ "python", "virtualenv", "buildout" ]
Buildout and Virtualenv
1,567,494
<p>I am messing around with the combination of buildout and virtualenv to setup an <em>isolated</em> development environment in python that allows to do reproducible builds.</p> <p>There is a recipe for buildout that let's you integrate virtualenv into buildout:</p> <pre><code> tl.buildout_virtual_python </code></pre> <p>With this my buildout.cfg looks like this:</p> <pre><code>[buildout] develop = . parts = script virtualpython [virtualpython] recipe = tl.buildout_virtual_python headers = true executable-name = vp site-packages = false [script] recipe = zc.recipe.egg:scripts eggs = foo python = virtualpython </code></pre> <p>This will deploy two executables into ./bin/:</p> <pre><code>vp script </code></pre> <p>When I execute vp, I get an interactive, isolated python dialog, as expected (can't load any packages from the system). What I would expect now, is that if I run </p> <pre><code>./bin/script </code></pre> <p>that the isolated python interpreter is used. But it doesn't, it's not isolated as "vp" is (meaning I can import libraries from system level). However I can run:</p> <pre><code>./bin/vp ./bin/script </code></pre> <p>Which will run the script in an isolated environment as I wished. But there must be a way to specify this to do so without chaining commands otherwise buildout only solves half of the problems I hoped :)</p> <p>Thanks for your help! Patrick</p>
12
2009-10-14T16:35:42Z
11,530,360
<p>Had issue running buildout using bootstrap on ubuntu server, from then I use virtualenv and buildout together. Simply create virualenv and install buildout in it. This way only virtualenv has to be installed into system (in theory<sup>1</sup>).</p> <pre><code>$ virtualenv [options_you_might_need] virtual $ source virtual/bin/activate $ pip install zc.buildout $ buildout -c &lt;buildout.cfg&gt; </code></pre> <p>Also tell buildout to put its scripts in to virtual/bin/ directory, that way scripts appear on <code>$PATH</code>.</p> <pre><code>[buildout] bin-directory = ${buildout:directory}/virtual/bin ... </code></pre> <hr> <p>1: In practice you probably will need to eggs what require compilation to system level that require compilation. Eggs like mysql or memcache.</p>
3
2012-07-17T20:26:01Z
[ "python", "virtualenv", "buildout" ]
Buildout and Virtualenv
1,567,494
<p>I am messing around with the combination of buildout and virtualenv to setup an <em>isolated</em> development environment in python that allows to do reproducible builds.</p> <p>There is a recipe for buildout that let's you integrate virtualenv into buildout:</p> <pre><code> tl.buildout_virtual_python </code></pre> <p>With this my buildout.cfg looks like this:</p> <pre><code>[buildout] develop = . parts = script virtualpython [virtualpython] recipe = tl.buildout_virtual_python headers = true executable-name = vp site-packages = false [script] recipe = zc.recipe.egg:scripts eggs = foo python = virtualpython </code></pre> <p>This will deploy two executables into ./bin/:</p> <pre><code>vp script </code></pre> <p>When I execute vp, I get an interactive, isolated python dialog, as expected (can't load any packages from the system). What I would expect now, is that if I run </p> <pre><code>./bin/script </code></pre> <p>that the isolated python interpreter is used. But it doesn't, it's not isolated as "vp" is (meaning I can import libraries from system level). However I can run:</p> <pre><code>./bin/vp ./bin/script </code></pre> <p>Which will run the script in an isolated environment as I wished. But there must be a way to specify this to do so without chaining commands otherwise buildout only solves half of the problems I hoped :)</p> <p>Thanks for your help! Patrick</p>
12
2009-10-14T16:35:42Z
19,562,106
<p><strong>zc.buildout 2.0</strong> and later <strong>does not provide the isolated environment anymore</strong>. </p> <p>But <strong>virtualenv 1.9</strong> and later provides complete isolation (including to not install setuptools). </p> <p>Thus the easiest way to get a buildout in a complete controlled environment is to run the following steps (here i.e for widely used Python 2.7):</p> <pre><code>cd /path/to/buildout rm ./bin/python /path/to/virtualenv-2.7 --no-setuptools --no-site-packages --clear . ./bin/python2.7 bootstrap.py ./bin/buildout </code></pre> <p>Preconditions:</p> <ul> <li><p><code>bootstrap.py</code> has to be a recent one matching the buildput version you are using. You'll find the latest at <a href="http://downloads.buildout.org/2/" rel="nofollow">http://downloads.buildout.org/2/</a></p></li> <li><p>if there are any version pins in your buildout, ensure they do not pin buildout itself or recipes/ extensions to versions not compatible with zc.buildout 2 or later.</p></li> </ul>
3
2013-10-24T09:30:35Z
[ "python", "virtualenv", "buildout" ]
finding substring
1,567,607
<p>Thanks in advance. I have a string:</p> <pre><code>A = 'asdfghjklmn' </code></pre> <p>How can I get a substring having a maximum length which is a multiple of three?</p>
0
2009-10-14T16:53:59Z
1,567,645
<p>Is this what you want?</p> <pre><code>A = 'asdfghjklmn' A[0:(len(A)/3)*3] 'asdfghjkl' </code></pre>
0
2009-10-14T17:00:24Z
[ "python" ]
finding substring
1,567,607
<p>Thanks in advance. I have a string:</p> <pre><code>A = 'asdfghjklmn' </code></pre> <p>How can I get a substring having a maximum length which is a multiple of three?</p>
0
2009-10-14T16:53:59Z
1,567,658
<p>It seems like you're looking for something like this:</p> <pre><code>&gt;&gt;&gt; A = 'asdfghjklmn' &gt;&gt;&gt; mult, _ = divmod(len(A), 3) &gt;&gt;&gt; A[:mult*3] 'asdfghjkl' </code></pre> <p>here resulting string will have length which is multiple of three and it will be the longest possible substring of <code>A</code> with such length.</p>
1
2009-10-14T17:02:33Z
[ "python" ]
finding substring
1,567,607
<p>Thanks in advance. I have a string:</p> <pre><code>A = 'asdfghjklmn' </code></pre> <p>How can I get a substring having a maximum length which is a multiple of three?</p>
0
2009-10-14T16:53:59Z
1,567,664
<p>You can use <a href="http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation">slice notation</a> and integer arithmetic.</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; a = 'asdfghjklmn' &gt;&gt;&gt; a[:len(a)//3*3] 'asdfghjkl' &gt;&gt;&gt; len(a) 11 &gt;&gt;&gt; len(a[:len(a)//3*3]) 9 </code></pre> <p>In general, <code>n//k*k</code> will yield the largest multiple of <em>k</em> less than or equal to <em>n</em>.</p>
4
2009-10-14T17:03:47Z
[ "python" ]
finding substring
1,567,607
<p>Thanks in advance. I have a string:</p> <pre><code>A = 'asdfghjklmn' </code></pre> <p>How can I get a substring having a maximum length which is a multiple of three?</p>
0
2009-10-14T16:53:59Z
1,567,674
<p>Yet another example:</p> <pre><code>&gt;&gt;&gt; A = '12345678' &gt;&gt;&gt; A[:len(A) - len(A)%3] '123456' &gt;&gt;&gt; </code></pre>
1
2009-10-14T17:06:13Z
[ "python" ]
finding substring
1,567,607
<p>Thanks in advance. I have a string:</p> <pre><code>A = 'asdfghjklmn' </code></pre> <p>How can I get a substring having a maximum length which is a multiple of three?</p>
0
2009-10-14T16:53:59Z
1,567,710
<p>With the foreword that it will never be as efficient as the ones that actually use <em>math</em> to find the longest multiple-of-3-substring, here's a way to do it using regular expressions:</p> <pre><code>&gt;&gt;&gt; re.findall("^(?:.{3})*", "asdfghjklmn")[0] 'asdfghjkl' </code></pre> <p>Changing the <code>3</code> quantifier will allow you to get different multiples.</p>
0
2009-10-14T17:12:16Z
[ "python" ]
deleting an object in a loop that runs through the range of the list?
1,567,669
<p>I have a list composed of [start position, stop position, [sample names with those positions]]</p> <p>My goal is to remove the duplicates with exact start and stop positions and just add the extra sample to the sample names section. The problem I'm encountering is that when I delete from the list, I end up with an out of range error, because it's not recalculating the <code>len(list)</code> within the loops. </p> <pre><code>for g in range (len(list)) : for n in range(len(list)): #compares the start and stop position of one line to the start and stop of another line if (list[g][0]==list[n+1][0] and list[g][1]==[n+1][1]) #adds new sample numbers to first start and stop entry with duplication labels1=list[g][2] labels2=list[n+1][2] labels=labels1+labels2 list[g][2]=labels #now delete the extra line del list[n+1] </code></pre>
1
2009-10-14T17:05:32Z
1,567,739
<p>I not sure I understand what you want, but it might be this:</p> <pre><code>from collections import defaultdict d = defaultdict(list) for start, stop, samples in L1: d[start, stop].extend(samples) L2 = [[start, stop, samples] for (start, stop), samples in d.items()] </code></pre> <p>Which will take L1:</p> <pre><code>L1 = [ [1, 5, ["a", "b", "c"]], [3, 4, ["d", "e"]], [1, 5, ["f"]] ] </code></pre> <p>and make L2:</p> <pre><code>L2 = [ [1, 5, ["a", "b", "c", "f"]], [3, 4, ["d", "e"]] ] </code></pre> <p>Please note that this does not guarantee the same order of the elements in L2 as in L1, but from the looks of your question, that doesn't matter.</p>
3
2009-10-14T17:18:34Z
[ "python", "list", "for-loop" ]
deleting an object in a loop that runs through the range of the list?
1,567,669
<p>I have a list composed of [start position, stop position, [sample names with those positions]]</p> <p>My goal is to remove the duplicates with exact start and stop positions and just add the extra sample to the sample names section. The problem I'm encountering is that when I delete from the list, I end up with an out of range error, because it's not recalculating the <code>len(list)</code> within the loops. </p> <pre><code>for g in range (len(list)) : for n in range(len(list)): #compares the start and stop position of one line to the start and stop of another line if (list[g][0]==list[n+1][0] and list[g][1]==[n+1][1]) #adds new sample numbers to first start and stop entry with duplication labels1=list[g][2] labels2=list[n+1][2] labels=labels1+labels2 list[g][2]=labels #now delete the extra line del list[n+1] </code></pre>
1
2009-10-14T17:05:32Z
1,567,753
<p>Your loops should not be for loops, they should be while loop with an increment step. I guess you can just manually check the condition within your for loop (<code>continue</code> if it's not met), but a while loop makes more sense, imo.</p>
2
2009-10-14T17:21:22Z
[ "python", "list", "for-loop" ]
deleting an object in a loop that runs through the range of the list?
1,567,669
<p>I have a list composed of [start position, stop position, [sample names with those positions]]</p> <p>My goal is to remove the duplicates with exact start and stop positions and just add the extra sample to the sample names section. The problem I'm encountering is that when I delete from the list, I end up with an out of range error, because it's not recalculating the <code>len(list)</code> within the loops. </p> <pre><code>for g in range (len(list)) : for n in range(len(list)): #compares the start and stop position of one line to the start and stop of another line if (list[g][0]==list[n+1][0] and list[g][1]==[n+1][1]) #adds new sample numbers to first start and stop entry with duplication labels1=list[g][2] labels2=list[n+1][2] labels=labels1+labels2 list[g][2]=labels #now delete the extra line del list[n+1] </code></pre>
1
2009-10-14T17:05:32Z
1,567,787
<p>I've just put together a nice little list comprehension that does pretty much what you did, except without the nasty <code>del</code> s.</p> <pre><code>from functools import reduce from operator import add from itertools import groupby data = [ [1, 1, [2, 3, 4]], [1, 1, [5, 7, 8]], [1, 3, [2, 8, 5]], [2, 3, [1, 7, 9]], [2, 3, [3, 8, 5]], ] data.sort() print( [[key[0], key[1], reduce(add, (i[2] for i in iterator))] for key, iterator in groupby(data, lambda item: item[:2]) ] ) </code></pre>
0
2009-10-14T17:27:02Z
[ "python", "list", "for-loop" ]
deleting an object in a loop that runs through the range of the list?
1,567,669
<p>I have a list composed of [start position, stop position, [sample names with those positions]]</p> <p>My goal is to remove the duplicates with exact start and stop positions and just add the extra sample to the sample names section. The problem I'm encountering is that when I delete from the list, I end up with an out of range error, because it's not recalculating the <code>len(list)</code> within the loops. </p> <pre><code>for g in range (len(list)) : for n in range(len(list)): #compares the start and stop position of one line to the start and stop of another line if (list[g][0]==list[n+1][0] and list[g][1]==[n+1][1]) #adds new sample numbers to first start and stop entry with duplication labels1=list[g][2] labels2=list[n+1][2] labels=labels1+labels2 list[g][2]=labels #now delete the extra line del list[n+1] </code></pre>
1
2009-10-14T17:05:32Z
1,568,197
<p>Here is truppo's answer, re-written to preserve the order of entries from L1. It has a few other small changes, such as using a plain dict instead of a defaultdict, and using explicit tuples instead of packing and unpacking them on the fly.</p> <pre><code>L1 = [ [1, 5, ["a", "b", "c"]], [3, 4, ["d", "e"]], [1, 5, ["f"]] ] d = {} oplist = [] # order-preserving list for start, stop, samples in L1: tup = (start, stop) # make a tuple out of start/stop pair if tup in d: d[tup].extend(samples) else: d[tup] = samples oplist.append(tup) L2 = [[tup[0], tup[1], d[tup]] for tup in oplist] print L2 # prints: [[1, 5, ['a', 'b', 'c', 'f']], [3, 4, ['d', 'e']]] </code></pre>
1
2009-10-14T18:39:30Z
[ "python", "list", "for-loop" ]
Writing a class that accepts a callback in Python?
1,567,777
<p>I need to write a class that allows a subclass to set an attribute with the name of a function. That function must then be callable from instances of the class.</p> <p>For example, I say I need to write a Fruit class where the subclass can pass in a welcome message. The Fruit class must expose an attribute print_callback that can be set. </p> <pre><code>class Fruit(object): print_callback = None def __init__(self, *args, **kwargs): super(Fruit, self).__init__(*args, **kwargs) self.print_callback("Message from Fruit: ") </code></pre> <p>I need to expose an API that is can be consumed by this code (to be clear, this code cannot change, say it is 3rd party code):</p> <pre><code>def apple_print(f): print "%sI am an Apple!" % f class Apple(Fruit): print_callback = apple_print </code></pre> <p>If I run:</p> <pre><code>mac = Apple() </code></pre> <p>I want to get:</p> <blockquote> <p>Message from Fruit: I am an Apple!</p> </blockquote> <p>Instead I get:</p> <blockquote> <p>TypeError: apple_print() takes exactly 1 argument (2 given)</p> </blockquote> <p>I think this is because self is passed in as the first argument.</p> <p>So how do I write the Fruit class? Thanks!</p>
6
2009-10-14T17:25:39Z
1,567,820
<p>Python assumes that any functions bound within a class scope are methods. If you'd like to treat them as functions, you have to dig around in their attributes to retrieve the original function object:</p> <pre><code>def __init__(self, *args, **kwargs): super(Fruit, self).__init__(*args, **kwargs) # The attribute name was changed in Python 3; pick whichever line matches # your Python version. callback = self.print_callback.im_func # Python 2 callback = self.print_callback.__func__ # Python 3 callback("Message from Fruit: ") </code></pre>
6
2009-10-14T17:35:12Z
[ "python", "callback" ]
Writing a class that accepts a callback in Python?
1,567,777
<p>I need to write a class that allows a subclass to set an attribute with the name of a function. That function must then be callable from instances of the class.</p> <p>For example, I say I need to write a Fruit class where the subclass can pass in a welcome message. The Fruit class must expose an attribute print_callback that can be set. </p> <pre><code>class Fruit(object): print_callback = None def __init__(self, *args, **kwargs): super(Fruit, self).__init__(*args, **kwargs) self.print_callback("Message from Fruit: ") </code></pre> <p>I need to expose an API that is can be consumed by this code (to be clear, this code cannot change, say it is 3rd party code):</p> <pre><code>def apple_print(f): print "%sI am an Apple!" % f class Apple(Fruit): print_callback = apple_print </code></pre> <p>If I run:</p> <pre><code>mac = Apple() </code></pre> <p>I want to get:</p> <blockquote> <p>Message from Fruit: I am an Apple!</p> </blockquote> <p>Instead I get:</p> <blockquote> <p>TypeError: apple_print() takes exactly 1 argument (2 given)</p> </blockquote> <p>I think this is because self is passed in as the first argument.</p> <p>So how do I write the Fruit class? Thanks!</p>
6
2009-10-14T17:25:39Z
1,567,963
<p><strong>Updated</strong>: incorporating <a href="http://stackoverflow.com/questions/1567777/writing-a-class-that-accepts-a-callback-in-python/1568198#1568198">abourget's suggestion</a> to use <code>staticmethod</code>:</p> <p>Try this:</p> <pre><code>def __init__(self, *args, **kwargs): super(Fruit, self).__init__(*args, **kwargs) # Wrap function back into a proper static method self.print_callback = staticmethod(self.print_callback) # And now you can do: self.print_callback("Message from Fruit: ") </code></pre>
2
2009-10-14T17:57:31Z
[ "python", "callback" ]
Writing a class that accepts a callback in Python?
1,567,777
<p>I need to write a class that allows a subclass to set an attribute with the name of a function. That function must then be callable from instances of the class.</p> <p>For example, I say I need to write a Fruit class where the subclass can pass in a welcome message. The Fruit class must expose an attribute print_callback that can be set. </p> <pre><code>class Fruit(object): print_callback = None def __init__(self, *args, **kwargs): super(Fruit, self).__init__(*args, **kwargs) self.print_callback("Message from Fruit: ") </code></pre> <p>I need to expose an API that is can be consumed by this code (to be clear, this code cannot change, say it is 3rd party code):</p> <pre><code>def apple_print(f): print "%sI am an Apple!" % f class Apple(Fruit): print_callback = apple_print </code></pre> <p>If I run:</p> <pre><code>mac = Apple() </code></pre> <p>I want to get:</p> <blockquote> <p>Message from Fruit: I am an Apple!</p> </blockquote> <p>Instead I get:</p> <blockquote> <p>TypeError: apple_print() takes exactly 1 argument (2 given)</p> </blockquote> <p>I think this is because self is passed in as the first argument.</p> <p>So how do I write the Fruit class? Thanks!</p>
6
2009-10-14T17:25:39Z
1,568,198
<p>You can use directly:</p> <pre><code>class Apple(Fruit): print_callback = staticmethod(apple_print) </code></pre> <p>or:</p> <pre><code>class Apple(Fruit): print_callback = classmethod(apple_print) </code></pre> <p>In the first case, you'll get only one parameter (the original). In the second, you'll receive two parameters where the first will be the class on which it was called.</p> <p>Hope this helps, and is shorter and less complex.</p>
3
2009-10-14T18:40:09Z
[ "python", "callback" ]
Writing a class that accepts a callback in Python?
1,567,777
<p>I need to write a class that allows a subclass to set an attribute with the name of a function. That function must then be callable from instances of the class.</p> <p>For example, I say I need to write a Fruit class where the subclass can pass in a welcome message. The Fruit class must expose an attribute print_callback that can be set. </p> <pre><code>class Fruit(object): print_callback = None def __init__(self, *args, **kwargs): super(Fruit, self).__init__(*args, **kwargs) self.print_callback("Message from Fruit: ") </code></pre> <p>I need to expose an API that is can be consumed by this code (to be clear, this code cannot change, say it is 3rd party code):</p> <pre><code>def apple_print(f): print "%sI am an Apple!" % f class Apple(Fruit): print_callback = apple_print </code></pre> <p>If I run:</p> <pre><code>mac = Apple() </code></pre> <p>I want to get:</p> <blockquote> <p>Message from Fruit: I am an Apple!</p> </blockquote> <p>Instead I get:</p> <blockquote> <p>TypeError: apple_print() takes exactly 1 argument (2 given)</p> </blockquote> <p>I think this is because self is passed in as the first argument.</p> <p>So how do I write the Fruit class? Thanks!</p>
6
2009-10-14T17:25:39Z
1,569,028
<p>There's also a bit dirtyer solution with metaclasses:</p> <pre><code>def apple_print(f): print "Apple " + f class FruitMeta(type): def __new__(cls, name, bases, dct): func = dct["print_callback"] dct["print_callback"]=lambda x,f,func=func: func(f) return type.__new__(cls,name,bases,dct) class Fruit(object): __metaclass__ = FruitMeta print_callback = None def __init__(self): super(Fruit,self).__init__() self.print_callback("Msg ") class Apple(Fruit): print_callback = apple_print mac = Apple()here </code></pre> <p>It manipulates the class before its creation!</p>
0
2009-10-14T21:10:52Z
[ "python", "callback" ]
Writing a class that accepts a callback in Python?
1,567,777
<p>I need to write a class that allows a subclass to set an attribute with the name of a function. That function must then be callable from instances of the class.</p> <p>For example, I say I need to write a Fruit class where the subclass can pass in a welcome message. The Fruit class must expose an attribute print_callback that can be set. </p> <pre><code>class Fruit(object): print_callback = None def __init__(self, *args, **kwargs): super(Fruit, self).__init__(*args, **kwargs) self.print_callback("Message from Fruit: ") </code></pre> <p>I need to expose an API that is can be consumed by this code (to be clear, this code cannot change, say it is 3rd party code):</p> <pre><code>def apple_print(f): print "%sI am an Apple!" % f class Apple(Fruit): print_callback = apple_print </code></pre> <p>If I run:</p> <pre><code>mac = Apple() </code></pre> <p>I want to get:</p> <blockquote> <p>Message from Fruit: I am an Apple!</p> </blockquote> <p>Instead I get:</p> <blockquote> <p>TypeError: apple_print() takes exactly 1 argument (2 given)</p> </blockquote> <p>I think this is because self is passed in as the first argument.</p> <p>So how do I write the Fruit class? Thanks!</p>
6
2009-10-14T17:25:39Z
21,103,505
<p>I was looking for something more like this when I found this question: </p> <pre><code>class Something: def my_callback(self, arg_a): print arg_a class SomethingElse: def __init__(self, callback): self.callback = callback something = Something() something_else = SomethingElse(something.my_callback) something_else.callback("It works...") </code></pre>
1
2014-01-13T23:36:36Z
[ "python", "callback" ]
How can I view a text representation of an lxml element?
1,567,903
<p>If I'm parsing an XML document using lxml, is it possible to view a text representation of an element? I tried to do :</p> <pre><code>print repr(node) </code></pre> <p>but this outputs </p> <pre><code>&lt;Element obj at b743c0&gt; </code></pre> <p>What can I use to see the node like it exists in the XML file? Is there some <code>to_xml</code> method or something?</p>
6
2009-10-14T17:48:03Z
1,567,932
<p>From <a href="http://lxml.de/tutorial.html#serialisation">http://lxml.de/tutorial.html#serialisation</a></p> <pre><code>&gt;&gt;&gt; root = etree.XML('&lt;root&gt;&lt;a&gt;&lt;b/&gt;&lt;/a&gt;&lt;/root&gt;') &gt;&gt;&gt; etree.tostring(root) b'&lt;root&gt;&lt;a&gt;&lt;b/&gt;&lt;/a&gt;&lt;/root&gt;' &gt;&gt;&gt; print(etree.tostring(root, xml_declaration=True)) &lt;?xml version='1.0' encoding='ASCII'?&gt; &lt;root&gt;&lt;a&gt;&lt;b/&gt;&lt;/a&gt;&lt;/root&gt; &gt;&gt;&gt; print(etree.tostring(root, encoding='iso-8859-1')) &lt;?xml version='1.0' encoding='iso-8859-1'?&gt; &lt;root&gt;&lt;a&gt;&lt;b/&gt;&lt;/a&gt;&lt;/root&gt; &gt;&gt;&gt; print(etree.tostring(root, pretty_print=True)) &lt;root&gt; &lt;a&gt; &lt;b/&gt; &lt;/a&gt; &lt;/root&gt; </code></pre>
15
2009-10-14T17:52:03Z
[ "python", "xml", "lxml" ]
Django: How do I make fields non-editable by default in an inline model formset?
1,568,058
<p>I have an inline model formset, and I'd like to make fields non-editable if those fields already have values when the page is loaded. If the user clicks an "Edit" button on that row, it would become editable and (using JavaScript) I would replace the original widgets with editable ones. I'd like to do something like this when loading the page:</p> <pre><code>for field in form.fields: if field.value: # display as text else: # display as my standard editable widget for this field </code></pre> <p>I see that <code>inlineformset_factory</code> has an argument called <code>formfield_callback</code>. I suspect that this could be useful, but so for I haven't found any documentation for it. Can anyone point me to some useful documentation for this, and how it can help me solve this problem?</p>
4
2009-10-14T18:13:19Z
1,568,238
<p>I think you might be able to override the init function of your form that is used in a formset. There you could check for initial_data, and dynamically build your forms like you're hoping to do. At least, it sounds plausible in my head.</p>
0
2009-10-14T18:50:04Z
[ "python", "django", "django-forms" ]
Django: How do I make fields non-editable by default in an inline model formset?
1,568,058
<p>I have an inline model formset, and I'd like to make fields non-editable if those fields already have values when the page is loaded. If the user clicks an "Edit" button on that row, it would become editable and (using JavaScript) I would replace the original widgets with editable ones. I'd like to do something like this when loading the page:</p> <pre><code>for field in form.fields: if field.value: # display as text else: # display as my standard editable widget for this field </code></pre> <p>I see that <code>inlineformset_factory</code> has an argument called <code>formfield_callback</code>. I suspect that this could be useful, but so for I haven't found any documentation for it. Can anyone point me to some useful documentation for this, and how it can help me solve this problem?</p>
4
2009-10-14T18:13:19Z
1,571,112
<p>I had a question where I wanted to "<a href="http://stackoverflow.com/questions/1409192/auto-generate-form-fields-for-a-form-in-django">Auto-generate form fields</a>", can found a solution for dynamically creating forms, it may help:</p> <p><a href="http://stackoverflow.com/questions/1409192/auto-generate-form-fields-for-a-form-in-django">http://stackoverflow.com/questions/1409192/auto-generate-form-fields-for-a-form-in-django</a></p> <p>It's not clean and there's probably a better way to handle this. </p> <p>How about just sending the data as editable (normal formset) from django and do the value check with javascript, using javascript to toggle the widgets?</p>
0
2009-10-15T08:49:33Z
[ "python", "django", "django-forms" ]
Django: How do I make fields non-editable by default in an inline model formset?
1,568,058
<p>I have an inline model formset, and I'd like to make fields non-editable if those fields already have values when the page is loaded. If the user clicks an "Edit" button on that row, it would become editable and (using JavaScript) I would replace the original widgets with editable ones. I'd like to do something like this when loading the page:</p> <pre><code>for field in form.fields: if field.value: # display as text else: # display as my standard editable widget for this field </code></pre> <p>I see that <code>inlineformset_factory</code> has an argument called <code>formfield_callback</code>. I suspect that this could be useful, but so for I haven't found any documentation for it. Can anyone point me to some useful documentation for this, and how it can help me solve this problem?</p>
4
2009-10-14T18:13:19Z
2,242,468
<p>This one stumped me for a bit too. Hopefully this is what you're looking for.</p> <pre><code>&lt;TABLE&gt; &lt;form method="post" action="."&gt; {{ formset.management_form }} {% for form in formset.forms %} {{ form.id }} &lt;tr&gt; &lt;td&gt;{{ form.FirstName }}&lt;/td&gt; &lt;!-- This is a normal, editable field --&gt; &lt;td&gt;{{ form.instance.LastName }}&lt;/td&gt; &lt;!-- 'instance' is your actual Django model. LastName displays the text from the last name field --&gt; &lt;/tr&gt; {% endfor %} &lt;/form&gt; &lt;/TABLE&gt; </code></pre>
12
2010-02-11T05:26:45Z
[ "python", "django", "django-forms" ]
Django: How do I make fields non-editable by default in an inline model formset?
1,568,058
<p>I have an inline model formset, and I'd like to make fields non-editable if those fields already have values when the page is loaded. If the user clicks an "Edit" button on that row, it would become editable and (using JavaScript) I would replace the original widgets with editable ones. I'd like to do something like this when loading the page:</p> <pre><code>for field in form.fields: if field.value: # display as text else: # display as my standard editable widget for this field </code></pre> <p>I see that <code>inlineformset_factory</code> has an argument called <code>formfield_callback</code>. I suspect that this could be useful, but so for I haven't found any documentation for it. Can anyone point me to some useful documentation for this, and how it can help me solve this problem?</p>
4
2009-10-14T18:13:19Z
3,605,849
<p>This thread is a bit old, but for anyone looking:</p> <p>in the form:</p> <pre><code>myfield=forms.CharField( widget=forms.TextInput(attrs={'class':'disabled', 'readonly':'readonly'})) </code></pre> <p>The "readonly" is an HTML attribute that makes the form uneditable. "disabled" is a CSS class as you'll want to modify the default styling, also it makes the jQuery simpler.</p> <p>To make readonly inputs editable when clicked, here's a jQuery example:</p> <pre><code>$('input.disabled').click(function(){ $(this).removeAttr('readonly').removeClass('disabled'); }); </code></pre>
6
2010-08-31T03:39:12Z
[ "python", "django", "django-forms" ]
Given a Python class, how can I inspect and find the place in my code where it is defined?
1,568,544
<p>I'm building a debugging tool.</p> <p>IPython lets me do stuff like</p> <pre><code>MyCls?? </code></pre> <p>And it will show me the source.</p>
5
2009-10-14T19:46:32Z
1,568,569
<p>Here's a pretty good overview of many of Python's meta-info capabilities:</p> <p><a href="http://www.ibm.com/developerworks/library/l-pyint.html" rel="nofollow">http://www.ibm.com/developerworks/library/l-pyint.html</a></p>
4
2009-10-14T19:50:52Z
[ "python" ]
Given a Python class, how can I inspect and find the place in my code where it is defined?
1,568,544
<p>I'm building a debugging tool.</p> <p>IPython lets me do stuff like</p> <pre><code>MyCls?? </code></pre> <p>And it will show me the source.</p>
5
2009-10-14T19:46:32Z
1,568,650
<pre><code>sys.modules[MyCls.__module__].__file__ </code></pre> <p>or</p> <pre><code>inspect.getsourcefile(MyCls) </code></pre> <p>There are more <a href="http://docs.python.org/library/inspect.html#types-and-members" rel="nofollow"><code>__xxx__</code> attributes</a> on various objects you might find useful.</p>
8
2009-10-14T20:04:27Z
[ "python" ]
Given a Python class, how can I inspect and find the place in my code where it is defined?
1,568,544
<p>I'm building a debugging tool.</p> <p>IPython lets me do stuff like</p> <pre><code>MyCls?? </code></pre> <p>And it will show me the source.</p>
5
2009-10-14T19:46:32Z
1,569,050
<p>The <a href="http://docs.python.org/library/inspect" rel="nofollow">inspect</a> module has everything you need.</p>
2
2009-10-14T21:15:51Z
[ "python" ]
Given a Python class, how can I inspect and find the place in my code where it is defined?
1,568,544
<p>I'm building a debugging tool.</p> <p>IPython lets me do stuff like</p> <pre><code>MyCls?? </code></pre> <p>And it will show me the source.</p>
5
2009-10-14T19:46:32Z
1,574,161
<p>If you just want to see the source, <a href="http://docs.python.org/library/inspect.html#inspect.getsource" rel="nofollow">inspect.getsource</a> is a very direct way to do that; for more advanced uses (getting the source <em>file</em>, line numbers, etc), see other functions in <code>inspect</code> documented at the same URL just before <code>getsource</code>. Note that each such function will raise an exception if source is not available, so make sure to be within a <code>try</code>/<code>except</code> block when you call it, and handle the exception as appropriate for your case. (Also, as I might hope goes without saying, you do need to <code>import inspect</code> in your modules in which you want to call <code>inspect</code> functionality).</p>
2
2009-10-15T18:20:59Z
[ "python" ]
Library to read a MySQL dump?
1,568,838
<p>I am looking for a library that will allow me to read a mysql dump.</p> <p>I don't want to have to create a MySQL database and import the library and use the MySQL API. I would prefer simply a library that can parse the mysql dump format.</p> <p>I prefer a python library, but other scripting languages are okay.</p>
9
2009-10-14T20:37:33Z
1,569,092
<p>I came across <a href="http://gnosis.cx/download/pywikipedia/sqldump.py" rel="nofollow">sqldump.py</a> while looking for something similar - might be of use...</p>
1
2009-10-14T21:24:17Z
[ "python", "mysql", "api", "mysqldump" ]
Library to read a MySQL dump?
1,568,838
<p>I am looking for a library that will allow me to read a mysql dump.</p> <p>I don't want to have to create a MySQL database and import the library and use the MySQL API. I would prefer simply a library that can parse the mysql dump format.</p> <p>I prefer a python library, but other scripting languages are okay.</p>
9
2009-10-14T20:37:33Z
1,569,669
<p><p>Import into MySQL and dump using --xml seems to be the best option.</P></p> <p><p>I wrote up the reasoning in this blog post: <a href="http://blog.metaoptimize.com/2009/10/14/use-flag-xml-when-you-run-mysqldump/">Use flag –xml when you run mysqldump</a></P></p>
5
2009-10-15T00:16:51Z
[ "python", "mysql", "api", "mysqldump" ]
How do I convert RFC822 to a python datetime object?
1,568,856
<p>I know how to do this the other way around... it would be:</p> <pre><code>&gt;&gt;&gt; dt.rfc822() 'Sun, 09 Mar 1997 13:45:00 -0500' </code></pre>
16
2009-10-14T20:39:39Z
1,568,882
<pre><code> In [1]: import rfc822 # This only works for python 2 series In [2]: rfc822.parsedate_tz('Sun, 09 Mar 1997 13:45:00 -0500') Out[2]: (1997, 3, 9, 13, 45, 0, 0, 1, 0, -18000) </code></pre> <p>in python3 parsedate_tz has moved to email.utils</p> <pre><code> >>> import email.utils # this works on Python2.5 and up >>> email.utils.parsedate_tz('Sun, 09 Mar 1997 13:45:00 -0500') (1997, 3, 9, 13, 45, 0, 0, 1, -1, -18000) </code></pre>
28
2009-10-14T20:43:57Z
[ "python", "rfc822" ]
How do I convert RFC822 to a python datetime object?
1,568,856
<p>I know how to do this the other way around... it would be:</p> <pre><code>&gt;&gt;&gt; dt.rfc822() 'Sun, 09 Mar 1997 13:45:00 -0500' </code></pre>
16
2009-10-14T20:39:39Z
1,568,910
<p>If you strip off the time zone, you can do it like this:</p> <pre><code>datetime.datetime.strptime('Sun, 09 Mar 1997 13:45:00', '%a, %d %b %Y %H:%M:%S') </code></pre>
0
2009-10-14T20:48:32Z
[ "python", "rfc822" ]
Making Python's `assert` throw an exception that I choose
1,569,049
<p>Can I make <code>assert</code> throw an exception that I choose instead of <code>AssertionError</code>?</p> <p><strong>UPDATE:</strong></p> <p>I'll explain my motivation: Up to now, I've had assertion-style tests that raised my own exceptions; For example, when you created a <code>Node</code> object with certain arguments, it would check if the arguments were good for creating a node, and if not it would raise <code>NodeError</code>.</p> <p>But I know that Python has a <code>-o</code> mode in which asserts are skipped, which I would like to have available because it would make my program faster. But I would still like to have my own exceptions. That's why I want to use assert with my own exceptions.</p>
20
2009-10-14T21:15:43Z
1,569,074
<p>This will work. But it's kind of crazy.</p> <pre><code>try: assert False, "A Message" except AssertionError, e: raise Exception( e.args ) </code></pre> <p>Why not the following? This is less crazy.</p> <pre><code>if not someAssertion: raise Exception( "Some Message" ) </code></pre> <p>It's only a little wordier than the <code>assert</code> statement, but doesn't violate our expectation that assert failures raise <code>AssertionError</code>.</p> <p>Consider this.</p> <pre><code>def myAssert( condition, action ): if not condition: raise action </code></pre> <p>Then you can more-or-less replace your existing assertions with something like this.</p> <pre><code>myAssert( {{ the original condition }}, MyException( {{ the original message }} ) ) </code></pre> <p>Once you've done this, you are now free to fuss around with enable or disabling or whatever it is you're trying to do.</p> <p>Also, read up on the <a href="http://docs.python.org/library/warnings.html">warnings</a> module. This may be exactly what you're trying to do.</p>
29
2009-10-14T21:19:18Z
[ "python", "exception", "assert" ]
Making Python's `assert` throw an exception that I choose
1,569,049
<p>Can I make <code>assert</code> throw an exception that I choose instead of <code>AssertionError</code>?</p> <p><strong>UPDATE:</strong></p> <p>I'll explain my motivation: Up to now, I've had assertion-style tests that raised my own exceptions; For example, when you created a <code>Node</code> object with certain arguments, it would check if the arguments were good for creating a node, and if not it would raise <code>NodeError</code>.</p> <p>But I know that Python has a <code>-o</code> mode in which asserts are skipped, which I would like to have available because it would make my program faster. But I would still like to have my own exceptions. That's why I want to use assert with my own exceptions.</p>
20
2009-10-14T21:15:43Z
1,569,110
<p>In Python 2.6.3 at least, this will also work:</p> <pre><code>class MyAssertionError (Exception): pass AssertionError = MyAssertionError assert False, "False" </code></pre> <p><hr /></p> <pre><code>Traceback (most recent call last): File "assert.py", line 8, in &lt;module&gt; assert False, "False" __main__.MyAssertionError: False </code></pre>
4
2009-10-14T21:28:12Z
[ "python", "exception", "assert" ]
Making Python's `assert` throw an exception that I choose
1,569,049
<p>Can I make <code>assert</code> throw an exception that I choose instead of <code>AssertionError</code>?</p> <p><strong>UPDATE:</strong></p> <p>I'll explain my motivation: Up to now, I've had assertion-style tests that raised my own exceptions; For example, when you created a <code>Node</code> object with certain arguments, it would check if the arguments were good for creating a node, and if not it would raise <code>NodeError</code>.</p> <p>But I know that Python has a <code>-o</code> mode in which asserts are skipped, which I would like to have available because it would make my program faster. But I would still like to have my own exceptions. That's why I want to use assert with my own exceptions.</p>
20
2009-10-14T21:15:43Z
1,569,237
<p>How about this?</p> <pre><code> >>> def myraise(e): raise e ... >>> cond=False >>> assert cond or myraise(RuntimeError) Traceback (most recent call last): File "", line 1, in File "", line 1, in myraise RuntimeError </code></pre>
13
2009-10-14T21:55:25Z
[ "python", "exception", "assert" ]
Making Python's `assert` throw an exception that I choose
1,569,049
<p>Can I make <code>assert</code> throw an exception that I choose instead of <code>AssertionError</code>?</p> <p><strong>UPDATE:</strong></p> <p>I'll explain my motivation: Up to now, I've had assertion-style tests that raised my own exceptions; For example, when you created a <code>Node</code> object with certain arguments, it would check if the arguments were good for creating a node, and if not it would raise <code>NodeError</code>.</p> <p>But I know that Python has a <code>-o</code> mode in which asserts are skipped, which I would like to have available because it would make my program faster. But I would still like to have my own exceptions. That's why I want to use assert with my own exceptions.</p>
20
2009-10-14T21:15:43Z
1,569,563
<p>You can let a <a href="http://docs.python.org/reference/datamodel.html#context-managers" rel="nofollow">context manager</a> do the conversion for you, inside a with block (which may contain more than one assertion, or more code and function calls or what you want.</p> <pre><code>from __future__ import with_statement import contextlib @contextlib.contextmanager def myassert(exctype): try: yield except AssertionError, exc: raise exctype(*exc.args) with myassert(ValueError): assert 0, "Zero is bad for you" </code></pre> <p>See a previous version of this answer for substituting constructed exception objects directly (<code>KeyError("bad key")</code>), instead of reusing the assertions' argument(s).</p>
1
2009-10-14T23:30:21Z
[ "python", "exception", "assert" ]
Making Python's `assert` throw an exception that I choose
1,569,049
<p>Can I make <code>assert</code> throw an exception that I choose instead of <code>AssertionError</code>?</p> <p><strong>UPDATE:</strong></p> <p>I'll explain my motivation: Up to now, I've had assertion-style tests that raised my own exceptions; For example, when you created a <code>Node</code> object with certain arguments, it would check if the arguments were good for creating a node, and if not it would raise <code>NodeError</code>.</p> <p>But I know that Python has a <code>-o</code> mode in which asserts are skipped, which I would like to have available because it would make my program faster. But I would still like to have my own exceptions. That's why I want to use assert with my own exceptions.</p>
20
2009-10-14T21:15:43Z
1,569,579
<p>Never use an assertion for logic! Only for optional testing checks. Remember, if Python is running with optimizations turned on, asserts aren't even compiled into the bytecode. If you're doing this, you obviously care about the exception being raised and if you care, then you're using asserts wrong in the first place.</p>
2
2009-10-14T23:36:48Z
[ "python", "exception", "assert" ]
Making Python's `assert` throw an exception that I choose
1,569,049
<p>Can I make <code>assert</code> throw an exception that I choose instead of <code>AssertionError</code>?</p> <p><strong>UPDATE:</strong></p> <p>I'll explain my motivation: Up to now, I've had assertion-style tests that raised my own exceptions; For example, when you created a <code>Node</code> object with certain arguments, it would check if the arguments were good for creating a node, and if not it would raise <code>NodeError</code>.</p> <p>But I know that Python has a <code>-o</code> mode in which asserts are skipped, which I would like to have available because it would make my program faster. But I would still like to have my own exceptions. That's why I want to use assert with my own exceptions.</p>
20
2009-10-14T21:15:43Z
1,569,618
<p>To see if try has any overhead I tried this experiment</p> <p>here is myassert.py <pre><code> def myassert(e): raise e</p> <p>def f1(): #this is the control for the experiment cond=True</p> <p>def f2(): cond=True try: assert cond, "Message" except AssertionError, e: raise Exception(e.args)</p> <p>def f3(): cond=True assert cond or myassert(RuntimeError)</p> <p>def f4(): cond=True if &#95;&#95;debug&#95;&#95;: raise(RuntimeError)</p> <p></pre></code></p> <p><pre><code> $ python -O -mtimeit -n100 -r1000 -s'import myassert' 'myassert.f1()' 100 loops, best of 1000: 0.42 usec per loop $ python -O -mtimeit -n100 -r1000 -s'import myassert' 'myassert.f2()' 100 loops, best of 1000: 0.479 usec per loop $ python -O -mtimeit -n100 -r1000 -s'import myassert' 'myassert.f3()' 100 loops, best of 1000: 0.42 usec per loop $ python -O -mtimeit -n100 -r1000 -s'import myassert' 'myassert.f4()' 100 loops, best of 1000: 0.42 usec per loop </pre></code></p>
3
2009-10-14T23:53:15Z
[ "python", "exception", "assert" ]
Making Python's `assert` throw an exception that I choose
1,569,049
<p>Can I make <code>assert</code> throw an exception that I choose instead of <code>AssertionError</code>?</p> <p><strong>UPDATE:</strong></p> <p>I'll explain my motivation: Up to now, I've had assertion-style tests that raised my own exceptions; For example, when you created a <code>Node</code> object with certain arguments, it would check if the arguments were good for creating a node, and if not it would raise <code>NodeError</code>.</p> <p>But I know that Python has a <code>-o</code> mode in which asserts are skipped, which I would like to have available because it would make my program faster. But I would still like to have my own exceptions. That's why I want to use assert with my own exceptions.</p>
20
2009-10-14T21:15:43Z
1,570,223
<p>Python also skips <code>if __debug__:</code> blocks when run with <code>-o</code> option. The following code is more verbose, but does what you need without hacks:</p> <pre><code>def my_assert(condition, message=None): if not condition: raise MyAssertError(message) if __debug__: my_assert(condition, message) </code></pre> <p>You can make it shorter by moving <code>if __debug__:</code> condition inside <code>my_assert()</code>, but then it will be called (without any action inside) when optimization is enabled.</p>
6
2009-10-15T04:01:48Z
[ "python", "exception", "assert" ]
Python's libxml2 can't parse unicode strings
1,569,076
<p>OK, the docs for Python's libxml2 bindings are really <code>****</code>. My problem:</p> <p>An XML document is stored in a string variable in Python. The string is a instance of Unicode, and there are non-ASCII characters in it. I want to parse it with libxml2, looking something like this:</p> <pre><code># -*- coding: utf-8 -*- import libxml2 DOC = u"""&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;data&gt; &lt;something&gt;Bäääh!&lt;/something&gt; &lt;/data&gt; """ xml_doc = libxml2.parseDoc(DOC) </code></pre> <p>with this result:</p> <pre><code>Traceback (most recent call last): File "test.py", line 13, in &lt;module&gt; xml_doc = libxml2.parseDoc(DOC) File "c:\Python26\lib\site-packages\libxml2.py", line 1237, in parseDoc ret = libxml2mod.xmlParseDoc(cur) UnicodeEncodeError: 'ascii' codec can't encode characters in position 46-48: ordinal not in range(128) </code></pre> <p>The point is the <code>u"..."</code> declaration. If I replace it with a simple <code>".."</code>, then everything is ok. Unfortunately it doesn't work in my setup, because <code>DOC</code> will definitely be a Unicode instance.</p> <p>Has anyone an idea how libxml2 can be brought to parse UTF-8 encoded strings?</p>
2
2009-10-14T21:20:08Z
1,569,137
<p>XML is a binary format, despite of looking like a text. An encoding is specified in the beginning of the XML file in order to decode the XML bytes into the text.</p> <p>What you should do is to pass <code>str</code>, not <code>unicode</code> to your library:</p> <pre><code>xml_doc = libxml2.parseDoc(DOC.encode("UTF-8")) </code></pre> <p>(Although some tricks are possible with <code>site.setencoding</code> if you are interested in reading or writing <code>unicode</code> strings with automatic conversion via <code>locale</code>.)</p> <p><strong>Edit:</strong> <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow">The Unicode article</a> by Joel Spolsky is good guide to string characters vs. bytes, encodings, etc.</p>
6
2009-10-14T21:34:46Z
[ "python", "xml", "unicode", "libxml2" ]
Python's libxml2 can't parse unicode strings
1,569,076
<p>OK, the docs for Python's libxml2 bindings are really <code>****</code>. My problem:</p> <p>An XML document is stored in a string variable in Python. The string is a instance of Unicode, and there are non-ASCII characters in it. I want to parse it with libxml2, looking something like this:</p> <pre><code># -*- coding: utf-8 -*- import libxml2 DOC = u"""&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;data&gt; &lt;something&gt;Bäääh!&lt;/something&gt; &lt;/data&gt; """ xml_doc = libxml2.parseDoc(DOC) </code></pre> <p>with this result:</p> <pre><code>Traceback (most recent call last): File "test.py", line 13, in &lt;module&gt; xml_doc = libxml2.parseDoc(DOC) File "c:\Python26\lib\site-packages\libxml2.py", line 1237, in parseDoc ret = libxml2mod.xmlParseDoc(cur) UnicodeEncodeError: 'ascii' codec can't encode characters in position 46-48: ordinal not in range(128) </code></pre> <p>The point is the <code>u"..."</code> declaration. If I replace it with a simple <code>".."</code>, then everything is ok. Unfortunately it doesn't work in my setup, because <code>DOC</code> will definitely be a Unicode instance.</p> <p>Has anyone an idea how libxml2 can be brought to parse UTF-8 encoded strings?</p>
2
2009-10-14T21:20:08Z
1,569,140
<p>It should be</p> <pre><code># -*- coding: utf-8 -*- import libxml2 DOC = u"""&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;data&gt; &lt;something&gt;Bäääh!&lt;/something&gt; &lt;/data&gt; """.encode("UTF-8") xml_doc = libxml2.parseDoc(DOC) </code></pre> <p>The .encode("UTF-8") is needed to get the binary representation of the unicode string with the utf8 encoding.</p>
9
2009-10-14T21:35:10Z
[ "python", "xml", "unicode", "libxml2" ]
Inserting two related objects fail in SQLAlchemy
1,569,112
<p>I'm getting the (probably trivial) error, but completely clueless about the possible causes. I want to insert two object in the DB using SQLAlchemy. Those objects are related, here are the declarations. Class User:</p> <pre><code>class User(Base): __tablename__ = 'cp_user' id = Column(Integer, Sequence('id_seq'), primary_key=True) # ... more properties </code></pre> <p>Class Picture (user may have many of them):</p> <pre><code>class Picture(Base): __tablename__ = 'picture' id = Column(Integer, Sequence('id_seq'), primary_key=True) authorId = Column('author_id', Integer, ForeignKey('cp_user.id')) author = relation(User, primaryjoin = authorId == User.id) # ... more properties </code></pre> <p>I'm trying to insert the new picture after I've fetched the right user from the DB, or just created it:</p> <pre><code>s = newSession() user = s.query(User.name).filter("...some filter here...").first() if not(user): user = User() s.add(user) s.commit() picture = Picture() picture.author = user s.add(picture) s.commit() </code></pre> <p>This fails with the exception: <code>AttributeError: 'RowTuple' object has no attribute '_sa_instance_state'</code></p> <p>I tried moving assignment of the author to the constructor -- same error. I can't assign IDs directly -- this breaks the idea of ORM.</p> <p>What do I do wrong?</p>
3
2009-10-14T21:28:43Z
1,569,263
<p>Your code fails if the <code>not(user)</code> branch is not taken.</p> <p>You query User.name which is a column and not a bound object.</p> <pre><code>user = s.query(User).filter("...some filter here...").first() </code></pre> <p>An object gets it's id designed as soon as it is transmitted to the database. You are doing this in the branch with a commit. This is probably not what you want. You should issue a flush. Read the docs on the difference.</p> <p>Also you should not need to commit the newly created user. If you assign a user object to a relation, this should be handled transparently. Every commit closes a transaction, which can be quite costly (locking, disk seeks, etc)</p>
5
2009-10-14T22:01:28Z
[ "python", "sql", "orm", "sqlalchemy" ]
Python/PyQT QString won't insert into MySQL database
1,569,161
<p>I am trying to trying to retrieve some values from a user using a QLineEdit widget. When a QPushButton raises a clicked event, I want the text to be retrieved from all QLineEdit widgets and stored in a local MySQL databaase. However, when I try to use string substition in the insert statement, the values don't get substituted. Here's my sql statement:</p> <pre><code>sql = 'INSERT INTO jobs (incident_id, organization, organization_poc, media_type) VALUES ("%s", "%s", "%s", "%s")' % (self.edi_IncidentID.text(), self.edi_OrganizationAffected.text(), self.edi_OrganizationContact.text(), self.edi_MediaType.text()) </code></pre> <p>All of the self.edi_xxx variables are just QLineEdit widgets. When a button is pushed, the following is fired:</p> <pre><code>self.connect(btn_Submit, QtCore.SIGNAL('clicked()'), self.submitForm) </code></pre> <p>All submit does is create a database object and write the values to the database. However, for debugging I print out the constructed SQL statement and this comes out: INSERT INTO jobs (incident_id, organization, organization_poc, media_type) VALUES ("", "", "", "").</p> <p>I have also tried using the str() function to convert a QString to a string but the same thing happens.</p> <p>Any help would be greatly appreciated :)?</p> <p>L</p> <p>EDIT: Here is the complete code minus the imports:</p> <pre><code>class Database(): def __init__(self): self.db_host = "localhost" self.db_user = "***********" self.db_pass = "***********" self.db_name = "incidents" def openConn(self): self.db = MySQLdb.connect(self.db_host, self.db_user, self.db_pass, self.db_name) def closeConn(self): self.db.close() def writeValues(self, sql): self.openConn() self.cursor = self.db.cursor() self.cursor.execute(sql) self.cursor.fetchone() self.closeConn() class NewIncidentForm(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('New Incident') lbl_IncidentID = QtGui.QLabel('Incident ID:') lbl_MediaType = QtGui.QLabel('Media Type:') lbl_OrganizationAffected = QtGui.QLabel('Organization Affected:') lbl_OrganizationContact = QtGui.QLabel('Organization Point of Contact: ') self.edi_IncidentID = QtGui.QLineEdit() self.edi_MediaType = QtGui.QLineEdit() self.edi_OrganizationAffected = QtGui.QLineEdit() self.edi_OrganizationContact = QtGui.QLineEdit() btn_Submit = QtGui.QPushButton('Submit') grid = QtGui.QGridLayout() grid.setSpacing(10) grid.addWidget(lbl_IncidentID, 1, 0) grid.addWidget(self.edi_IncidentID, 1, 1) grid.addWidget(lbl_MediaType, 3, 0) grid.addWidget(self.edi_MediaType, 3, 1) grid.addWidget(lbl_OrganizationAffected, 4, 0) grid.addWidget(self.edi_OrganizationAffected, 4, 1) grid.addWidget(lbl_OrganizationContact, 5, 0) grid.addWidget(self.edi_OrganizationContact, 5, 1) grid.addWidget(btn_Submit, 15, 0) self.sql = 'INSERT INTO jobs (incident_id, organization, organization_poc, media_type) VALUES ("%s", "%s", "%s", "%s")' % (self.edi_IncidentID.text(), self.edi_OrganizationAffected.text(), self.edi_OrganizationContact.text(), self.edi_MediaType.text()) self.connect(btn_Submit, QtCore.SIGNAL('clicked()'), self.submitForm) self.setLayout(grid) self.resize(350, 300) def submitForm(self): db = Database() db.writeValues(self.sql) app = QtGui.QApplication(sys.argv) qb = NewIncidentForm() qb.show() sys.exit(app.exec_()) </code></pre>
1
2009-10-14T21:39:07Z
1,813,523
<p>:D QString have <code>__str__</code> functions so try this:</p> <pre><code>self.sql = 'INSERT INTO jobs (incident_id, organization, organization_poc, media_type) VALUES ("%s", "%s", "%s", "%s")' % (''.join(self.edi_IncidentID.text()), ''.join(self.edi_OrganizationAffected.text()), ''.join(self.edi_OrganizationContact.text()), ''.join(self.edi_MediaType.text())) </code></pre> <p>added <code>''.join()</code></p> <p>Or QString have toUtf8()</p> <p>so change <code>self.edi_IncidentIS.text()</code> to:</p> <pre><code>self.edi_IncidentIS.text().toUtf8() </code></pre> <p>Whole instruction:</p> <pre><code>self.sql = 'INSERT INTO jobs (incident_id, organization, organization_poc, media_type) VALUES ("%s", "%s", "%s", "%s")' % (self.edi_IncidentID.text().toUtf8(), self.edi_OrganizationAffected.text().toUtf8(), self.edi_OrganizationContact.text().toUtf8(), self.edi_MediaType.text().toUtf8()) </code></pre>
1
2009-11-28T19:31:35Z
[ "python", "mysql", "pyqt4", "qstring" ]
Python/PyQT QString won't insert into MySQL database
1,569,161
<p>I am trying to trying to retrieve some values from a user using a QLineEdit widget. When a QPushButton raises a clicked event, I want the text to be retrieved from all QLineEdit widgets and stored in a local MySQL databaase. However, when I try to use string substition in the insert statement, the values don't get substituted. Here's my sql statement:</p> <pre><code>sql = 'INSERT INTO jobs (incident_id, organization, organization_poc, media_type) VALUES ("%s", "%s", "%s", "%s")' % (self.edi_IncidentID.text(), self.edi_OrganizationAffected.text(), self.edi_OrganizationContact.text(), self.edi_MediaType.text()) </code></pre> <p>All of the self.edi_xxx variables are just QLineEdit widgets. When a button is pushed, the following is fired:</p> <pre><code>self.connect(btn_Submit, QtCore.SIGNAL('clicked()'), self.submitForm) </code></pre> <p>All submit does is create a database object and write the values to the database. However, for debugging I print out the constructed SQL statement and this comes out: INSERT INTO jobs (incident_id, organization, organization_poc, media_type) VALUES ("", "", "", "").</p> <p>I have also tried using the str() function to convert a QString to a string but the same thing happens.</p> <p>Any help would be greatly appreciated :)?</p> <p>L</p> <p>EDIT: Here is the complete code minus the imports:</p> <pre><code>class Database(): def __init__(self): self.db_host = "localhost" self.db_user = "***********" self.db_pass = "***********" self.db_name = "incidents" def openConn(self): self.db = MySQLdb.connect(self.db_host, self.db_user, self.db_pass, self.db_name) def closeConn(self): self.db.close() def writeValues(self, sql): self.openConn() self.cursor = self.db.cursor() self.cursor.execute(sql) self.cursor.fetchone() self.closeConn() class NewIncidentForm(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('New Incident') lbl_IncidentID = QtGui.QLabel('Incident ID:') lbl_MediaType = QtGui.QLabel('Media Type:') lbl_OrganizationAffected = QtGui.QLabel('Organization Affected:') lbl_OrganizationContact = QtGui.QLabel('Organization Point of Contact: ') self.edi_IncidentID = QtGui.QLineEdit() self.edi_MediaType = QtGui.QLineEdit() self.edi_OrganizationAffected = QtGui.QLineEdit() self.edi_OrganizationContact = QtGui.QLineEdit() btn_Submit = QtGui.QPushButton('Submit') grid = QtGui.QGridLayout() grid.setSpacing(10) grid.addWidget(lbl_IncidentID, 1, 0) grid.addWidget(self.edi_IncidentID, 1, 1) grid.addWidget(lbl_MediaType, 3, 0) grid.addWidget(self.edi_MediaType, 3, 1) grid.addWidget(lbl_OrganizationAffected, 4, 0) grid.addWidget(self.edi_OrganizationAffected, 4, 1) grid.addWidget(lbl_OrganizationContact, 5, 0) grid.addWidget(self.edi_OrganizationContact, 5, 1) grid.addWidget(btn_Submit, 15, 0) self.sql = 'INSERT INTO jobs (incident_id, organization, organization_poc, media_type) VALUES ("%s", "%s", "%s", "%s")' % (self.edi_IncidentID.text(), self.edi_OrganizationAffected.text(), self.edi_OrganizationContact.text(), self.edi_MediaType.text()) self.connect(btn_Submit, QtCore.SIGNAL('clicked()'), self.submitForm) self.setLayout(grid) self.resize(350, 300) def submitForm(self): db = Database() db.writeValues(self.sql) app = QtGui.QApplication(sys.argv) qb = NewIncidentForm() qb.show() sys.exit(app.exec_()) </code></pre>
1
2009-10-14T21:39:07Z
5,186,155
<p>The reason is very simple:</p> <p>self.sql should be in def submitForm(self):</p> <p>not in def <strong>init</strong>(self, parent=None):</p> <p>because otherweise it's void!</p>
1
2011-03-03T20:27:10Z
[ "python", "mysql", "pyqt4", "qstring" ]
Python/PyQT QString won't insert into MySQL database
1,569,161
<p>I am trying to trying to retrieve some values from a user using a QLineEdit widget. When a QPushButton raises a clicked event, I want the text to be retrieved from all QLineEdit widgets and stored in a local MySQL databaase. However, when I try to use string substition in the insert statement, the values don't get substituted. Here's my sql statement:</p> <pre><code>sql = 'INSERT INTO jobs (incident_id, organization, organization_poc, media_type) VALUES ("%s", "%s", "%s", "%s")' % (self.edi_IncidentID.text(), self.edi_OrganizationAffected.text(), self.edi_OrganizationContact.text(), self.edi_MediaType.text()) </code></pre> <p>All of the self.edi_xxx variables are just QLineEdit widgets. When a button is pushed, the following is fired:</p> <pre><code>self.connect(btn_Submit, QtCore.SIGNAL('clicked()'), self.submitForm) </code></pre> <p>All submit does is create a database object and write the values to the database. However, for debugging I print out the constructed SQL statement and this comes out: INSERT INTO jobs (incident_id, organization, organization_poc, media_type) VALUES ("", "", "", "").</p> <p>I have also tried using the str() function to convert a QString to a string but the same thing happens.</p> <p>Any help would be greatly appreciated :)?</p> <p>L</p> <p>EDIT: Here is the complete code minus the imports:</p> <pre><code>class Database(): def __init__(self): self.db_host = "localhost" self.db_user = "***********" self.db_pass = "***********" self.db_name = "incidents" def openConn(self): self.db = MySQLdb.connect(self.db_host, self.db_user, self.db_pass, self.db_name) def closeConn(self): self.db.close() def writeValues(self, sql): self.openConn() self.cursor = self.db.cursor() self.cursor.execute(sql) self.cursor.fetchone() self.closeConn() class NewIncidentForm(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('New Incident') lbl_IncidentID = QtGui.QLabel('Incident ID:') lbl_MediaType = QtGui.QLabel('Media Type:') lbl_OrganizationAffected = QtGui.QLabel('Organization Affected:') lbl_OrganizationContact = QtGui.QLabel('Organization Point of Contact: ') self.edi_IncidentID = QtGui.QLineEdit() self.edi_MediaType = QtGui.QLineEdit() self.edi_OrganizationAffected = QtGui.QLineEdit() self.edi_OrganizationContact = QtGui.QLineEdit() btn_Submit = QtGui.QPushButton('Submit') grid = QtGui.QGridLayout() grid.setSpacing(10) grid.addWidget(lbl_IncidentID, 1, 0) grid.addWidget(self.edi_IncidentID, 1, 1) grid.addWidget(lbl_MediaType, 3, 0) grid.addWidget(self.edi_MediaType, 3, 1) grid.addWidget(lbl_OrganizationAffected, 4, 0) grid.addWidget(self.edi_OrganizationAffected, 4, 1) grid.addWidget(lbl_OrganizationContact, 5, 0) grid.addWidget(self.edi_OrganizationContact, 5, 1) grid.addWidget(btn_Submit, 15, 0) self.sql = 'INSERT INTO jobs (incident_id, organization, organization_poc, media_type) VALUES ("%s", "%s", "%s", "%s")' % (self.edi_IncidentID.text(), self.edi_OrganizationAffected.text(), self.edi_OrganizationContact.text(), self.edi_MediaType.text()) self.connect(btn_Submit, QtCore.SIGNAL('clicked()'), self.submitForm) self.setLayout(grid) self.resize(350, 300) def submitForm(self): db = Database() db.writeValues(self.sql) app = QtGui.QApplication(sys.argv) qb = NewIncidentForm() qb.show() sys.exit(app.exec_()) </code></pre>
1
2009-10-14T21:39:07Z
18,804,492
<p>the other part that is missing for the program is the commit() function to have data stored or autocommit(true) at the begging of the script</p> <pre><code>def closeConn(self): self.db.close() self.db.commit() def submitForm(self): db = Database() self.sql = 'INSERT INTO jobs (incident_id, organization, organization_poc, media_type) VALUES ("%s", "%s", "%s", "%s")' % (self.edi_IncidentID.text(), self.edi_OrganizationAffected.text(), self.edi_OrganizationContact.text(), self.edi_MediaType.text()) db.writeValues(self.sql) </code></pre>
1
2013-09-14T17:31:08Z
[ "python", "mysql", "pyqt4", "qstring" ]
How to use Python to log into Facebook/Myspace and crawl the content?
1,569,206
<p>Right now, I can crawl regular pages using urllib2.</p> <pre><code>request = urllib2.Request('http://stackoverflow.com') request.add_header('User-Agent',random.choice(agents)) response = urllib2.urlopen(request) htmlSource = response.read() print htmlSource </code></pre> <p>However...I would like to simulate a POST (or fake sessions)? so that I can go into Facebook and crawl. How do I do that?</p>
4
2009-10-14T21:49:39Z
1,569,231
<p>You can do POST requests by first encoding the data using urllib, and then sending the request using urllib2 just as you are doing now.</p> <p>This is explained in <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml" rel="nofollow">this article</a>.</p>
1
2009-10-14T21:53:47Z
[ "python", "authentication", "session", "post", "web-crawler" ]
How to use Python to log into Facebook/Myspace and crawl the content?
1,569,206
<p>Right now, I can crawl regular pages using urllib2.</p> <pre><code>request = urllib2.Request('http://stackoverflow.com') request.add_header('User-Agent',random.choice(agents)) response = urllib2.urlopen(request) htmlSource = response.read() print htmlSource </code></pre> <p>However...I would like to simulate a POST (or fake sessions)? so that I can go into Facebook and crawl. How do I do that?</p>
4
2009-10-14T21:49:39Z
1,569,257
<p>You'll need to keep the cookie your site of choice sends you when you log in; that's what keeps your session. With <code>urllib2</code>, you do this by creating an Opener object that supports cookie processing:</p> <pre><code>import urllib2, cookielib jar = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) </code></pre> <p>With this opener, you can do requests, either GET or POST:</p> <pre><code>content = opener.open(urllib2.Request( "http://social.netwo.rk/login", "user=foo&amp;pass=bar") ).read() </code></pre> <p>As there's a second parameter to urllib2.Request, it'll be a POST request -- if that's None, you end up with a GET request. You can also add HTTP headers, either with <code>.add_header</code> or by handing the constructor a dictionary (or a tuple-tuple) of headers. Read the manual for urllib2.Request for more information.</p> <p>That should get you started! Good luck.</p> <p>(ps: If you don't need read access to the cookies, you can just omit creating the cookie jar yourself; the HTTPCookieProcessor will do it for you.)</p>
7
2009-10-14T21:59:46Z
[ "python", "authentication", "session", "post", "web-crawler" ]
How to use Python to log into Facebook/Myspace and crawl the content?
1,569,206
<p>Right now, I can crawl regular pages using urllib2.</p> <pre><code>request = urllib2.Request('http://stackoverflow.com') request.add_header('User-Agent',random.choice(agents)) response = urllib2.urlopen(request) htmlSource = response.read() print htmlSource </code></pre> <p>However...I would like to simulate a POST (or fake sessions)? so that I can go into Facebook and crawl. How do I do that?</p>
4
2009-10-14T21:49:39Z
1,569,449
<p>The <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">Mechanize</a> library is an easy way to emulate a browser in Python.</p>
4
2009-10-14T22:54:01Z
[ "python", "authentication", "session", "post", "web-crawler" ]
How to use Python to log into Facebook/Myspace and crawl the content?
1,569,206
<p>Right now, I can crawl regular pages using urllib2.</p> <pre><code>request = urllib2.Request('http://stackoverflow.com') request.add_header('User-Agent',random.choice(agents)) response = urllib2.urlopen(request) htmlSource = response.read() print htmlSource </code></pre> <p>However...I would like to simulate a POST (or fake sessions)? so that I can go into Facebook and crawl. How do I do that?</p>
4
2009-10-14T21:49:39Z
1,569,693
<p>OR you may use PyCurl as a choice...</p>
1
2009-10-15T00:26:24Z
[ "python", "authentication", "session", "post", "web-crawler" ]
Clojure equivalent to Python's lxml library?
1,569,223
<p>I'm looking for the Clojure/Java equivalent to Python's lxml library. </p> <p>I've used it a ton in the past for parsing all sorts of html (as a replacement for BeautifulSoup) and it's great to be able to use the same elementtree api for xml as well -- really a trusted friend! Can anyone recommend a similar Java/Clojure library?</p> <p>About lxml</p> <p>lxml is an xml and html processing library based off of libxml2. It handles broken html pages very well so it is excellent for screen scraping tasks. It also implements the ElementTree api, so the xml/html structure is represented as a tree object with full support for xpath and css selectors among other things. </p> <p>It also has some really handy utility functions such as the "cleaner" module which will strip out unwanted tags from the "soup" (ie script tags, style tags, etc...).</p> <p>So it is simple to use, robust, and VERY fast...!</p>
10
2009-10-14T21:51:49Z
1,569,666
<p>For Java (and thus usable from Clojure) is the <a href="http://home.ccil.org/~cowan/XML/tagsoup/" rel="nofollow"><code>tagsoup</code>-library</a>, which, like <code>lxml</code>, is a tolerant parser for faulty SGML-variants.</p> <p>Clojure has a bundled namespace <code>clojure.xml</code>, but this will only work with valid XML.</p>
3
2009-10-15T00:16:27Z
[ "java", "python", "clojure", "lxml" ]