title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
|---|---|---|---|---|---|---|---|---|---|
Is there a python equivalent of the prefuse visualization toolkit?
| 591,839
|
<p>The <a href="http://prefuse.org/" rel="nofollow">prefuse visualization toolkit</a> is pretty nice, but for Java. I was wondering if there was something similar for python. My primary interest is being able to navigate dynamic graphs.</p>
| 10
|
2009-02-26T18:30:45Z
| 3,476,644
|
<p>This is well after OP, but just in case:</p>
<p><a href="http://dkbza.org/pydot.html" rel="nofollow">pydot</a>. Allows generation & rendering of graphs. If you need graph algorithms (transitive closure etc.) also look at pygraphlib which extends and integrates pydot.</p>
<p>Note that neither allows interactive editing of the rendered diagram. They both use graphviz to generate output.</p>
| 1
|
2010-08-13T12:12:14Z
|
[
"python",
"visualization",
"prefuse"
] |
In Python what is the preferred way to create and manage threads?
| 592,143
|
<p>Python provides several methods to create threads. Which provides
the best API and the most control?</p>
<p>Thanks.</p>
| 2
|
2009-02-26T19:54:47Z
| 592,168
|
<p>I believe the <code>threading</code> module is the recommended one. The <code>thread</code> module is being renamed to _thread in Python 3.x, and is meant as a lower-level interface. See the note at the top of this page:</p>
<p><a href="http://docs.python.org/library/thread.html" rel="nofollow">http://docs.python.org/library/thread.html</a></p>
| 4
|
2009-02-26T20:00:17Z
|
[
"python",
"multithreading"
] |
In Python what is the preferred way to create and manage threads?
| 592,143
|
<p>Python provides several methods to create threads. Which provides
the best API and the most control?</p>
<p>Thanks.</p>
| 2
|
2009-02-26T19:54:47Z
| 592,170
|
<p>When necessary, the <a href="http://docs.python.org/library/threading.html" rel="nofollow">threading</a> module and its high-level interface is preferred. Of course, many people suggest that it's rarely/never necessary, and threads aren't very nice to deal with. The thread module may be necessary for some weird use-case or other, but I've never needed it (and of course, I've only rarely used threading, a long time ago). There's some other modules that do neater things, such as <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">multiprocessing</a>, which may be of interest. That doesn't do threading, it just shares the interface (quite cool). I've heard good things about it, but haven't wanted anything like either of them for quite a while.</p>
| 8
|
2009-02-26T20:00:54Z
|
[
"python",
"multithreading"
] |
Fast way to determine if a PID exists on (Windows)?
| 592,256
|
<p>I realize "fast" is a bit subjective so I'll explain with some context. I'm working on a Python module called <a href="http://code.google.com/p/psutil/" rel="nofollow"><strong>psutil</strong></a> for reading process information in a cross-platform way. One of the functions is a <code>pid_exists(pid)</code> function for determining if a PID is in the current process list.</p>
<p>Right now I'm doing this the obvious way, using <a href="http://msdn.microsoft.com/en-us/library/ms682629%28VS.85%29.aspx" rel="nofollow">EnumProcesses()</a> to pull the process list, then interating through the list and looking for the PID. However, some simple benchmarking shows this is dramatically slower than the pid_exists function on UNIX-based platforms (Linux, OS X, FreeBSD) where we're using <code>kill(pid, 0)</code> with a 0 signal to determine if a PID exists. Additional testing shows it's EnumProcesses that's taking up almost all the time.</p>
<p>Anyone know a faster way than using EnumProcesses to determine if a PID exists? I tried <a href="http://msdn.microsoft.com/en-us/library/ms684320%28VS.85%29.aspx" rel="nofollow">OpenProcess()</a> and checking for an error opening the nonexistent process, but this turned out to be over 4x slower than iterating through the EnumProcesses list, so that's out as well. Any other (better) suggestions?</p>
<p><strong>NOTE</strong>: This is a Python library intended to avoid third-party lib dependencies like pywin32 extensions. I need a solution that is faster than our current code, and that doesn't depend on pywin32 or other modules not present in a standard Python distribution.</p>
<p><strong>EDIT</strong>: To clarify - we're well aware that there are race conditions inherent in reading process iformation. We raise exceptions if the process goes away during the course of data collection or we run into other problems. The pid_exists() function isn't intended to replace proper error handling.</p>
<p><strong>UPDATE</strong>: Apparently my earlier benchmarks were flawed - I wrote some simple test apps in C and EnumProcesses consistently comes out slower and OpenProcess (in conjunction with GetProcessExitCode in case the PID is valid but the process has stopped) is actually much <em>faster</em> not slower.</p>
| 8
|
2009-02-26T20:19:23Z
| 592,449
|
<p>There is an inherent race condition in the use of pid_exists function: by the time the calling program gets to use the answer, the process may have already disappeared, or a new process with the queried id may have been created. I would dare say that any application that uses this function is flawed by design and that optimizing this function is therefore not worth the effort.</p>
| 4
|
2009-02-26T21:08:02Z
|
[
"python",
"c",
"winapi",
"pid"
] |
Fast way to determine if a PID exists on (Windows)?
| 592,256
|
<p>I realize "fast" is a bit subjective so I'll explain with some context. I'm working on a Python module called <a href="http://code.google.com/p/psutil/" rel="nofollow"><strong>psutil</strong></a> for reading process information in a cross-platform way. One of the functions is a <code>pid_exists(pid)</code> function for determining if a PID is in the current process list.</p>
<p>Right now I'm doing this the obvious way, using <a href="http://msdn.microsoft.com/en-us/library/ms682629%28VS.85%29.aspx" rel="nofollow">EnumProcesses()</a> to pull the process list, then interating through the list and looking for the PID. However, some simple benchmarking shows this is dramatically slower than the pid_exists function on UNIX-based platforms (Linux, OS X, FreeBSD) where we're using <code>kill(pid, 0)</code> with a 0 signal to determine if a PID exists. Additional testing shows it's EnumProcesses that's taking up almost all the time.</p>
<p>Anyone know a faster way than using EnumProcesses to determine if a PID exists? I tried <a href="http://msdn.microsoft.com/en-us/library/ms684320%28VS.85%29.aspx" rel="nofollow">OpenProcess()</a> and checking for an error opening the nonexistent process, but this turned out to be over 4x slower than iterating through the EnumProcesses list, so that's out as well. Any other (better) suggestions?</p>
<p><strong>NOTE</strong>: This is a Python library intended to avoid third-party lib dependencies like pywin32 extensions. I need a solution that is faster than our current code, and that doesn't depend on pywin32 or other modules not present in a standard Python distribution.</p>
<p><strong>EDIT</strong>: To clarify - we're well aware that there are race conditions inherent in reading process iformation. We raise exceptions if the process goes away during the course of data collection or we run into other problems. The pid_exists() function isn't intended to replace proper error handling.</p>
<p><strong>UPDATE</strong>: Apparently my earlier benchmarks were flawed - I wrote some simple test apps in C and EnumProcesses consistently comes out slower and OpenProcess (in conjunction with GetProcessExitCode in case the PID is valid but the process has stopped) is actually much <em>faster</em> not slower.</p>
| 8
|
2009-02-26T20:19:23Z
| 592,788
|
<p><a href="http://msdn.microsoft.com/en-us/library/ms684320%28VS.85%29.aspx">OpenProcess</a> could tell you w/o enumerating all. I have no idea how fast.</p>
<p><strong>EDIT</strong>: note that you also need <code>GetExitCodeProcess</code> to verify the state of the process even if you get a handle from <code>OpenProcess</code>.</p>
| 8
|
2009-02-26T22:41:23Z
|
[
"python",
"c",
"winapi",
"pid"
] |
Fast way to determine if a PID exists on (Windows)?
| 592,256
|
<p>I realize "fast" is a bit subjective so I'll explain with some context. I'm working on a Python module called <a href="http://code.google.com/p/psutil/" rel="nofollow"><strong>psutil</strong></a> for reading process information in a cross-platform way. One of the functions is a <code>pid_exists(pid)</code> function for determining if a PID is in the current process list.</p>
<p>Right now I'm doing this the obvious way, using <a href="http://msdn.microsoft.com/en-us/library/ms682629%28VS.85%29.aspx" rel="nofollow">EnumProcesses()</a> to pull the process list, then interating through the list and looking for the PID. However, some simple benchmarking shows this is dramatically slower than the pid_exists function on UNIX-based platforms (Linux, OS X, FreeBSD) where we're using <code>kill(pid, 0)</code> with a 0 signal to determine if a PID exists. Additional testing shows it's EnumProcesses that's taking up almost all the time.</p>
<p>Anyone know a faster way than using EnumProcesses to determine if a PID exists? I tried <a href="http://msdn.microsoft.com/en-us/library/ms684320%28VS.85%29.aspx" rel="nofollow">OpenProcess()</a> and checking for an error opening the nonexistent process, but this turned out to be over 4x slower than iterating through the EnumProcesses list, so that's out as well. Any other (better) suggestions?</p>
<p><strong>NOTE</strong>: This is a Python library intended to avoid third-party lib dependencies like pywin32 extensions. I need a solution that is faster than our current code, and that doesn't depend on pywin32 or other modules not present in a standard Python distribution.</p>
<p><strong>EDIT</strong>: To clarify - we're well aware that there are race conditions inherent in reading process iformation. We raise exceptions if the process goes away during the course of data collection or we run into other problems. The pid_exists() function isn't intended to replace proper error handling.</p>
<p><strong>UPDATE</strong>: Apparently my earlier benchmarks were flawed - I wrote some simple test apps in C and EnumProcesses consistently comes out slower and OpenProcess (in conjunction with GetProcessExitCode in case the PID is valid but the process has stopped) is actually much <em>faster</em> not slower.</p>
| 8
|
2009-02-26T20:19:23Z
| 600,217
|
<p>Turns out that my benchmarks evidently were flawed somehow, as later testing reveals OpenProcess and GetExitCodeProcess are much faster than using EnumProcesses after all. I'm not sure what happened but I did some new tests and verified this is the faster solution: </p>
<pre><code>int pid_is_running(DWORD pid)
{
HANDLE hProcess;
DWORD exitCode;
//Special case for PID 0 System Idle Process
if (pid == 0) {
return 1;
}
//skip testing bogus PIDs
if (pid < 0) {
return 0;
}
hProcess = handle_from_pid(pid);
if (NULL == hProcess) {
//invalid parameter means PID isn't in the system
if (GetLastError() == ERROR_INVALID_PARAMETER) {
return 0;
}
//some other error with OpenProcess
return -1;
}
if (GetExitCodeProcess(hProcess, &exitCode)) {
CloseHandle(hProcess);
return (exitCode == STILL_ACTIVE);
}
//error in GetExitCodeProcess()
CloseHandle(hProcess);
return -1;
}
</code></pre>
<p>Note that you do need to use <code>GetExitCodeProcess()</code> because <code>OpenProcess()</code> will succeed on processes that have died recently so you can't assume a valid process handle means the process is running. </p>
<p>Also note that <code>OpenProcess()</code> succeeds for PIDs that are within 3 of any valid PID (See <a href="http://blogs.msdn.com/oldnewthing/archive/2008/06/06/8576557.aspx" rel="nofollow">Why does OpenProcess succeed even when I add three to the process ID?</a>)</p>
| 3
|
2009-03-01T18:18:22Z
|
[
"python",
"c",
"winapi",
"pid"
] |
Fast way to determine if a PID exists on (Windows)?
| 592,256
|
<p>I realize "fast" is a bit subjective so I'll explain with some context. I'm working on a Python module called <a href="http://code.google.com/p/psutil/" rel="nofollow"><strong>psutil</strong></a> for reading process information in a cross-platform way. One of the functions is a <code>pid_exists(pid)</code> function for determining if a PID is in the current process list.</p>
<p>Right now I'm doing this the obvious way, using <a href="http://msdn.microsoft.com/en-us/library/ms682629%28VS.85%29.aspx" rel="nofollow">EnumProcesses()</a> to pull the process list, then interating through the list and looking for the PID. However, some simple benchmarking shows this is dramatically slower than the pid_exists function on UNIX-based platforms (Linux, OS X, FreeBSD) where we're using <code>kill(pid, 0)</code> with a 0 signal to determine if a PID exists. Additional testing shows it's EnumProcesses that's taking up almost all the time.</p>
<p>Anyone know a faster way than using EnumProcesses to determine if a PID exists? I tried <a href="http://msdn.microsoft.com/en-us/library/ms684320%28VS.85%29.aspx" rel="nofollow">OpenProcess()</a> and checking for an error opening the nonexistent process, but this turned out to be over 4x slower than iterating through the EnumProcesses list, so that's out as well. Any other (better) suggestions?</p>
<p><strong>NOTE</strong>: This is a Python library intended to avoid third-party lib dependencies like pywin32 extensions. I need a solution that is faster than our current code, and that doesn't depend on pywin32 or other modules not present in a standard Python distribution.</p>
<p><strong>EDIT</strong>: To clarify - we're well aware that there are race conditions inherent in reading process iformation. We raise exceptions if the process goes away during the course of data collection or we run into other problems. The pid_exists() function isn't intended to replace proper error handling.</p>
<p><strong>UPDATE</strong>: Apparently my earlier benchmarks were flawed - I wrote some simple test apps in C and EnumProcesses consistently comes out slower and OpenProcess (in conjunction with GetProcessExitCode in case the PID is valid but the process has stopped) is actually much <em>faster</em> not slower.</p>
| 8
|
2009-02-26T20:19:23Z
| 609,020
|
<p>I'd code Jay's last function this way.</p>
<pre><code>int pid_is_running(DWORD pid){
HANDLE hProcess;
DWORD exitCode;
//Special case for PID 0 System Idle Process
if (pid == 0) {
return 1;
}
//skip testing bogus PIDs
if (pid < 0) {
return 0;
}
hProcess = handle_from_pid(pid);
if (NULL == hProcess) {
//invalid parameter means PID isn't in the system
if (GetLastError() == ERROR_INVALID_PARAMETER) {
return 0;
}
//some other error with OpenProcess
return -1;
}
DWORD dwRetval = WaitForSingleObject(hProcess, 0);
CloseHandle(hProcess); // otherwise you'll be losing handles
switch(dwRetval) {
case WAIT_OBJECT_0;
return 0;
case WAIT_TIMEOUT;
return 1;
default:
return -1;
}
}
</code></pre>
<p>The main difference is closing the process handle (important when the client of this function is running for a long time) and the process termination detection strategy. WaitForSingleObject gives you the opportunity to wait for a while (changing the 0 to a function parameter value) until the process ends.</p>
| 3
|
2009-03-04T02:13:18Z
|
[
"python",
"c",
"winapi",
"pid"
] |
Any reasons not to use SQLObject over SQLAlchemy?
| 592,332
|
<p>I don't expect to need much more than basic CRUD type functionality. I know that SQLAlchemy is more flexible, but the syntax etc of sqlobject just seem to be a bit easier to get up and going with.</p>
| 13
|
2009-02-26T20:37:30Z
| 592,348
|
<p>I think SQLObject is more pythonic/simpler, so if it works for you, then stick with it.<br />
SQLAlchemy takes a little more to learn, but can do more advanced things if you need that.</p>
| 8
|
2009-02-26T20:41:48Z
|
[
"python",
"orm",
"sqlalchemy",
"sqlobject"
] |
Any reasons not to use SQLObject over SQLAlchemy?
| 592,332
|
<p>I don't expect to need much more than basic CRUD type functionality. I know that SQLAlchemy is more flexible, but the syntax etc of sqlobject just seem to be a bit easier to get up and going with.</p>
| 13
|
2009-02-26T20:37:30Z
| 592,427
|
<p>Also, you might wanna take a look at <a href="http://elixir.ematia.de/trac/wiki">elixir</a>, which is a fairly thick wrapper around SQLAlchemy and really makes the basic tasks easy while retaining the power of SQLA.</p>
| 6
|
2009-02-26T21:00:19Z
|
[
"python",
"orm",
"sqlalchemy",
"sqlobject"
] |
Any reasons not to use SQLObject over SQLAlchemy?
| 592,332
|
<p>I don't expect to need much more than basic CRUD type functionality. I know that SQLAlchemy is more flexible, but the syntax etc of sqlobject just seem to be a bit easier to get up and going with.</p>
| 13
|
2009-02-26T20:37:30Z
| 11,271,218
|
<p>Try quick_orm. It is as powerful as SQLAlchemy and simpler than SQLObject. </p>
<p><a href="https://github.com/tylerlong/quick_orm" rel="nofollow">https://github.com/tylerlong/quick_orm</a></p>
| 0
|
2012-06-30T03:41:30Z
|
[
"python",
"orm",
"sqlalchemy",
"sqlobject"
] |
PyQt4: Databinding?
| 592,404
|
<p>Coming from the .NET world over to Python and PyQt4. Was wondering if anyone is familiar with any functionality that would allow me to bind data to Qt widgets? For example (using sqlalchemy for data):</p>
<pre><code>gems = session.query(Gem).all()
list = QListWidget()
list.datasource = gems
</code></pre>
<p>Is such a thing possible?</p>
| 3
|
2009-02-26T20:55:38Z
| 592,439
|
<p>One option would have a function that returns a list (or tuple) object from a query, and then use that to update the QListWidget. Remember that the QListWidget stores QListStrings. Your update function might look like this:</p>
<pre><code>def updateQListWidget(qlistwidget, values):
""" Updates a QListWidget object with a list of values
ARGS:
qlistwidget - QListWidget object
values - list of values to add to list widget
"""
qlistwidget.clear()
qlist = QtCore.QStringList()
for v in values:
s = QtCore.QString(v)
qlist.append(s)
qlistwidget.addItems(qlist)
</code></pre>
| 3
|
2009-02-26T21:03:53Z
|
[
"python",
"data-binding",
"qt4",
"pyqt4"
] |
PyQt4: Databinding?
| 592,404
|
<p>Coming from the .NET world over to Python and PyQt4. Was wondering if anyone is familiar with any functionality that would allow me to bind data to Qt widgets? For example (using sqlalchemy for data):</p>
<pre><code>gems = session.query(Gem).all()
list = QListWidget()
list.datasource = gems
</code></pre>
<p>Is such a thing possible?</p>
| 3
|
2009-02-26T20:55:38Z
| 592,785
|
<p>Although not a direct replacement, you might find it useful to look at the QDataWidgetMapper class:</p>
<p><a href="http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qdatawidgetmapper.html" rel="nofollow">http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qdatawidgetmapper.html</a></p>
<p>If you're not scared of reading C++ code, this example might also prove to be helpful:</p>
<p><a href="http://doc.trolltech.com/4.5/sql-sqlwidgetmapper.html" rel="nofollow">http://doc.trolltech.com/4.5/sql-sqlwidgetmapper.html</a></p>
<p>Note that the mapper operates within Qt's Model/View framework. In this example, the model just happens to be a SQL database model.</p>
| 4
|
2009-02-26T22:40:32Z
|
[
"python",
"data-binding",
"qt4",
"pyqt4"
] |
Parsing an HTML file with selectorgadget.com
| 592,910
|
<p>How can I use beautiful soup and <a href="http://selectorgadget.com" rel="nofollow">selectorgadget</a> to scrape a website. For example I have a website - <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E16819115017" rel="nofollow">(a newegg product)</a> and I would like my script to return all of the specifications of that product (click on SPECIFICATIONS) by this I mean - Intel, Desktop, ......, 2.4GHz, 1066Mhz, ...... , 3 years limited. </p>
<p>After using selectorgadget I get the string-
.desc</p>
<p>How do I use this?</p>
<p>Thanks :)</p>
| 3
|
2009-02-26T23:21:39Z
| 592,986
|
<p>Inspecting the page, I can see that the specifications are placed in a div with the ID pcraSpecs:</p>
<pre><code><div id="pcraSpecs">
<script type="text/javascript">...</script>
<TABLE cellpadding="0" cellspacing="0" class="specification">
<TR>
<TD colspan="2" class="title">Model</TD>
</TR>
<TR>
<TD class="name">Brand</TD>
<TD class="desc"><script type="text/javascript">document.write(neg_specification_newline('Intel'));</script></TD>
</TR>
<TR>
<TD class="name">Processors Type</TD>
<TD class="desc"><script type="text/javascript">document.write(neg_specification_newline('Desktop'));</script></TD>
</TR>
...
</TABLE>
</div>
</code></pre>
<p>desc is the class of the table cells.</p>
<p>What you want to do is to extract the contents of this table.</p>
<p><code>soup.find(id="pcraSpecs").findAll("td")</code> should get you started.</p>
| 1
|
2009-02-26T23:40:38Z
|
[
"python",
"css",
"screen-scraping",
"beautifulsoup",
"html-content-extraction"
] |
Parsing an HTML file with selectorgadget.com
| 592,910
|
<p>How can I use beautiful soup and <a href="http://selectorgadget.com" rel="nofollow">selectorgadget</a> to scrape a website. For example I have a website - <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E16819115017" rel="nofollow">(a newegg product)</a> and I would like my script to return all of the specifications of that product (click on SPECIFICATIONS) by this I mean - Intel, Desktop, ......, 2.4GHz, 1066Mhz, ...... , 3 years limited. </p>
<p>After using selectorgadget I get the string-
.desc</p>
<p>How do I use this?</p>
<p>Thanks :)</p>
| 3
|
2009-02-26T23:21:39Z
| 593,345
|
<p>Have you tried using Feedity - <a href="http://feedity.com" rel="nofollow">http://feedity.com</a> for creating a custom RSS feed from any webpage.</p>
| 0
|
2009-02-27T02:58:36Z
|
[
"python",
"css",
"screen-scraping",
"beautifulsoup",
"html-content-extraction"
] |
Why doesn't Python have static variables?
| 592,931
|
<p>There is a <a href="http://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python">questions asking how to simulate static variables in python</a>.</p>
<p>Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.)</p>
<p>Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax?</p>
<p><strong>Edit:</strong></p>
<p>I asked specifically about the <em>why</em> of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables.</p>
| 42
|
2009-02-26T23:28:09Z
| 592,961
|
<p>I think most uses of local static variables is to simulate generators, that is, having some function which performs some iteration of a process, returns the result, but mantains the state for the subsequent invocation. Python handles this very elegantly using the <code>yield</code> command, so it seems there is not so much need for static variables.</p>
| 6
|
2009-02-26T23:35:18Z
|
[
"python"
] |
Why doesn't Python have static variables?
| 592,931
|
<p>There is a <a href="http://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python">questions asking how to simulate static variables in python</a>.</p>
<p>Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.)</p>
<p>Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax?</p>
<p><strong>Edit:</strong></p>
<p>I asked specifically about the <em>why</em> of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables.</p>
| 42
|
2009-02-26T23:28:09Z
| 592,971
|
<p>It's a design choice.</p>
<p>I'm assuming Guido thinks you don't need them very often, and you never <em>really</em> need them: you can always just use a global variable and tell everyone to keep their greasy paws offa' your variable ;-)</p>
| 5
|
2009-02-26T23:37:37Z
|
[
"python"
] |
Why doesn't Python have static variables?
| 592,931
|
<p>There is a <a href="http://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python">questions asking how to simulate static variables in python</a>.</p>
<p>Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.)</p>
<p>Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax?</p>
<p><strong>Edit:</strong></p>
<p>I asked specifically about the <em>why</em> of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables.</p>
| 42
|
2009-02-26T23:28:09Z
| 593,046
|
<p>The idea behind this omission is that static variables are only useful in two situations: when you really should be using a class and when you really should be using a generator.</p>
<p>If you want to attach stateful information to a function, what you need is a class. A trivially simple class, perhaps, but a class nonetheless:</p>
<pre><code>def foo(bar):
static my_bar # doesn't work
if not my_bar:
my_bar = bar
do_stuff(my_bar)
foo(bar)
foo()
# -- becomes ->
class Foo(object):
def __init__(self, bar):
self.bar = bar
def __call__(self):
do_stuff(self.bar)
foo = Foo(bar)
foo()
foo()
</code></pre>
<p>If you want your function's behavior to change each time it's called, what you need is a generator:</p>
<pre><code>def foo(bar):
static my_bar # doesn't work
if not my_bar:
my_bar = bar
my_bar = my_bar * 3 % 5
return my_bar
foo(bar)
foo()
# -- becomes ->
def foogen(bar):
my_bar = bar
while True:
my_bar = my_bar * 3 % 5
yield my_bar
foo = foogen(bar)
foo.next()
foo.next()
</code></pre>
<p>Of course, static variables <em>are</em> useful for quick-and-dirty scripts where you don't want to deal with the hassle of big structures for little tasks. But there, you don't really need anything more than <code>global</code> â it may seem a but kludgy, but that's okay for small, one-off scripts:</p>
<pre><code>def foo():
global bar
do_stuff(bar)
foo()
foo()
</code></pre>
| 73
|
2009-02-27T00:04:02Z
|
[
"python"
] |
Why doesn't Python have static variables?
| 592,931
|
<p>There is a <a href="http://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python">questions asking how to simulate static variables in python</a>.</p>
<p>Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.)</p>
<p>Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax?</p>
<p><strong>Edit:</strong></p>
<p>I asked specifically about the <em>why</em> of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables.</p>
| 42
|
2009-02-26T23:28:09Z
| 593,098
|
<p>The answer's pretty much the same as why nobody uses static methods (even though they exist). You have a module-level namespace that serves about the same purpose as a class would anyway.</p>
| 0
|
2009-02-27T00:28:54Z
|
[
"python"
] |
Why doesn't Python have static variables?
| 592,931
|
<p>There is a <a href="http://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python">questions asking how to simulate static variables in python</a>.</p>
<p>Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.)</p>
<p>Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax?</p>
<p><strong>Edit:</strong></p>
<p>I asked specifically about the <em>why</em> of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables.</p>
| 42
|
2009-02-26T23:28:09Z
| 593,154
|
<p>For caching or <a href="http://code.activestate.com/recipes/52201/" rel="nofollow">memoization</a> purposes, decorators can be used as an elegant and general solution.</p>
| 4
|
2009-02-27T00:54:15Z
|
[
"python"
] |
Why doesn't Python have static variables?
| 592,931
|
<p>There is a <a href="http://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python">questions asking how to simulate static variables in python</a>.</p>
<p>Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.)</p>
<p>Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax?</p>
<p><strong>Edit:</strong></p>
<p>I asked specifically about the <em>why</em> of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables.</p>
| 42
|
2009-02-26T23:28:09Z
| 593,226
|
<p>One alternative to a class is a function attribute:</p>
<pre><code>def foo(arg):
if not hasattr(foo, 'cache'):
foo.cache = get_data_dict()
return foo.cache[arg]
</code></pre>
<p>While a class is probably cleaner, this technique can be useful and is nicer, in my opinion, then a global. </p>
| 19
|
2009-02-27T01:41:57Z
|
[
"python"
] |
Why doesn't Python have static variables?
| 592,931
|
<p>There is a <a href="http://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python">questions asking how to simulate static variables in python</a>.</p>
<p>Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.)</p>
<p>Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax?</p>
<p><strong>Edit:</strong></p>
<p>I asked specifically about the <em>why</em> of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables.</p>
| 42
|
2009-02-26T23:28:09Z
| 593,477
|
<p>An ill-advised alternative:</p>
<p>You can also use the side-effects of the definition time evaluation of function defaults:</p>
<pre><code>def func(initial=0, my_static=[])
if not my_static:
my_static.append(initial)
my_static[0] += 1
return my_static[0]
print func(0), func(0), func(0)
</code></pre>
<p>Its <em>really</em> ugly and easily subverted, but works. Using <code>global</code> would be cleaner than this, imo.</p>
| 0
|
2009-02-27T04:04:02Z
|
[
"python"
] |
Why doesn't Python have static variables?
| 592,931
|
<p>There is a <a href="http://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python">questions asking how to simulate static variables in python</a>.</p>
<p>Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.)</p>
<p>Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax?</p>
<p><strong>Edit:</strong></p>
<p>I asked specifically about the <em>why</em> of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables.</p>
| 42
|
2009-02-26T23:28:09Z
| 594,760
|
<p>From one of your comments: "I'd like to use them to cache things loaded from disk. I think it clutters the instance less, if I could assign them to the function"</p>
<p>Use a caching class then, as a class or instance attribute to your other class. That way, you can use the full feature set of classes without cluttering other things. Also, you get a reusable tool.</p>
<p>This shows that on SO it always pays off to state one's problem instead of asking for a specific, low level solution (e.g. for a missing language feature). That way, instead of endless debates about simulating "static" (a deprecated feature from an ancient language, in my view) someone could have given a good answer to you problem sooner.</p>
| -1
|
2009-02-27T13:34:45Z
|
[
"python"
] |
Why doesn't Python have static variables?
| 592,931
|
<p>There is a <a href="http://stackoverflow.com/questions/460586/simulating-a-local-static-variable-in-python">questions asking how to simulate static variables in python</a>.</p>
<p>Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.)</p>
<p>Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax?</p>
<p><strong>Edit:</strong></p>
<p>I asked specifically about the <em>why</em> of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables.</p>
| 42
|
2009-02-26T23:28:09Z
| 623,043
|
<p>In Python 3, I would use a closure:</p>
<pre><code>def makefoo():
x = 0
def foo():
nonlocal x
x += 1
return x
return foo
foo = makefoo()
print(foo())
print(foo())
</code></pre>
| 8
|
2009-03-08T04:39:27Z
|
[
"python"
] |
Python for mathematics students?
| 593,685
|
<p>I need to deliver one and half hour seminar on programming for students at the department of mathematics. </p>
<p>I have chosen python as language.</p>
<ol>
<li>What should be content of my presentation ?</li>
<li>What are good resources available ?</li>
<li>What is necessity of programming for maths students?</li>
<li>How will knowledge of programming will help them?</li>
</ol>
<p>Thank you !!!</p>
<p>NOTE: I know <a href="http://stackoverflow.com/questions/488502/best-language-to-program-some-math-free-fast-easy-cool-etc">here</a> is one post but it doesn't solve my problem.</p>
| 7
|
2009-02-27T06:10:16Z
| 593,694
|
<p>Do the getting started guide to scipy?</p>
<p><a href="http://www.scipy.org/Getting%5FStarted" rel="nofollow">http://www.scipy.org/Getting_Started</a></p>
| 8
|
2009-02-27T06:13:05Z
|
[
"python",
"math"
] |
Python for mathematics students?
| 593,685
|
<p>I need to deliver one and half hour seminar on programming for students at the department of mathematics. </p>
<p>I have chosen python as language.</p>
<ol>
<li>What should be content of my presentation ?</li>
<li>What are good resources available ?</li>
<li>What is necessity of programming for maths students?</li>
<li>How will knowledge of programming will help them?</li>
</ol>
<p>Thank you !!!</p>
<p>NOTE: I know <a href="http://stackoverflow.com/questions/488502/best-language-to-program-some-math-free-fast-easy-cool-etc">here</a> is one post but it doesn't solve my problem.</p>
| 7
|
2009-02-27T06:10:16Z
| 593,705
|
<p>Assuming that these students are new to programming (which is quite likely for math students), you'll want to give them a basic introduction to programming (what a function is, what a variable is, how each of these differ from functions and variables in math, etc).</p>
<p>Show them some example programs, with a view to things that will be helpful for math: numerical methods, matrix multiplication, etc.</p>
<p>Wherever possible, wow them so that they'll get excited about using computers for their own projects.
<a href="http://www.math.okstate.edu/~ullrich/PyPlug/" rel="nofollow">Some Python/Math resources</a></p>
| 4
|
2009-02-27T06:16:45Z
|
[
"python",
"math"
] |
Python for mathematics students?
| 593,685
|
<p>I need to deliver one and half hour seminar on programming for students at the department of mathematics. </p>
<p>I have chosen python as language.</p>
<ol>
<li>What should be content of my presentation ?</li>
<li>What are good resources available ?</li>
<li>What is necessity of programming for maths students?</li>
<li>How will knowledge of programming will help them?</li>
</ol>
<p>Thank you !!!</p>
<p>NOTE: I know <a href="http://stackoverflow.com/questions/488502/best-language-to-program-some-math-free-fast-easy-cool-etc">here</a> is one post but it doesn't solve my problem.</p>
| 7
|
2009-02-27T06:10:16Z
| 593,708
|
<p>I'm assuming this is for Freshmen (only because most higher level Math students will likely know how to program)? If so, do something that is fun and relevant. Go through the basics, but maybe walk them through the logic / basic framework for a Game (which are heavily math oriented) or Python-Based Graphing Calculator. </p>
<p>If you want to get them real geeked though, show them Mathematica. I know, it's not what you selected ... but when I was a Sophomore Math major and first saw what you could do with it, I was in love.</p>
| 0
|
2009-02-27T06:20:02Z
|
[
"python",
"math"
] |
Python for mathematics students?
| 593,685
|
<p>I need to deliver one and half hour seminar on programming for students at the department of mathematics. </p>
<p>I have chosen python as language.</p>
<ol>
<li>What should be content of my presentation ?</li>
<li>What are good resources available ?</li>
<li>What is necessity of programming for maths students?</li>
<li>How will knowledge of programming will help them?</li>
</ol>
<p>Thank you !!!</p>
<p>NOTE: I know <a href="http://stackoverflow.com/questions/488502/best-language-to-program-some-math-free-fast-easy-cool-etc">here</a> is one post but it doesn't solve my problem.</p>
| 7
|
2009-02-27T06:10:16Z
| 593,711
|
<p>Python will work well, but GNU Octave may be better.</p>
| 0
|
2009-02-27T06:21:47Z
|
[
"python",
"math"
] |
Python for mathematics students?
| 593,685
|
<p>I need to deliver one and half hour seminar on programming for students at the department of mathematics. </p>
<p>I have chosen python as language.</p>
<ol>
<li>What should be content of my presentation ?</li>
<li>What are good resources available ?</li>
<li>What is necessity of programming for maths students?</li>
<li>How will knowledge of programming will help them?</li>
</ol>
<p>Thank you !!!</p>
<p>NOTE: I know <a href="http://stackoverflow.com/questions/488502/best-language-to-program-some-math-free-fast-easy-cool-etc">here</a> is one post but it doesn't solve my problem.</p>
| 7
|
2009-02-27T06:10:16Z
| 593,833
|
<p>Sage: <a href="http://www.sagemath.org/" rel="nofollow">http://www.sagemath.org/</a></p>
| 7
|
2009-02-27T07:22:18Z
|
[
"python",
"math"
] |
Python for mathematics students?
| 593,685
|
<p>I need to deliver one and half hour seminar on programming for students at the department of mathematics. </p>
<p>I have chosen python as language.</p>
<ol>
<li>What should be content of my presentation ?</li>
<li>What are good resources available ?</li>
<li>What is necessity of programming for maths students?</li>
<li>How will knowledge of programming will help them?</li>
</ol>
<p>Thank you !!!</p>
<p>NOTE: I know <a href="http://stackoverflow.com/questions/488502/best-language-to-program-some-math-free-fast-easy-cool-etc">here</a> is one post but it doesn't solve my problem.</p>
| 7
|
2009-02-27T06:10:16Z
| 593,900
|
<p>What should be content of my presentation ?</p>
<blockquote>
<p>The concept of <strong>functional programming</strong> with Python.
Some introduction to third party modules like <strong>NumPy</strong> and <strong>SciPy</strong>.</p>
</blockquote>
<p>What are good resources available ?</p>
<blockquote>
<p>Hans Petter Langtangen, <strong>Python Scripting for Computational Science</strong>, Springer</p>
</blockquote>
<p>What is necessity of programming for maths students?</p>
<blockquote>
<p><strong>None</strong>. Usually maths students will have no problem in programming, since most programming language were developed to solve maths problem.</p>
</blockquote>
<p>How will knowledge of programming will help them?</p>
<blockquote>
<p>The computer was earlier developed as a tool for scientist to help them <strong>solve scientific/mathematics problems efficiently in a very short time, as compared to human</strong>.</p>
</blockquote>
| 0
|
2009-02-27T07:54:09Z
|
[
"python",
"math"
] |
Python for mathematics students?
| 593,685
|
<p>I need to deliver one and half hour seminar on programming for students at the department of mathematics. </p>
<p>I have chosen python as language.</p>
<ol>
<li>What should be content of my presentation ?</li>
<li>What are good resources available ?</li>
<li>What is necessity of programming for maths students?</li>
<li>How will knowledge of programming will help them?</li>
</ol>
<p>Thank you !!!</p>
<p>NOTE: I know <a href="http://stackoverflow.com/questions/488502/best-language-to-program-some-math-free-fast-easy-cool-etc">here</a> is one post but it doesn't solve my problem.</p>
| 7
|
2009-02-27T06:10:16Z
| 593,932
|
<p>You are going to have to decide what you want to show them. If you want to show them how to using a computer can be a useful tool in mathematics show them sage and how you can perform numerical methods with it to get answers to hard questions. Then manipulate some algebraic formulas with it. Maybe show how it can whip through hard integrals and derivatives without sweating. They will be nearing the end of some of their first calulus courses after all.</p>
<p>None of this displays why they need to know how to program of course. This just shows how useful other people's programming is for them to use. While you do have the full power of python in sage the reality is the odd "for loop" and some "if statements" is really all of the programming most mathematicians will do with sage most of the time (though there is a significant minority who will do a lot more). If you want to go down this road I would suggest you try to get your hands on one of the Experimental mathematics books(<a href="http://www.experimentalmath.info/" rel="nofollow">http://www.experimentalmath.info/</a>). These are the guys who (amongst many other interesting results) came up with BBP numbers: which is the way to find arbitrary digits of pi. They mostly use maple and mathematica but most of this work translates to sage.</p>
<p>I would strongly suggest you don't show them how to actually implement numerical methods themselves. Very few mathematicians are writing programs to solve numerical problems. Most just plug their programs into other people's programs. So I don't think showing how they could implement these methods themselves, if only they knew how to program, will excite anyone.</p>
<p>If this were me I think I would probably give a seminar building a simple game plugin for cgsuite (<a href="http://cgsuite.sourceforge.net/" rel="nofollow">http://cgsuite.sourceforge.net/</a>). I recognize that this is java and not python but their are a lot of advantages to this approach. First young mathematicians always get excited by combinatorial game theory. You are fundamentally showing them how they can use math to always win at certain games. It's like you are giving them a super power.</p>
<p>Second, you are implementing the rules of a game in a program. Game rules are great ways to learn programming idioms because they translate so directly into programming concepts.</p>
<p>And finally, you end up with a tool that can play your game perfectly. 90 minutes is a long time for a seminar as far as I'm concerned. If you can end on a bang, like with 10 minutes of playing a game against a computer, they will leave excited instead of bored and drained.</p>
| 1
|
2009-02-27T08:10:34Z
|
[
"python",
"math"
] |
Python for mathematics students?
| 593,685
|
<p>I need to deliver one and half hour seminar on programming for students at the department of mathematics. </p>
<p>I have chosen python as language.</p>
<ol>
<li>What should be content of my presentation ?</li>
<li>What are good resources available ?</li>
<li>What is necessity of programming for maths students?</li>
<li>How will knowledge of programming will help them?</li>
</ol>
<p>Thank you !!!</p>
<p>NOTE: I know <a href="http://stackoverflow.com/questions/488502/best-language-to-program-some-math-free-fast-easy-cool-etc">here</a> is one post but it doesn't solve my problem.</p>
| 7
|
2009-02-27T06:10:16Z
| 593,973
|
<p>I would recommend solving a few different kinds of problems from Project Euler in Python and having a discussion about the solutions, how they could have been done differently to be more efficient, etc. as part of the seminar. Python is a very elegant language for solving mathematical problems and should be one of those easier understood than most by mathematics students, so I think you made a good choice there. </p>
| 1
|
2009-02-27T08:34:15Z
|
[
"python",
"math"
] |
Python for mathematics students?
| 593,685
|
<p>I need to deliver one and half hour seminar on programming for students at the department of mathematics. </p>
<p>I have chosen python as language.</p>
<ol>
<li>What should be content of my presentation ?</li>
<li>What are good resources available ?</li>
<li>What is necessity of programming for maths students?</li>
<li>How will knowledge of programming will help them?</li>
</ol>
<p>Thank you !!!</p>
<p>NOTE: I know <a href="http://stackoverflow.com/questions/488502/best-language-to-program-some-math-free-fast-easy-cool-etc">here</a> is one post but it doesn't solve my problem.</p>
| 7
|
2009-02-27T06:10:16Z
| 600,499
|
<p><a href="http://www.sagemath.org" rel="nofollow">http://www.sagemath.org</a></p>
<p>In our wiki is a collection of talks, they may help you! <a href="http://wiki.sagemath.org/Talks" rel="nofollow">http://wiki.sagemath.org/Talks</a></p>
<p>Also be aware, that Sage contains NumPy, SciPy and SymPy. Therefore all information about these three python libraries hold for Sage. </p>
| 0
|
2009-03-01T20:55:49Z
|
[
"python",
"math"
] |
Python for mathematics students?
| 593,685
|
<p>I need to deliver one and half hour seminar on programming for students at the department of mathematics. </p>
<p>I have chosen python as language.</p>
<ol>
<li>What should be content of my presentation ?</li>
<li>What are good resources available ?</li>
<li>What is necessity of programming for maths students?</li>
<li>How will knowledge of programming will help them?</li>
</ol>
<p>Thank you !!!</p>
<p>NOTE: I know <a href="http://stackoverflow.com/questions/488502/best-language-to-program-some-math-free-fast-easy-cool-etc">here</a> is one post but it doesn't solve my problem.</p>
| 7
|
2009-02-27T06:10:16Z
| 641,395
|
<p>I would bring up using Python as a free & open source option to replace/augment expensive packages like Matlab, IDL, etc via:</p>
<ul>
<li>scipy - fft's, </li>
<li>ipython - "shell"/debugger</li>
<li>matplotlib - 2d graphing</li>
<li>MayaVi - 3d graphing/visualization</li>
</ul>
<p><a href="http://www.archive.org/details/Perez%5FPython%5FWorkshop%5F2008%5F10%5F09c" rel="nofollow">This video</a> may be helpful.</p>
| 2
|
2009-03-13T03:43:01Z
|
[
"python",
"math"
] |
How do I find images with a similar color using Python and PIL?
| 593,925
|
<p>I have a lot of images in a folder, and I would like to find images with a similar color to a pre chosen image.</p>
<p>I would like to be able to do something like: </p>
<pre><code>python find_similar.py sample.jpg
</code></pre>
<p>and have that return something like:</p>
<pre><code>234324.jpg
55.jpg
9945.jpg
345434.jpg
104.jpg
</code></pre>
<p>Is this doable?</p>
| 3
|
2009-02-27T08:07:21Z
| 593,936
|
<p>The algorithm for finding similar images is discussed in a <a href="http://stackoverflow.com/questions/75891/algorithm-for-finding-similar-images">Question on Stackoverflow</a>, you might want to implement one of those in Python & PIL.</p>
<p>Also, you can straightaway use the <code>ImageChops</code> module from PIL and use the <code>difference</code> method to compare two images like this:</p>
<pre><code>import Image
import ImageChops
im1 = Image.open("original.jpg")
im2 = Image.open("sample.jpg")
diff = ImageChops.difference(im2, im1)
</code></pre>
<p>That might help you in getting some idea about the difference in your original image and the others.</p>
<p>There is another <a href="http://stackoverflow.com/questions/189943/how-can-i-quantify-difference-between-two-images">similar question on Stackoverflow</a> which discusses this.</p>
| 1
|
2009-02-27T08:13:04Z
|
[
"python",
"image-processing",
"python-imaging-library"
] |
How do I find images with a similar color using Python and PIL?
| 593,925
|
<p>I have a lot of images in a folder, and I would like to find images with a similar color to a pre chosen image.</p>
<p>I would like to be able to do something like: </p>
<pre><code>python find_similar.py sample.jpg
</code></pre>
<p>and have that return something like:</p>
<pre><code>234324.jpg
55.jpg
9945.jpg
345434.jpg
104.jpg
</code></pre>
<p>Is this doable?</p>
| 3
|
2009-02-27T08:07:21Z
| 593,958
|
<p>I cannot give you a canned solution, but here's an angle to tackle the problem. It's not PIL-specific, and it might be entirely bogus, since I have no experience in image processing.</p>
<ol>
<li><p>Perform <a href="http://en.wikipedia.org/wiki/Color%5Fquantization" rel="nofollow">color quantization</a> on the image. That gives you a palette that encodes the color information in the image without any shape information.</p></li>
<li><p>Run a <a href="http://en.wikipedia.org/wiki/Principal%5Fcomponents%5Fanalysis" rel="nofollow">principal components analysis</a> to get the dominant components in the color cube. Strictly, you could run this without quantization first, but it might be too expensive.</p></li>
<li><p>Do a least-squares fitting on the principal components of different images.</p></li>
</ol>
<p>Hope this helps.</p>
| 4
|
2009-02-27T08:23:06Z
|
[
"python",
"image-processing",
"python-imaging-library"
] |
Equation parsing in Python
| 594,266
|
<p>How can I (easily) take a string such as <code>"sin(x)*x^2"</code> which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of <code>x</code>? </p>
| 26
|
2009-02-27T10:42:07Z
| 594,292
|
<p><a href="http://www.sagemath.org/index.html" rel="nofollow">Sage</a> is intended as matlab replacement and in <a href="http://www.sagemath.org/help-video.html" rel="nofollow">intro videos</a> it's demonstrated how similar to yours cases are handled. They seem to be supporting a wide range of approaches. Since the code is open-source you could browse and see for yourself how the authors handle such cases.</p>
| 0
|
2009-02-27T10:50:39Z
|
[
"python",
"parsing",
"equation"
] |
Equation parsing in Python
| 594,266
|
<p>How can I (easily) take a string such as <code>"sin(x)*x^2"</code> which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of <code>x</code>? </p>
| 26
|
2009-02-27T10:42:07Z
| 594,294
|
<pre><code> f = parser.parse('sin(x)*x^2').to_pyfunc()
</code></pre>
<p>Where <code>parser</code> could be defined using PLY, pyparsing, builtin tokenizer, parser, ast.</p>
<p>Don't use <code>eval</code> on user input.</p>
| 9
|
2009-02-27T10:51:37Z
|
[
"python",
"parsing",
"equation"
] |
Equation parsing in Python
| 594,266
|
<p>How can I (easily) take a string such as <code>"sin(x)*x^2"</code> which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of <code>x</code>? </p>
| 26
|
2009-02-27T10:42:07Z
| 594,360
|
<p>Python's own internal compiler can parse this, if you use Python notation.</p>
<p>If your change the notation slightly, you'll be happier.</p>
<pre><code>import compiler
eq= "sin(x)*x**2"
ast= compiler.parse( eq )
</code></pre>
<p>You get an abstract syntax tree that you can work with.</p>
| 37
|
2009-02-27T11:12:34Z
|
[
"python",
"parsing",
"equation"
] |
Equation parsing in Python
| 594,266
|
<p>How can I (easily) take a string such as <code>"sin(x)*x^2"</code> which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of <code>x</code>? </p>
| 26
|
2009-02-27T10:42:07Z
| 594,457
|
<p>To emphasize J.F. Sebastian's advice, 'eval' and even the 'compiler' solutions can be open to subtle security holes. How trustworthy is the input? With 'compiler' you can at least filter out things like getattr lookups from the AST, but I've found it's easier to use PLY or pyparsing for this sort of thing than it is to secure the result of letting Python help out.</p>
<p>Also, 'compiler' is clumsy and hard to use. It's deprecated and removed in 3.0. You should use the 'ast' module (added in 2.6, available in 2.5 as '_ast').</p>
| 2
|
2009-02-27T11:57:10Z
|
[
"python",
"parsing",
"equation"
] |
Equation parsing in Python
| 594,266
|
<p>How can I (easily) take a string such as <code>"sin(x)*x^2"</code> which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of <code>x</code>? </p>
| 26
|
2009-02-27T10:42:07Z
| 2,537,560
|
<p>In agreement with vartec. I would use SymPy - in particular the lambdify function should do exactly what you want.</p>
<p>See: <a href="http://showmedo.com/videotutorials/video?name=7200080&fromSeriesID=720" rel="nofollow">http://showmedo.com/videotutorials/video?name=7200080&fromSeriesID=720</a></p>
<p>for a very nice explanation of this.</p>
<p>Best wishes,</p>
| 0
|
2010-03-29T11:44:17Z
|
[
"python",
"parsing",
"equation"
] |
Equation parsing in Python
| 594,266
|
<p>How can I (easily) take a string such as <code>"sin(x)*x^2"</code> which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of <code>x</code>? </p>
| 26
|
2009-02-27T10:42:07Z
| 2,537,691
|
<p>pyparsing might do what you want (http://pyparsing.wikispaces.com/) especially if the strings are from an untrusted source.</p>
<p>See also <a href="http://pyparsing.wikispaces.com/file/view/fourFn.py">http://pyparsing.wikispaces.com/file/view/fourFn.py</a> for a fairly full-featured calculator built with it.</p>
| 7
|
2010-03-29T12:11:39Z
|
[
"python",
"parsing",
"equation"
] |
Equation parsing in Python
| 594,266
|
<p>How can I (easily) take a string such as <code>"sin(x)*x^2"</code> which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of <code>x</code>? </p>
| 26
|
2009-02-27T10:42:07Z
| 5,936,822
|
<p>You can use Python <code>parser</code>:</p>
<pre><code>import parser
formula = "sin(x)*x**2"
code = parser.expr(formula).compile()
from math import sin
x = 10
print eval(code)
</code></pre>
<p>It performs better than pure <code>eval</code>.</p>
| 18
|
2011-05-09T12:23:11Z
|
[
"python",
"parsing",
"equation"
] |
Choosing between different switch-case replacements in Python - dictionary or if-elif-else?
| 594,442
|
<p>I recently read the questions that recommend against using switch-case statements in languages that do support it. As far as Python goes, I've seen a number of switch case replacements, such as: </p>
<ol>
<li>Using a dictionary (Many variants) </li>
<li>Using a Tuple </li>
<li>Using a function decorator (<a href="http://code.activestate.com/recipes/440499/">http://code.activestate.com/recipes/440499/</a>) </li>
<li>Using Polymorphism (Recommended method instead of type checking objects) </li>
<li>Using an if-elif-else ladder </li>
<li>Someone even recommended the Visitor pattern (Possibly Extrinsic) </li>
</ol>
<p>Given the wide variety of options, I am having a bit of difficulty deciding what to do for a particular piece of code. I would like to learn the criteria for selecting one of these methods over the other in general. In addition, I would appreciate advice on what to do in the specific cases where I am having trouble deciding (with an explanation of the choice).</p>
<p>Here is the specific problem:<br />
(1) </p>
<pre><code>def _setCurrentCurve(self, curve):
if curve == "sine":
self.currentCurve = SineCurve(startAngle = 0, endAngle = 14,
lineColor = (0.0, 0.0, 0.0), expansionFactor = 1,
centerPos = (0.0, 0.0))
elif curve == "quadratic":
self.currentCurve = QuadraticCurve(lineColor = (0.0, 0.0, 0.0))
</code></pre>
<p>This method is called by a <strong>qt-slot</strong> in response to choosing to draw a curve from a menu. The above method will contain a total of 4-7 curves once the application is complete. Is it justified to use a throw away dictionary in this case? Since the most obvious way to do this is if-elif-else, should I stick with that? I have also consider using **kargs here (with a friends help) since all the curve classes use **kargs...</p>
<p>(2)<br />
This second piece of code is a <strong>qt-slot</strong> that is called when the user changes a property of a curve. Basically the slot takes the data from the gui (spinBox) and puts it in an instance variable of the appropriate curve class. In this case, I again have the same question - should I use a dict?</p>
<p>Here is the aforementioned slot- </p>
<pre><code>def propertyChanged(self, name, value):
"""A Qt slot, to react to changes of SineCurve's properties."""
if name == "amplitude":
self.amplitude = value
elif name == "expansionFactor":
self.expansionFactor = value
elif name == "startAngle":
self.startAngle = value
elif name == "endAngle":
self.endAngle = value
</code></pre>
<p>For reference, here is the code for connecting to the above slot - </p>
<pre><code>def _connectToPage(self, page):
for connectionData in page.getConnectibles():
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
lambda value, name = connectionData["property"]:\
self.currentCurve.propertyChanged(name, value))
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
self.hackedDisplayArea.update)
</code></pre>
<p><strong>Note</strong> - The self.endAngle etc. are initialized in the constructor.</p>
<p>As far as I know, the reasons for choosing a dict is for fast lookup. When is that warranted? when I have 100 cases or more? Is it a good idea to keep building and throwing away a dictionary each time the function is called? If I build a dict for this purpose outside a function, should I check If it is needed elswhere? What happens if it is not needed elsewhere?</p>
<p>My question is what is the best-practice if there is one? What is the best/most elegant way to go about things? Put in yet another way, when to use <strong>if-elif-else</strong>, when to use each of the other options?</p>
| 15
|
2009-02-27T11:47:51Z
| 594,532
|
<p>In the first example I would certainly stick with the if-else statement. In fact I don't see a reason not to use if-else unless</p>
<ol>
<li><p>You find (using e.g. the profile module) that the if statement is a bottleneck (very unlikely IMO unless you have a huge number of cases that do very little)</p></li>
<li><p>The code using a dictionary is clearer / has less repetition. </p></li>
</ol>
<p>Your second example I would actually rewrite</p>
<pre><code>setattr(self, name, value)
</code></pre>
<p>(probably adding an assert statement to catch invalid names).</p>
| 8
|
2009-02-27T12:21:10Z
|
[
"python",
"switch-statement"
] |
Choosing between different switch-case replacements in Python - dictionary or if-elif-else?
| 594,442
|
<p>I recently read the questions that recommend against using switch-case statements in languages that do support it. As far as Python goes, I've seen a number of switch case replacements, such as: </p>
<ol>
<li>Using a dictionary (Many variants) </li>
<li>Using a Tuple </li>
<li>Using a function decorator (<a href="http://code.activestate.com/recipes/440499/">http://code.activestate.com/recipes/440499/</a>) </li>
<li>Using Polymorphism (Recommended method instead of type checking objects) </li>
<li>Using an if-elif-else ladder </li>
<li>Someone even recommended the Visitor pattern (Possibly Extrinsic) </li>
</ol>
<p>Given the wide variety of options, I am having a bit of difficulty deciding what to do for a particular piece of code. I would like to learn the criteria for selecting one of these methods over the other in general. In addition, I would appreciate advice on what to do in the specific cases where I am having trouble deciding (with an explanation of the choice).</p>
<p>Here is the specific problem:<br />
(1) </p>
<pre><code>def _setCurrentCurve(self, curve):
if curve == "sine":
self.currentCurve = SineCurve(startAngle = 0, endAngle = 14,
lineColor = (0.0, 0.0, 0.0), expansionFactor = 1,
centerPos = (0.0, 0.0))
elif curve == "quadratic":
self.currentCurve = QuadraticCurve(lineColor = (0.0, 0.0, 0.0))
</code></pre>
<p>This method is called by a <strong>qt-slot</strong> in response to choosing to draw a curve from a menu. The above method will contain a total of 4-7 curves once the application is complete. Is it justified to use a throw away dictionary in this case? Since the most obvious way to do this is if-elif-else, should I stick with that? I have also consider using **kargs here (with a friends help) since all the curve classes use **kargs...</p>
<p>(2)<br />
This second piece of code is a <strong>qt-slot</strong> that is called when the user changes a property of a curve. Basically the slot takes the data from the gui (spinBox) and puts it in an instance variable of the appropriate curve class. In this case, I again have the same question - should I use a dict?</p>
<p>Here is the aforementioned slot- </p>
<pre><code>def propertyChanged(self, name, value):
"""A Qt slot, to react to changes of SineCurve's properties."""
if name == "amplitude":
self.amplitude = value
elif name == "expansionFactor":
self.expansionFactor = value
elif name == "startAngle":
self.startAngle = value
elif name == "endAngle":
self.endAngle = value
</code></pre>
<p>For reference, here is the code for connecting to the above slot - </p>
<pre><code>def _connectToPage(self, page):
for connectionData in page.getConnectibles():
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
lambda value, name = connectionData["property"]:\
self.currentCurve.propertyChanged(name, value))
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
self.hackedDisplayArea.update)
</code></pre>
<p><strong>Note</strong> - The self.endAngle etc. are initialized in the constructor.</p>
<p>As far as I know, the reasons for choosing a dict is for fast lookup. When is that warranted? when I have 100 cases or more? Is it a good idea to keep building and throwing away a dictionary each time the function is called? If I build a dict for this purpose outside a function, should I check If it is needed elswhere? What happens if it is not needed elsewhere?</p>
<p>My question is what is the best-practice if there is one? What is the best/most elegant way to go about things? Put in yet another way, when to use <strong>if-elif-else</strong>, when to use each of the other options?</p>
| 15
|
2009-02-27T11:47:51Z
| 594,539
|
<p>Each of the exposed options fit well some scenarios:</p>
<ol>
<li>if-elif-else: simplicity, clarity</li>
<li>dictionary: useful when you configure it dynamically (imagine that you need a particular functionality to be executed on a branch)</li>
<li>tuple: simplicity over if-else case for multiple choices per branch.</li>
<li>polymorphism: automatic object oriented branching</li>
<li>etc.</li>
</ol>
<p>Python is about readability and consistency and even if your decision will always be a subjective and it will depend on your style, you should always think about Python mantras.</p>
<p>./alex</p>
| 1
|
2009-02-27T12:23:10Z
|
[
"python",
"switch-statement"
] |
Choosing between different switch-case replacements in Python - dictionary or if-elif-else?
| 594,442
|
<p>I recently read the questions that recommend against using switch-case statements in languages that do support it. As far as Python goes, I've seen a number of switch case replacements, such as: </p>
<ol>
<li>Using a dictionary (Many variants) </li>
<li>Using a Tuple </li>
<li>Using a function decorator (<a href="http://code.activestate.com/recipes/440499/">http://code.activestate.com/recipes/440499/</a>) </li>
<li>Using Polymorphism (Recommended method instead of type checking objects) </li>
<li>Using an if-elif-else ladder </li>
<li>Someone even recommended the Visitor pattern (Possibly Extrinsic) </li>
</ol>
<p>Given the wide variety of options, I am having a bit of difficulty deciding what to do for a particular piece of code. I would like to learn the criteria for selecting one of these methods over the other in general. In addition, I would appreciate advice on what to do in the specific cases where I am having trouble deciding (with an explanation of the choice).</p>
<p>Here is the specific problem:<br />
(1) </p>
<pre><code>def _setCurrentCurve(self, curve):
if curve == "sine":
self.currentCurve = SineCurve(startAngle = 0, endAngle = 14,
lineColor = (0.0, 0.0, 0.0), expansionFactor = 1,
centerPos = (0.0, 0.0))
elif curve == "quadratic":
self.currentCurve = QuadraticCurve(lineColor = (0.0, 0.0, 0.0))
</code></pre>
<p>This method is called by a <strong>qt-slot</strong> in response to choosing to draw a curve from a menu. The above method will contain a total of 4-7 curves once the application is complete. Is it justified to use a throw away dictionary in this case? Since the most obvious way to do this is if-elif-else, should I stick with that? I have also consider using **kargs here (with a friends help) since all the curve classes use **kargs...</p>
<p>(2)<br />
This second piece of code is a <strong>qt-slot</strong> that is called when the user changes a property of a curve. Basically the slot takes the data from the gui (spinBox) and puts it in an instance variable of the appropriate curve class. In this case, I again have the same question - should I use a dict?</p>
<p>Here is the aforementioned slot- </p>
<pre><code>def propertyChanged(self, name, value):
"""A Qt slot, to react to changes of SineCurve's properties."""
if name == "amplitude":
self.amplitude = value
elif name == "expansionFactor":
self.expansionFactor = value
elif name == "startAngle":
self.startAngle = value
elif name == "endAngle":
self.endAngle = value
</code></pre>
<p>For reference, here is the code for connecting to the above slot - </p>
<pre><code>def _connectToPage(self, page):
for connectionData in page.getConnectibles():
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
lambda value, name = connectionData["property"]:\
self.currentCurve.propertyChanged(name, value))
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
self.hackedDisplayArea.update)
</code></pre>
<p><strong>Note</strong> - The self.endAngle etc. are initialized in the constructor.</p>
<p>As far as I know, the reasons for choosing a dict is for fast lookup. When is that warranted? when I have 100 cases or more? Is it a good idea to keep building and throwing away a dictionary each time the function is called? If I build a dict for this purpose outside a function, should I check If it is needed elswhere? What happens if it is not needed elsewhere?</p>
<p>My question is what is the best-practice if there is one? What is the best/most elegant way to go about things? Put in yet another way, when to use <strong>if-elif-else</strong>, when to use each of the other options?</p>
| 15
|
2009-02-27T11:47:51Z
| 594,547
|
<p>I agree with df regarding the second example. The first example I would probably try to rewrite using a dictionary, particularly if all the curve constructors have the same type signature (perhaps using *args and/or **kwargs). Something like</p>
<pre><code>def _setCurrentCurve(self, new_curve):
self.currentCurve = self.preset_curves[new_curve](options_here)
</code></pre>
<p>or perhaps even</p>
<pre><code>def _setCurrentCurve(self, new_curve):
self.currentCurve = self.preset_curves[new_curve](**preset_curve_defaults[new_curve])
</code></pre>
| 1
|
2009-02-27T12:27:03Z
|
[
"python",
"switch-statement"
] |
Choosing between different switch-case replacements in Python - dictionary or if-elif-else?
| 594,442
|
<p>I recently read the questions that recommend against using switch-case statements in languages that do support it. As far as Python goes, I've seen a number of switch case replacements, such as: </p>
<ol>
<li>Using a dictionary (Many variants) </li>
<li>Using a Tuple </li>
<li>Using a function decorator (<a href="http://code.activestate.com/recipes/440499/">http://code.activestate.com/recipes/440499/</a>) </li>
<li>Using Polymorphism (Recommended method instead of type checking objects) </li>
<li>Using an if-elif-else ladder </li>
<li>Someone even recommended the Visitor pattern (Possibly Extrinsic) </li>
</ol>
<p>Given the wide variety of options, I am having a bit of difficulty deciding what to do for a particular piece of code. I would like to learn the criteria for selecting one of these methods over the other in general. In addition, I would appreciate advice on what to do in the specific cases where I am having trouble deciding (with an explanation of the choice).</p>
<p>Here is the specific problem:<br />
(1) </p>
<pre><code>def _setCurrentCurve(self, curve):
if curve == "sine":
self.currentCurve = SineCurve(startAngle = 0, endAngle = 14,
lineColor = (0.0, 0.0, 0.0), expansionFactor = 1,
centerPos = (0.0, 0.0))
elif curve == "quadratic":
self.currentCurve = QuadraticCurve(lineColor = (0.0, 0.0, 0.0))
</code></pre>
<p>This method is called by a <strong>qt-slot</strong> in response to choosing to draw a curve from a menu. The above method will contain a total of 4-7 curves once the application is complete. Is it justified to use a throw away dictionary in this case? Since the most obvious way to do this is if-elif-else, should I stick with that? I have also consider using **kargs here (with a friends help) since all the curve classes use **kargs...</p>
<p>(2)<br />
This second piece of code is a <strong>qt-slot</strong> that is called when the user changes a property of a curve. Basically the slot takes the data from the gui (spinBox) and puts it in an instance variable of the appropriate curve class. In this case, I again have the same question - should I use a dict?</p>
<p>Here is the aforementioned slot- </p>
<pre><code>def propertyChanged(self, name, value):
"""A Qt slot, to react to changes of SineCurve's properties."""
if name == "amplitude":
self.amplitude = value
elif name == "expansionFactor":
self.expansionFactor = value
elif name == "startAngle":
self.startAngle = value
elif name == "endAngle":
self.endAngle = value
</code></pre>
<p>For reference, here is the code for connecting to the above slot - </p>
<pre><code>def _connectToPage(self, page):
for connectionData in page.getConnectibles():
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
lambda value, name = connectionData["property"]:\
self.currentCurve.propertyChanged(name, value))
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
self.hackedDisplayArea.update)
</code></pre>
<p><strong>Note</strong> - The self.endAngle etc. are initialized in the constructor.</p>
<p>As far as I know, the reasons for choosing a dict is for fast lookup. When is that warranted? when I have 100 cases or more? Is it a good idea to keep building and throwing away a dictionary each time the function is called? If I build a dict for this purpose outside a function, should I check If it is needed elswhere? What happens if it is not needed elsewhere?</p>
<p>My question is what is the best-practice if there is one? What is the best/most elegant way to go about things? Put in yet another way, when to use <strong>if-elif-else</strong>, when to use each of the other options?</p>
| 15
|
2009-02-27T11:47:51Z
| 594,550
|
<p>Considering that this is done in response to a user action (pickings something from a menu), and the number of choices you anticipate is very small, I'd definitely go with a simple if-elif-else ladder.</p>
<p>There's no point in optinizing for speed, since it only happens as fast as the user can make the selection anyway, this is not "inner loop of a raytracer"-territory. Sure, it matters to give the user quick feedback, but since the number of cases is so small, there is no danger of that either.</p>
<p>There's no point in optimizing for conciseness, since the (imo clearer, zero-readability-overhead) if-ladder will be so very short anyway.</p>
| 2
|
2009-02-27T12:27:13Z
|
[
"python",
"switch-statement"
] |
Choosing between different switch-case replacements in Python - dictionary or if-elif-else?
| 594,442
|
<p>I recently read the questions that recommend against using switch-case statements in languages that do support it. As far as Python goes, I've seen a number of switch case replacements, such as: </p>
<ol>
<li>Using a dictionary (Many variants) </li>
<li>Using a Tuple </li>
<li>Using a function decorator (<a href="http://code.activestate.com/recipes/440499/">http://code.activestate.com/recipes/440499/</a>) </li>
<li>Using Polymorphism (Recommended method instead of type checking objects) </li>
<li>Using an if-elif-else ladder </li>
<li>Someone even recommended the Visitor pattern (Possibly Extrinsic) </li>
</ol>
<p>Given the wide variety of options, I am having a bit of difficulty deciding what to do for a particular piece of code. I would like to learn the criteria for selecting one of these methods over the other in general. In addition, I would appreciate advice on what to do in the specific cases where I am having trouble deciding (with an explanation of the choice).</p>
<p>Here is the specific problem:<br />
(1) </p>
<pre><code>def _setCurrentCurve(self, curve):
if curve == "sine":
self.currentCurve = SineCurve(startAngle = 0, endAngle = 14,
lineColor = (0.0, 0.0, 0.0), expansionFactor = 1,
centerPos = (0.0, 0.0))
elif curve == "quadratic":
self.currentCurve = QuadraticCurve(lineColor = (0.0, 0.0, 0.0))
</code></pre>
<p>This method is called by a <strong>qt-slot</strong> in response to choosing to draw a curve from a menu. The above method will contain a total of 4-7 curves once the application is complete. Is it justified to use a throw away dictionary in this case? Since the most obvious way to do this is if-elif-else, should I stick with that? I have also consider using **kargs here (with a friends help) since all the curve classes use **kargs...</p>
<p>(2)<br />
This second piece of code is a <strong>qt-slot</strong> that is called when the user changes a property of a curve. Basically the slot takes the data from the gui (spinBox) and puts it in an instance variable of the appropriate curve class. In this case, I again have the same question - should I use a dict?</p>
<p>Here is the aforementioned slot- </p>
<pre><code>def propertyChanged(self, name, value):
"""A Qt slot, to react to changes of SineCurve's properties."""
if name == "amplitude":
self.amplitude = value
elif name == "expansionFactor":
self.expansionFactor = value
elif name == "startAngle":
self.startAngle = value
elif name == "endAngle":
self.endAngle = value
</code></pre>
<p>For reference, here is the code for connecting to the above slot - </p>
<pre><code>def _connectToPage(self, page):
for connectionData in page.getConnectibles():
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
lambda value, name = connectionData["property"]:\
self.currentCurve.propertyChanged(name, value))
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
self.hackedDisplayArea.update)
</code></pre>
<p><strong>Note</strong> - The self.endAngle etc. are initialized in the constructor.</p>
<p>As far as I know, the reasons for choosing a dict is for fast lookup. When is that warranted? when I have 100 cases or more? Is it a good idea to keep building and throwing away a dictionary each time the function is called? If I build a dict for this purpose outside a function, should I check If it is needed elswhere? What happens if it is not needed elsewhere?</p>
<p>My question is what is the best-practice if there is one? What is the best/most elegant way to go about things? Put in yet another way, when to use <strong>if-elif-else</strong>, when to use each of the other options?</p>
| 15
|
2009-02-27T11:47:51Z
| 594,574
|
<p>Regarding your dictionary questions:</p>
<blockquote>
<p>As far as I know, the reasons for choosing a dict is for fast lookup. When is that warranted? when I have 100 cases or more? Is it a good idea to keep building and throwing away a dictionary each time the function is called? If I build a dict for this purpose outside a function, should I check If it is needed elswhere? What happens if it is not needed elsewhere?</p>
</blockquote>
<ol>
<li><p>Another issue is maintainability. Having the string->curveFunction dictionary allows you to data-drive the menu. Then adding another option is just a matter of putting another string->function entry in the dictionary (which lives in a part of the code dedicated to configuration.</p></li>
<li><p>Even if you have only a few entries, it "separates concerns"; <code>_setCurrentCurve</code> is responsible for wiring up at run time, not defining the box of components.</p></li>
<li><p>Build the dictionary and hold onto it.</p></li>
<li><p>Even if it's not used elsewhere, you get the above benefits (locatability, maintainability).</p></li>
</ol>
<p>My rule of thumb is to ask "What's going on here?" for each component of my code. If the answer is of the form</p>
<blockquote>
<p>... <strong>and</strong> ... <strong>and</strong> ...</p>
</blockquote>
<p>(as in "defining the library of functions <strong>and</strong> associating each with a value in the menu") then there are some concerns begging to be separated.</p>
| 2
|
2009-02-27T12:35:44Z
|
[
"python",
"switch-statement"
] |
Choosing between different switch-case replacements in Python - dictionary or if-elif-else?
| 594,442
|
<p>I recently read the questions that recommend against using switch-case statements in languages that do support it. As far as Python goes, I've seen a number of switch case replacements, such as: </p>
<ol>
<li>Using a dictionary (Many variants) </li>
<li>Using a Tuple </li>
<li>Using a function decorator (<a href="http://code.activestate.com/recipes/440499/">http://code.activestate.com/recipes/440499/</a>) </li>
<li>Using Polymorphism (Recommended method instead of type checking objects) </li>
<li>Using an if-elif-else ladder </li>
<li>Someone even recommended the Visitor pattern (Possibly Extrinsic) </li>
</ol>
<p>Given the wide variety of options, I am having a bit of difficulty deciding what to do for a particular piece of code. I would like to learn the criteria for selecting one of these methods over the other in general. In addition, I would appreciate advice on what to do in the specific cases where I am having trouble deciding (with an explanation of the choice).</p>
<p>Here is the specific problem:<br />
(1) </p>
<pre><code>def _setCurrentCurve(self, curve):
if curve == "sine":
self.currentCurve = SineCurve(startAngle = 0, endAngle = 14,
lineColor = (0.0, 0.0, 0.0), expansionFactor = 1,
centerPos = (0.0, 0.0))
elif curve == "quadratic":
self.currentCurve = QuadraticCurve(lineColor = (0.0, 0.0, 0.0))
</code></pre>
<p>This method is called by a <strong>qt-slot</strong> in response to choosing to draw a curve from a menu. The above method will contain a total of 4-7 curves once the application is complete. Is it justified to use a throw away dictionary in this case? Since the most obvious way to do this is if-elif-else, should I stick with that? I have also consider using **kargs here (with a friends help) since all the curve classes use **kargs...</p>
<p>(2)<br />
This second piece of code is a <strong>qt-slot</strong> that is called when the user changes a property of a curve. Basically the slot takes the data from the gui (spinBox) and puts it in an instance variable of the appropriate curve class. In this case, I again have the same question - should I use a dict?</p>
<p>Here is the aforementioned slot- </p>
<pre><code>def propertyChanged(self, name, value):
"""A Qt slot, to react to changes of SineCurve's properties."""
if name == "amplitude":
self.amplitude = value
elif name == "expansionFactor":
self.expansionFactor = value
elif name == "startAngle":
self.startAngle = value
elif name == "endAngle":
self.endAngle = value
</code></pre>
<p>For reference, here is the code for connecting to the above slot - </p>
<pre><code>def _connectToPage(self, page):
for connectionData in page.getConnectibles():
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
lambda value, name = connectionData["property"]:\
self.currentCurve.propertyChanged(name, value))
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
self.hackedDisplayArea.update)
</code></pre>
<p><strong>Note</strong> - The self.endAngle etc. are initialized in the constructor.</p>
<p>As far as I know, the reasons for choosing a dict is for fast lookup. When is that warranted? when I have 100 cases or more? Is it a good idea to keep building and throwing away a dictionary each time the function is called? If I build a dict for this purpose outside a function, should I check If it is needed elswhere? What happens if it is not needed elsewhere?</p>
<p>My question is what is the best-practice if there is one? What is the best/most elegant way to go about things? Put in yet another way, when to use <strong>if-elif-else</strong>, when to use each of the other options?</p>
| 15
|
2009-02-27T11:47:51Z
| 594,622
|
<p>Sigh. Too much hand-wringing over the wrong part of the problem. The switch statement is not the issue. There are many ways of expressing "alternative" that don't add <strong>meaning</strong>.</p>
<p>The issue is <strong>meaning</strong> -- not technical statement choices. </p>
<p>There are three common patterns.</p>
<ul>
<li><p><strong>Mapping a key to an object</strong>. Use a dictionary if it is almost totally static and you have a mapping between a simple key and another more complex thing. Building a dictionary on the fly each time you need it is silly. You can use this if it's what you <strong>mean</strong>: your "conditions" are simple, static key values that map to objects.</p></li>
<li><p><strong>Variant behavior among subclasses</strong>. Use Polymorphism instead of type checking objects. Correct. If you have similar objects in multiple classes with variant behavior, they should be polymorphic. Use this as often as possible.</p></li>
<li><p><strong>Other variant behavior</strong>. Use an if-elif-else ladder. Use this when you don't have largely static key-to-value mapping. Use this when the conditions are complex, or you <strong>mean</strong> procedures, not objects.</p></li>
</ul>
<p>Everything else is just tricky code that can achieve similar results.</p>
<p>Using a Tuple. This is just dictionary without the mapping. This requires search, and search should be avoided whenever possible. Don't do this, it's inefficient. Use a dictionary.</p>
<p>Using a function decorator (<a href="http://code.activestate.com/recipes/440499/">http://code.activestate.com/recipes/440499/</a>). Icky. This conceals the if-elif-elif nature of the problem you're solving. Don't do this, it isn't obvious that the choices are <em>exclusive</em>. Use anything else.</p>
<p>Someone even recommended the <strong>Visitor</strong> pattern. Use this when you have an object which follows the <strong>Composite</strong> design pattern. This depends on polymorphism to work, so it's not really a different solution.</p>
| 22
|
2009-02-27T12:51:21Z
|
[
"python",
"switch-statement"
] |
Choosing between different switch-case replacements in Python - dictionary or if-elif-else?
| 594,442
|
<p>I recently read the questions that recommend against using switch-case statements in languages that do support it. As far as Python goes, I've seen a number of switch case replacements, such as: </p>
<ol>
<li>Using a dictionary (Many variants) </li>
<li>Using a Tuple </li>
<li>Using a function decorator (<a href="http://code.activestate.com/recipes/440499/">http://code.activestate.com/recipes/440499/</a>) </li>
<li>Using Polymorphism (Recommended method instead of type checking objects) </li>
<li>Using an if-elif-else ladder </li>
<li>Someone even recommended the Visitor pattern (Possibly Extrinsic) </li>
</ol>
<p>Given the wide variety of options, I am having a bit of difficulty deciding what to do for a particular piece of code. I would like to learn the criteria for selecting one of these methods over the other in general. In addition, I would appreciate advice on what to do in the specific cases where I am having trouble deciding (with an explanation of the choice).</p>
<p>Here is the specific problem:<br />
(1) </p>
<pre><code>def _setCurrentCurve(self, curve):
if curve == "sine":
self.currentCurve = SineCurve(startAngle = 0, endAngle = 14,
lineColor = (0.0, 0.0, 0.0), expansionFactor = 1,
centerPos = (0.0, 0.0))
elif curve == "quadratic":
self.currentCurve = QuadraticCurve(lineColor = (0.0, 0.0, 0.0))
</code></pre>
<p>This method is called by a <strong>qt-slot</strong> in response to choosing to draw a curve from a menu. The above method will contain a total of 4-7 curves once the application is complete. Is it justified to use a throw away dictionary in this case? Since the most obvious way to do this is if-elif-else, should I stick with that? I have also consider using **kargs here (with a friends help) since all the curve classes use **kargs...</p>
<p>(2)<br />
This second piece of code is a <strong>qt-slot</strong> that is called when the user changes a property of a curve. Basically the slot takes the data from the gui (spinBox) and puts it in an instance variable of the appropriate curve class. In this case, I again have the same question - should I use a dict?</p>
<p>Here is the aforementioned slot- </p>
<pre><code>def propertyChanged(self, name, value):
"""A Qt slot, to react to changes of SineCurve's properties."""
if name == "amplitude":
self.amplitude = value
elif name == "expansionFactor":
self.expansionFactor = value
elif name == "startAngle":
self.startAngle = value
elif name == "endAngle":
self.endAngle = value
</code></pre>
<p>For reference, here is the code for connecting to the above slot - </p>
<pre><code>def _connectToPage(self, page):
for connectionData in page.getConnectibles():
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
lambda value, name = connectionData["property"]:\
self.currentCurve.propertyChanged(name, value))
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
self.hackedDisplayArea.update)
</code></pre>
<p><strong>Note</strong> - The self.endAngle etc. are initialized in the constructor.</p>
<p>As far as I know, the reasons for choosing a dict is for fast lookup. When is that warranted? when I have 100 cases or more? Is it a good idea to keep building and throwing away a dictionary each time the function is called? If I build a dict for this purpose outside a function, should I check If it is needed elswhere? What happens if it is not needed elsewhere?</p>
<p>My question is what is the best-practice if there is one? What is the best/most elegant way to go about things? Put in yet another way, when to use <strong>if-elif-else</strong>, when to use each of the other options?</p>
| 15
|
2009-02-27T11:47:51Z
| 594,707
|
<p>In Python, don't event think about how to replace a switch statement.</p>
<p>Use classes and polymorphism instead. Try to keep the information about each availble choice and how to implement it in one place (i.e. the class that implements it).</p>
<p>Otherwise you will end up having lots of places that each contain a tiny fraction of each choice, and updating/extending will be a maintenance nightmare. </p>
<p>This is exactly the kind of problem that OOD tries to solve by abstraction, information hiding, polymorphism and the lot.</p>
<p>Think about what classes of objects you have and their properties, then create an OO architecture around them. This way you will never ever have to worry about a missing "switch" statement again.</p>
| 1
|
2009-02-27T13:23:21Z
|
[
"python",
"switch-statement"
] |
Email body is a string sometimes and a list sometimes. Why?
| 594,545
|
<p>My application is written in python. What I am doing is I am running a script on each email received by postfix and do something with the email content. Procmail is responsible for running the script taking the email as input. The problem started when I was converting the input message(may be text) to email_message object(because the latter comes in handy). I am using email.message_from_string (where email is the default email module, comes with python).</p>
<pre>
<code>
import email
message = email.message_from_string(original_mail_content)
message_body = message.get_payload()
</code>
</pre>
<p>This message_body is sometimes returning a list[email.message.Message instance,email.message.Message instance] and sometime returning a string(actual body content of the incoming email). Why is it. And even I found one more observation. When I was browsing through the email.message.Message.get_payload() docstring, I found this..<br/>
"""
The payload will either be a list object or a string.If you mutate
the list object, you modify the message's payload in place.....""" </p>
<p>So how do I have generic method to get the body of email through python? Please help me out.</p>
| 7
|
2009-02-27T12:24:39Z
| 594,559
|
<p>It might be <a href="http://en.wikipedia.org/wiki/MIME#Multipart%5Fmessages" rel="nofollow">MIME multipart</a> </p>
<p>See <a href="http://docs.python.org/library/email.parser.html#additional-notes" rel="nofollow">http://docs.python.org/library/email.parser.html#additional-notes</a></p>
| 0
|
2009-02-27T12:30:42Z
|
[
"python",
"email",
"message",
"payload"
] |
Email body is a string sometimes and a list sometimes. Why?
| 594,545
|
<p>My application is written in python. What I am doing is I am running a script on each email received by postfix and do something with the email content. Procmail is responsible for running the script taking the email as input. The problem started when I was converting the input message(may be text) to email_message object(because the latter comes in handy). I am using email.message_from_string (where email is the default email module, comes with python).</p>
<pre>
<code>
import email
message = email.message_from_string(original_mail_content)
message_body = message.get_payload()
</code>
</pre>
<p>This message_body is sometimes returning a list[email.message.Message instance,email.message.Message instance] and sometime returning a string(actual body content of the incoming email). Why is it. And even I found one more observation. When I was browsing through the email.message.Message.get_payload() docstring, I found this..<br/>
"""
The payload will either be a list object or a string.If you mutate
the list object, you modify the message's payload in place.....""" </p>
<p>So how do I have generic method to get the body of email through python? Please help me out.</p>
| 7
|
2009-02-27T12:24:39Z
| 594,566
|
<p>As crazy as it might seem, the reason for the sometimes string, sometimes list-semantics are <a href="http://docs.python.org/library/email.parser.html#email.message%5Ffrom%5Fstring">given in the documentation</a>. Basically, multipart messages are returned as lists.</p>
| 10
|
2009-02-27T12:31:24Z
|
[
"python",
"email",
"message",
"payload"
] |
Email body is a string sometimes and a list sometimes. Why?
| 594,545
|
<p>My application is written in python. What I am doing is I am running a script on each email received by postfix and do something with the email content. Procmail is responsible for running the script taking the email as input. The problem started when I was converting the input message(may be text) to email_message object(because the latter comes in handy). I am using email.message_from_string (where email is the default email module, comes with python).</p>
<pre>
<code>
import email
message = email.message_from_string(original_mail_content)
message_body = message.get_payload()
</code>
</pre>
<p>This message_body is sometimes returning a list[email.message.Message instance,email.message.Message instance] and sometime returning a string(actual body content of the incoming email). Why is it. And even I found one more observation. When I was browsing through the email.message.Message.get_payload() docstring, I found this..<br/>
"""
The payload will either be a list object or a string.If you mutate
the list object, you modify the message's payload in place.....""" </p>
<p>So how do I have generic method to get the body of email through python? Please help me out.</p>
| 7
|
2009-02-27T12:24:39Z
| 594,633
|
<p>Well, the answers are correct, you should read the docs, but for an example of a generic way:</p>
<pre><code>def get_first_text_part(msg):
maintype = msg.get_content_maintype()
if maintype == 'multipart':
for part in msg.get_payload():
if part.get_content_maintype() == 'text':
return part.get_payload()
elif maintype == 'text':
return msg.get_payload()
</code></pre>
<p>This is prone to some disaster, as it is conceivable the parts themselves might have multiparts, and it really only returns the first text part, so this might be wrong too, but you can play with it.</p>
| 11
|
2009-02-27T12:53:42Z
|
[
"python",
"email",
"message",
"payload"
] |
Email body is a string sometimes and a list sometimes. Why?
| 594,545
|
<p>My application is written in python. What I am doing is I am running a script on each email received by postfix and do something with the email content. Procmail is responsible for running the script taking the email as input. The problem started when I was converting the input message(may be text) to email_message object(because the latter comes in handy). I am using email.message_from_string (where email is the default email module, comes with python).</p>
<pre>
<code>
import email
message = email.message_from_string(original_mail_content)
message_body = message.get_payload()
</code>
</pre>
<p>This message_body is sometimes returning a list[email.message.Message instance,email.message.Message instance] and sometime returning a string(actual body content of the incoming email). Why is it. And even I found one more observation. When I was browsing through the email.message.Message.get_payload() docstring, I found this..<br/>
"""
The payload will either be a list object or a string.If you mutate
the list object, you modify the message's payload in place.....""" </p>
<p>So how do I have generic method to get the body of email through python? Please help me out.</p>
| 7
|
2009-02-27T12:24:39Z
| 3,543,831
|
<p>Rather than simply looking for a sub-part, use walk() to iterate through the message contents</p>
<pre><code>def walkMsg(msg):
for part in msg.walk():
if part.get_content_type() == "multipart/alternative":
continue
yield part.get_payload(decode=1)
</code></pre>
<p>The walk() method returns an iterator that you can loop with (i.e. it's a generator). If the message is not a container of parts (i.e. has no attachments or alternates), the walk() method will then return an iterator with a single element - the message itself.</p>
<p>You want to skip any 'multipart' parts as they are just glue.</p>
<p>The above method returns all readable parts. You may want to expand this to simply return the text parts if they contain the info you are seeking.</p>
<p>Note that as of Python 2.5, methods get_type(), get_main_type(), and get_subtype() have been removed -> <a href="http://docs.python.org/library/email.message.html#email.message.Message.walk" rel="nofollow">http://docs.python.org/library/email.message.html#email.message.Message.walk</a> </p>
| 8
|
2010-08-22T23:04:49Z
|
[
"python",
"email",
"message",
"payload"
] |
Make a python property with the same name as the class member name
| 594,856
|
<p>Is it possible in python to create a property with the same name as the member variable name of the class. e.g.</p>
<pre><code>Class X:
...
self.i = 10 # marker
...
property(fget = get_i, fset = set_i)
</code></pre>
<p>Please tell me how I can do so. Because if I do so, for the statement at marker I get stack overflow for the assingm</p>
| 5
|
2009-02-27T13:58:53Z
| 594,892
|
<blockquote>
<p>Is it possible in python to create a property with the same name as the member variable name</p>
</blockquote>
<p>No. properties, members and methods all share the same namespace.</p>
<blockquote>
<p>the statement at marker I get stack overflow</p>
</blockquote>
<p>Clearly. You try to set i, which calls the setter for property i, which tries to set i, which calls the setter for property i... ad stackoverflowum.</p>
<p>The usual pattern is to make the backend value member conventionally non-public, by prefixing it with â_â:</p>
<pre><code>class X(object):
def get_i(self):
return self._i
def set_i(self, value):
self._i= value
i= property(get_i, set_i)
</code></pre>
<p>Note you must use new-style objects (subclass âobjectâ) for âpropertyâ to work properly.</p>
| 17
|
2009-02-27T14:09:00Z
|
[
"python"
] |
How to load an RSA key from a PEM file and use it in python-crypto
| 595,114
|
<p>I have not found a way to load an RSA private key from a PEM file to use it in python-crypto (signature).</p>
<p>python-openssl can load a PEM file but the PKey object can't be used to retrieved key information (p, q, ...) to use with Crypto.PublicKey.construct().</p>
| 8
|
2009-02-27T15:01:59Z
| 595,150
|
<p>is this (close to) what you tried doing?</p>
<pre><code>public_key_filename = 'public_key.pem'
rsa = M2Crypto.RSA.load_pub_key(pk)
</code></pre>
<p>That should work. The issue might be with openssl too, does it work when you just use openssl (not in Python)?</p>
<p><a href="http://chandlerproject.org/bin/view/Projects/MeTooCrypto" rel="nofollow">Link to Me Too Crypto</a></p>
| 5
|
2009-02-27T15:12:02Z
|
[
"python",
"cryptography"
] |
How to load an RSA key from a PEM file and use it in python-crypto
| 595,114
|
<p>I have not found a way to load an RSA private key from a PEM file to use it in python-crypto (signature).</p>
<p>python-openssl can load a PEM file but the PKey object can't be used to retrieved key information (p, q, ...) to use with Crypto.PublicKey.construct().</p>
| 8
|
2009-02-27T15:01:59Z
| 606,702
|
<p>I recommend M2Crypto instead of python-crypto. You will need M2Crypto to parse PEM anyway and its EVP api frees your code from depending on a particular algorithm.</p>
<pre><code>private = """
-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBANQNY7RD9BarYRsmMazM1hd7a+u3QeMPFZQ7Ic+BmmeWHvvVP4Yj
yu1t6vAut7mKkaDeKbT3yiGVUgAEUaWMXqECAwEAAQJAIHCz8h37N4ScZHThYJgt
oIYHKpZsg/oIyRaKw54GKxZq5f7YivcWoZ8j7IQ65lHVH3gmaqKOvqdAVVt5imKZ
KQIhAPPsr9i3FxU+Mac0pvQKhFVJUzAFfKiG3ulVUdHgAaw/AiEA3ozHKzfZWKxH
gs8v8ZQ/FnfI7DwYYhJC0YsXb6NSvR8CIHymwLo73mTxsogjBQqDcVrwLL3GoAyz
V6jf+/8HvXMbAiEAj1b3FVQEboOQD6WoyJ1mQO9n/xf50HjYhqRitOnp6ZsCIQDS
AvkvYKc6LG8IANmVv93g1dyKZvU/OQkAZepqHZB2MQ==
-----END RSA PRIVATE KEY-----
"""
message = "python-crypto sucks"
# Grab RSA parameters e, n
from M2Crypto import RSA, BIO
bio = BIO.MemoryBuffer(private)
rsa = RSA.load_key_bio(bio)
n, e = rsa.n, rsa.e
# In Python-crypto:
import Crypto.PublicKey.RSA
pycrypto_key = Crypto.PublicKey.RSA.construct((n, e))
# Use EVP api to sign message
from M2Crypto import EVP
key = EVP.load_key_string(private)
# if you need a different digest than the default 'sha1':
key.reset_context(md='sha256')
key.sign_init()
key.sign_update(message)
signature = key.sign_final()
# Use EVP api to verify signature
public = """
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANQNY7RD9BarYRsmMazM1hd7a+u3QeMP
FZQ7Ic+BmmeWHvvVP4Yjyu1t6vAut7mKkaDeKbT3yiGVUgAEUaWMXqECAwEAAQ==
-----END PUBLIC KEY-----
"""
from M2Crypto import BIO, RSA, EVP
bio = BIO.MemoryBuffer(public)
rsa = RSA.load_pub_key_bio(bio)
pubkey = EVP.PKey()
pubkey.assign_rsa(rsa)
pubkey.reset_context(md="sha256")
pubkey.verify_init()
pubkey.verify_update(message)
assert pubkey.verify_final(signature) == 1
</code></pre>
<p>See <a href="http://svn.osafoundation.org/m2crypto/trunk/tests/test%5Frsa.py">http://svn.osafoundation.org/m2crypto/trunk/tests/test_rsa.py</a>, but I prefer using the algorithm-independent EVP API <a href="http://svn.osafoundation.org/m2crypto/trunk/tests/test%5Fevp.py">http://svn.osafoundation.org/m2crypto/trunk/tests/test_evp.py</a>.</p>
<p><a href="http://stackoverflow.com/questions/544433/how-do-you-verify-an-rsa-sha1-signature-in-python/546476#546476">http://stackoverflow.com/questions/544433/how-do-you-verify-an-rsa-sha1-signature-in-python/546476#546476</a> addresses a similar issue.</p>
| 11
|
2009-03-03T14:57:27Z
|
[
"python",
"cryptography"
] |
Does PyS60 has a reliable garbage collection?
| 595,290
|
<p>I have heard it many times that garbage collection in PyS60 is not up to to the mark. This imposes a lot of limits on writing cleaner code. Can I at least rely that the non cyclic references are cleaned up after a function exists.</p>
| 3
|
2009-02-27T15:46:32Z
| 595,300
|
<p>PyS60 as of version 1.9.0 uses Python 2.5.1 core and has no problems with garbage collection.</p>
| 3
|
2009-02-27T15:49:30Z
|
[
"python",
"symbian",
"nokia",
"s60",
"pys60"
] |
Does PyS60 has a reliable garbage collection?
| 595,290
|
<p>I have heard it many times that garbage collection in PyS60 is not up to to the mark. This imposes a lot of limits on writing cleaner code. Can I at least rely that the non cyclic references are cleaned up after a function exists.</p>
| 3
|
2009-02-27T15:46:32Z
| 915,114
|
<p>Mostly you can, but occasionally PyS60 needs a little "help". Unbind keys, always cancel timers, might have to manually delete some classes etc. Nothing too bad.</p>
<p>Btw current 1.9.x branch uses python core 2.5.4. In my opinion 1.9.5 is the first version, which might be better that 1.4.5. Worth taking a look, especially if you want to play with 5800 XpressMusic :)</p>
| 0
|
2009-05-27T10:55:12Z
|
[
"python",
"symbian",
"nokia",
"s60",
"pys60"
] |
Does the stack limit of Symbian also apply to PyS60?
| 595,296
|
<p>Symbian has a stack limit of 8kB. Does this also apply to the function calling in PyS60 apps?</p>
| 3
|
2009-02-27T15:48:37Z
| 595,330
|
<p>Yes, PyS60 is based on CPython, thus uses the C stack.</p>
| 3
|
2009-02-27T15:54:53Z
|
[
"python",
"symbian",
"nokia",
"pys60"
] |
Does the stack limit of Symbian also apply to PyS60?
| 595,296
|
<p>Symbian has a stack limit of 8kB. Does this also apply to the function calling in PyS60 apps?</p>
| 3
|
2009-02-27T15:48:37Z
| 606,180
|
<p>Increasing the Symbian stack size is done through a parameter in the mmp file.
This is valid when you create a native application that the toolchain will turn into an exe file.</p>
<p>If you were to upgrade the Python runtime on your phone, with a version you built yourself, you could increase the stack size of the runtime process itself.</p>
| 1
|
2009-03-03T12:18:20Z
|
[
"python",
"symbian",
"nokia",
"pys60"
] |
Does the stack limit of Symbian also apply to PyS60?
| 595,296
|
<p>Symbian has a stack limit of 8kB. Does this also apply to the function calling in PyS60 apps?</p>
| 3
|
2009-02-27T15:48:37Z
| 685,145
|
<p>I would assume that PyS60 should be doing the memory management for you, as your program will probably be constrained by the resources of PyS60.</p>
| 0
|
2009-03-26T10:04:26Z
|
[
"python",
"symbian",
"nokia",
"pys60"
] |
Does the stack limit of Symbian also apply to PyS60?
| 595,296
|
<p>Symbian has a stack limit of 8kB. Does this also apply to the function calling in PyS60 apps?</p>
| 3
|
2009-02-27T15:48:37Z
| 915,134
|
<p>There is a difference between python runtime and python apps. Also from PyS60 app developer point of view, it's the heapsize that's more interesting...</p>
<p>Version 1.9.5 comes by default with heapsize 100k min and 4M max. Of course you can define those by yourself when creating the SIS package to release and distribute your application.</p>
<p>Sorry if I answered right question with wrong answer (stack vs heap).</p>
<p>Stack is usually "enough", but with deep enough recursion you can run out of it. Have done it - and fixed some endless loops :) Never had any real stack problems. Usually it's the heap that runs out, esp with graphics manipulation.</p>
| 1
|
2009-05-27T11:03:01Z
|
[
"python",
"symbian",
"nokia",
"pys60"
] |
What's the Python function like sum() but for multiplication? product()?
| 595,374
|
<p>Python's <a href="http://docs.python.org/library/functions.html#sum"><code>sum()</code></a> function returns the sum of numbers in an iterable.</p>
<pre><code>sum([3,4,5]) == 3 + 4 + 5 == 12
</code></pre>
<p>I'm looking for the function that returns the product instead.</p>
<pre><code>somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60
</code></pre>
<p>I'm pretty sure such a function exists, but I can't find it.</p>
| 91
|
2009-02-27T16:06:36Z
| 595,384
|
<pre><code>Numeric.product
</code></pre>
<p>( or </p>
<pre><code>reduce(lambda x,y:x*y,[3,4,5])
</code></pre>
<p>)</p>
| 16
|
2009-02-27T16:09:09Z
|
[
"python",
"builtin",
"pep"
] |
What's the Python function like sum() but for multiplication? product()?
| 595,374
|
<p>Python's <a href="http://docs.python.org/library/functions.html#sum"><code>sum()</code></a> function returns the sum of numbers in an iterable.</p>
<pre><code>sum([3,4,5]) == 3 + 4 + 5 == 12
</code></pre>
<p>I'm looking for the function that returns the product instead.</p>
<pre><code>somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60
</code></pre>
<p>I'm pretty sure such a function exists, but I can't find it.</p>
| 91
|
2009-02-27T16:06:36Z
| 595,391
|
<p>Use this</p>
<pre><code>def prod( iterable ):
p= 1
for n in iterable:
p *= n
return p
</code></pre>
<p>Since there's no built-in <code>prod</code> function.</p>
| 12
|
2009-02-27T16:10:46Z
|
[
"python",
"builtin",
"pep"
] |
What's the Python function like sum() but for multiplication? product()?
| 595,374
|
<p>Python's <a href="http://docs.python.org/library/functions.html#sum"><code>sum()</code></a> function returns the sum of numbers in an iterable.</p>
<pre><code>sum([3,4,5]) == 3 + 4 + 5 == 12
</code></pre>
<p>I'm looking for the function that returns the product instead.</p>
<pre><code>somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60
</code></pre>
<p>I'm pretty sure such a function exists, but I can't find it.</p>
| 91
|
2009-02-27T16:06:36Z
| 595,396
|
<p>There isn't one built in, but it's simple to roll your own, as demonstrated <a href="http://stackoverflow.com/questions/493853/which-python-module-is-suitable-for-data-manipulation-in-a-list/494034#494034">here</a>:</p>
<pre><code>import operator
def prod(factors):
return reduce(operator.mul, factors, 1)
</code></pre>
<p>See answers to this question: </p>
<p><a href="http://stackoverflow.com/questions/493853/which-python-module-is-suitable-for-data-manipulation-in-a-list">Which Python module is suitable for data manipulation in a list?</a></p>
| 38
|
2009-02-27T16:11:54Z
|
[
"python",
"builtin",
"pep"
] |
What's the Python function like sum() but for multiplication? product()?
| 595,374
|
<p>Python's <a href="http://docs.python.org/library/functions.html#sum"><code>sum()</code></a> function returns the sum of numbers in an iterable.</p>
<pre><code>sum([3,4,5]) == 3 + 4 + 5 == 12
</code></pre>
<p>I'm looking for the function that returns the product instead.</p>
<pre><code>somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60
</code></pre>
<p>I'm pretty sure such a function exists, but I can't find it.</p>
| 91
|
2009-02-27T16:06:36Z
| 595,409
|
<p>Actually, Guido vetoed the idea: <a href="http://bugs.python.org/issue1093">http://bugs.python.org/issue1093</a></p>
<p>But, as noted in that issue, you can make one pretty easily:</p>
<pre><code>from functools import reduce # Valid in Python 2.6+, required in Python 3
import operator
reduce(operator.mul, (3, 4, 5), 1)
</code></pre>
| 141
|
2009-02-27T16:13:48Z
|
[
"python",
"builtin",
"pep"
] |
What's the Python function like sum() but for multiplication? product()?
| 595,374
|
<p>Python's <a href="http://docs.python.org/library/functions.html#sum"><code>sum()</code></a> function returns the sum of numbers in an iterable.</p>
<pre><code>sum([3,4,5]) == 3 + 4 + 5 == 12
</code></pre>
<p>I'm looking for the function that returns the product instead.</p>
<pre><code>somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60
</code></pre>
<p>I'm pretty sure such a function exists, but I can't find it.</p>
| 91
|
2009-02-27T16:06:36Z
| 6,364,663
|
<p>There's a <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.prod.html"><code>prod()</code></a> in numpy that does what you're asking for.</p>
| 20
|
2011-06-15T21:33:14Z
|
[
"python",
"builtin",
"pep"
] |
wxPython toolbar help
| 596,190
|
<p>I am new to Python. I am writing an application using wxPython and I currently my code that generates a toolbar looks like this:</p>
<pre><code>class Window(wx.Frame)
def __init__(self, parent, plot):
wx.Frame.__init__(self, parent, wx.ID_ANY, "Name", size =(900, 600))
self.Centre()
self.toolbar = self.CreateToolBar(style=(wx.TB_HORZ_LAYOUT | wx.TB_TEXT))
self.toolbar.SetToolBitmapSize((32,32))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/fileopen.png'))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/filesave.png'))
self.toolbar.AddSeparator()
self.toolbar.Realize()
</code></pre>
<p>I am trying to clean up the code a bit and I want the toolbar to have its own class so when I want to create a toolbar, I simply call it something like this:</p>
<pre><code>toolbar = Toolbar()
</code></pre>
<p>My question is how can I rewrite it so it works like that? Currently my code looks like this:</p>
<pre><code>class Toolbar():
def __init__(self):
self.toolbar = self.CreateToolBar(style=(wx.TB_HORZ_LAYOUT | wx.TB_TEXT))
self.toolbar.SetToolBitmapSize((32,32))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/fileopen.png'))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/filesave.png'))
self.toolbar.AddSeparator()
self.toolbar.Realize()
</code></pre>
<p>I am not quite sure how 'self' works. Do I need to rewrite the <strong>init</strong> function? How do I fix it? Any help is greatly appreciated. Thanks</p>
| 0
|
2009-02-27T19:13:08Z
| 596,340
|
<p>Instead of a class that sets up your toolbar, use a function. The function can be a member function of your Window that subclasses wx.Frame. That way, the toolbar will get Created from the correct window, and be attached the way you would expect.</p>
<p>The class that you're writing above would work, if it knew which wx.Frame (your class called Window) to connect the toolbar to. To get it to work you would have to pass the frame object to the toolbar creator class...</p>
<pre><code>class Toolbar():
def __init__(self, frame_to_connect_to):
frame_to_connect_to.toolbar = frame_to_connect_to.CreateToolBar(style=(wx.TB_HORZ_LAYOUT | wx.TB_TEXT))
frame_to_connect_to.toolbar.SetToolBitmapSize((32,32))
frame_to_connect_to.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/fileopen.png'))
frame_to_connect_to.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/filesave.png'))
frame_to_connect_to.toolbar.AddSeparator()
frame_to_connect_to.toolbar.Realize()
</code></pre>
<p>It looks like a quick fix... but really using a class to do this is not a good use of classes. (I'd even go so far as to say it was incorrect.)</p>
<p>Really, what would clean things up a bit would be just to move the toolbar stuff to its own member function:</p>
<pre><code>class Window(wx.Frame)
def __init__(self, parent, plot):
wx.Frame.__init__(self, parent, wx.ID_ANY, "Name", size =(900, 600))
self.Centre()
self._init_toolbar()
def _init_toolbar(self):
self.toolbar = self.CreateToolBar(style=(wx.TB_HORZ_LAYOUT | wx.TB_TEXT))
self.toolbar.SetToolBitmapSize((32,32))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/fileopen.png'))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/filesave.png'))
self.toolbar.AddSeparator()
self.toolbar.Realize()
</code></pre>
<p>You get all the benefits.</p>
| 3
|
2009-02-27T19:52:14Z
|
[
"python",
"user-interface",
"wxpython",
"toolbars"
] |
wxPython toolbar help
| 596,190
|
<p>I am new to Python. I am writing an application using wxPython and I currently my code that generates a toolbar looks like this:</p>
<pre><code>class Window(wx.Frame)
def __init__(self, parent, plot):
wx.Frame.__init__(self, parent, wx.ID_ANY, "Name", size =(900, 600))
self.Centre()
self.toolbar = self.CreateToolBar(style=(wx.TB_HORZ_LAYOUT | wx.TB_TEXT))
self.toolbar.SetToolBitmapSize((32,32))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/fileopen.png'))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/filesave.png'))
self.toolbar.AddSeparator()
self.toolbar.Realize()
</code></pre>
<p>I am trying to clean up the code a bit and I want the toolbar to have its own class so when I want to create a toolbar, I simply call it something like this:</p>
<pre><code>toolbar = Toolbar()
</code></pre>
<p>My question is how can I rewrite it so it works like that? Currently my code looks like this:</p>
<pre><code>class Toolbar():
def __init__(self):
self.toolbar = self.CreateToolBar(style=(wx.TB_HORZ_LAYOUT | wx.TB_TEXT))
self.toolbar.SetToolBitmapSize((32,32))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/fileopen.png'))
self.toolbar.AddLabelTool(3, '', wx.Bitmap('GUI/icons/filesave.png'))
self.toolbar.AddSeparator()
self.toolbar.Realize()
</code></pre>
<p>I am not quite sure how 'self' works. Do I need to rewrite the <strong>init</strong> function? How do I fix it? Any help is greatly appreciated. Thanks</p>
| 0
|
2009-02-27T19:13:08Z
| 598,126
|
<p>Yes. Break your wxpython code into objects like this. It is much easier to maintain if you are going to code your GUI by hand (I do).</p>
<p>You need to subclass <a href="http://wxpython.org/docs/api/wx.ToolBar-class.html" rel="nofollow">wx.ToolBar</a> (which itself is a subclass of <a href="http://wxpython.org/docs/api/wx.ToolBarBase-class.html" rel="nofollow">wx.ToolBarBase</a>, and most of wx.ToolBar's functions are derived from that namespace):</p>
<pre><code>class MyToolBar(wx.ToolBar):
def __init__(self, parent, *args, **kwargs):
wx.ToolBar.__init__(self, parent, *args, **kwargs)
#note self here and not self.toolbar
self.SetToolBitmapSize((32,32))
#add other code here
</code></pre>
<p>Then in your <code>__init__</code> for your wx.Frame call your toolbar:</p>
<pre><code>class MyFrame(wx.Frame):
def __init__(self, parent, *args, **kwargs):
wx.Frame.__init__(self, parent, *args, **kwargs)
#note that below, self refers to the wx.Frame
#self(wx.Frame) = parent for the toolbar constructor
toolbar = MyToolBar(self)
</code></pre>
<p><a href="http://wiki.wxpython.org/wxPython%20Style%20Guide" rel="nofollow">wxPython Style Guide</a></p>
<p>Another thing to note is that often the <a href="http://docs.wxwidgets.org/stable/" rel="nofollow">wxWidgets docs</a> are much easier to navigate and <a href="http://docs.wxwidgets.org/stable/wx%5Fwxtoolbar.html#wxtoolbar" rel="nofollow">to decipher</a>.</p>
| 1
|
2009-02-28T15:04:55Z
|
[
"python",
"user-interface",
"wxpython",
"toolbars"
] |
How do I use python for web development without relying on a framework?
| 596,729
|
<p>I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing <em>python</em>.</p>
<p>The only thing I have found so far that lets me do this in the most obvious way possible is <a href="http://webpy.org/">web.py</a> but I have slight concerns on its performance.</p>
<p>For those of you using nginx(or another flavour)+mod_wsgi+web.py... how's performance? Can it be improved further?</p>
<p>For those of you who have used web.py, liked the idea and went on to write something better or found something better... care to point me to the source?</p>
<p>I'd like to hear about all the conspicuous, minimal yet powerful approaches.</p>
| 28
|
2009-02-27T21:20:50Z
| 596,762
|
<p>For what it's worth, I wrote my website in mod_python without any intervening framework like Django. I didn't really have any reason to complain. (Well maybe a little, mod_python is kind of quirky in a few ways but not in the common use cases) One thing's for sure, it will definitely let you write Python ;-)</p>
| 3
|
2009-02-27T21:33:33Z
|
[
"python",
"performance",
"web.py"
] |
How do I use python for web development without relying on a framework?
| 596,729
|
<p>I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing <em>python</em>.</p>
<p>The only thing I have found so far that lets me do this in the most obvious way possible is <a href="http://webpy.org/">web.py</a> but I have slight concerns on its performance.</p>
<p>For those of you using nginx(or another flavour)+mod_wsgi+web.py... how's performance? Can it be improved further?</p>
<p>For those of you who have used web.py, liked the idea and went on to write something better or found something better... care to point me to the source?</p>
<p>I'd like to hear about all the conspicuous, minimal yet powerful approaches.</p>
| 28
|
2009-02-27T21:20:50Z
| 596,807
|
<p>The way to go is <a href="http://wsgi.org">wsgi</a>.</p>
<p>WSGI is the <strong>Web Server Gateway Interface</strong>. It is a specification for web servers and application servers to communicate with web applications (though it can also be used for more than that). <strong>It is a Python standard, described in detail in <a href="http://www.python.org/dev/peps/pep-0333/">PEP 333</a></strong>. </p>
<p>All current frameworks support wsgi. A lot of webservers support it also (apache included, through <a href="http://code.google.com/p/modwsgi/">mod_wsgi</a>). It is the way to go if you want to write your own framework.</p>
<p>Here is hello world, written to wsgi directly:</p>
<pre><code>def application(environ, start_response):
status = '200 OK'
response_headers = [('Content-type','text/plain')]
start_response(status, response_headers)
return ['Hello world!\n']
</code></pre>
<p>Put this in a <code>file.py</code>, point your <code>mod_wsgi</code> apache configuration to it, and it will run. Pure python. No imports. Just a python function.</p>
<p>If you are really writing your own framework, you could check <a href="http://werkzeug.pocoo.org/">werkzeug</a>. It is not a framework, but a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility modules. It includes a powerful debugger, full featured request and response objects, HTTP utilities to handle entity tags, cache control headers, HTTP dates, cookie handling, file uploads, a powerful URL routing system and a bunch of community contributed addon modules. Takes the boring part out of your hands.</p>
| 36
|
2009-02-27T21:45:58Z
|
[
"python",
"performance",
"web.py"
] |
How do I use python for web development without relying on a framework?
| 596,729
|
<p>I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing <em>python</em>.</p>
<p>The only thing I have found so far that lets me do this in the most obvious way possible is <a href="http://webpy.org/">web.py</a> but I have slight concerns on its performance.</p>
<p>For those of you using nginx(or another flavour)+mod_wsgi+web.py... how's performance? Can it be improved further?</p>
<p>For those of you who have used web.py, liked the idea and went on to write something better or found something better... care to point me to the source?</p>
<p>I'd like to hear about all the conspicuous, minimal yet powerful approaches.</p>
| 28
|
2009-02-27T21:20:50Z
| 596,811
|
<p>You could also check <a href="http://cherrypy.org" rel="nofollow">cherrypy</a>. The focus of cherrypy is in being a framework that lets you write python. Cherrypy has its own pretty good webserver, but it is wsgi-compatible so you can run cherrypy applications in apache via mod_wsgi. Here is hello world in cherrypy:</p>
<pre><code>import cherrypy
class HelloWorld(object):
def index(self):
return "Hello World!"
index.exposed = True
cherrypy.quickstart(HelloWorld())
</code></pre>
| 9
|
2009-02-27T21:46:50Z
|
[
"python",
"performance",
"web.py"
] |
How do I use python for web development without relying on a framework?
| 596,729
|
<p>I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing <em>python</em>.</p>
<p>The only thing I have found so far that lets me do this in the most obvious way possible is <a href="http://webpy.org/">web.py</a> but I have slight concerns on its performance.</p>
<p>For those of you using nginx(or another flavour)+mod_wsgi+web.py... how's performance? Can it be improved further?</p>
<p>For those of you who have used web.py, liked the idea and went on to write something better or found something better... care to point me to the source?</p>
<p>I'd like to hear about all the conspicuous, minimal yet powerful approaches.</p>
| 28
|
2009-02-27T21:20:50Z
| 596,845
|
<p>What's wrong with Django? It doesn't force you to use it's ORM and controllers are just plain Python functions instead of Rails-like class methods. Also, url routing is done with regular expressions instead of another framework-invented syntax. If django seems like too much for you anyway, i recommend taking a look at <a href="http://werkzeug.pocoo.org/" rel="nofollow">Werkzeug</a></p>
| 0
|
2009-02-27T21:56:26Z
|
[
"python",
"performance",
"web.py"
] |
How do I use python for web development without relying on a framework?
| 596,729
|
<p>I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing <em>python</em>.</p>
<p>The only thing I have found so far that lets me do this in the most obvious way possible is <a href="http://webpy.org/">web.py</a> but I have slight concerns on its performance.</p>
<p>For those of you using nginx(or another flavour)+mod_wsgi+web.py... how's performance? Can it be improved further?</p>
<p>For those of you who have used web.py, liked the idea and went on to write something better or found something better... care to point me to the source?</p>
<p>I'd like to hear about all the conspicuous, minimal yet powerful approaches.</p>
| 28
|
2009-02-27T21:20:50Z
| 596,877
|
<p>It's hilarious how, even prompted with a question asking how to write without a framework, everyone still piles in to promote their favourite framework. The OP whinges about not wanting a âheavyweight frameworkâ, and the replies mention <em>Twisted</em>, of all things?! Come now, really.</p>
<p>Yes, it <em>is</em> perfectly possible to write straight WSGI apps, and grab bits of wanted functionality from standalone modules, instead of fitting your code into one particular framework's view of the world.</p>
<p>To take this route you'll generally want to be familiar with the basics of HTTP and CGI (since WSGI inherits an awful lot from that earlier specification). It's not necessarily an approach to recommend to beginners, but it's quite doable.</p>
<blockquote>
<p>I'd like to hear about all the conspicuous, minimal yet powerful approaches</p>
</blockquote>
<p>You won't <em>hear</em> about them, because no-one has a tribal interest in promoting âdo it yourselfâ as a methodology. Me, I use a particular standalone templating package, a particular standalone form-reading package, a particular data access layer, and a few home-brew utility modules. I'm not writing to one particular philosophy I can proselytise about, they're all just boring tools that could be swapped out and replaced with something else just as good.</p>
| 18
|
2009-02-27T22:11:40Z
|
[
"python",
"performance",
"web.py"
] |
How do I use python for web development without relying on a framework?
| 596,729
|
<p>I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing <em>python</em>.</p>
<p>The only thing I have found so far that lets me do this in the most obvious way possible is <a href="http://webpy.org/">web.py</a> but I have slight concerns on its performance.</p>
<p>For those of you using nginx(or another flavour)+mod_wsgi+web.py... how's performance? Can it be improved further?</p>
<p>For those of you who have used web.py, liked the idea and went on to write something better or found something better... care to point me to the source?</p>
<p>I'd like to hear about all the conspicuous, minimal yet powerful approaches.</p>
| 28
|
2009-02-27T21:20:50Z
| 596,884
|
<p>I'm pretty fond of Google AppEngine. I use the ORM and templating system, but otherwise follow a REST-patterned design and just implement Python methods for the corresponding HTTP ones. It makes the raw HTTP interaction central, and optionally gives you other things to use. Plus no more configuring and managing your deployment environment!</p>
| 0
|
2009-02-27T22:14:37Z
|
[
"python",
"performance",
"web.py"
] |
How do I use python for web development without relying on a framework?
| 596,729
|
<p>I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing <em>python</em>.</p>
<p>The only thing I have found so far that lets me do this in the most obvious way possible is <a href="http://webpy.org/">web.py</a> but I have slight concerns on its performance.</p>
<p>For those of you using nginx(or another flavour)+mod_wsgi+web.py... how's performance? Can it be improved further?</p>
<p>For those of you who have used web.py, liked the idea and went on to write something better or found something better... care to point me to the source?</p>
<p>I'd like to hear about all the conspicuous, minimal yet powerful approaches.</p>
| 28
|
2009-02-27T21:20:50Z
| 596,890
|
<p>I've written a few small web applications using mod-python and <a href="http://www.math.temple.edu/doc/packages/apache2-mod_python/doc-html/pyapi-psp.html" rel="nofollow">PSP</a> -- mod-python's equivalent to php.</p>
<p>In one case, I wrote a web page that generates release notes by inspecting our source code repository. I rewrote it into PHP, and was surprised to discover that the PSP version was about 20% faster, as well as being about half as many lines of code. </p>
<p>So, for small problems at least, psp has worked well for me.</p>
| 1
|
2009-02-27T22:16:44Z
|
[
"python",
"performance",
"web.py"
] |
How do I use python for web development without relying on a framework?
| 596,729
|
<p>I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing <em>python</em>.</p>
<p>The only thing I have found so far that lets me do this in the most obvious way possible is <a href="http://webpy.org/">web.py</a> but I have slight concerns on its performance.</p>
<p>For those of you using nginx(or another flavour)+mod_wsgi+web.py... how's performance? Can it be improved further?</p>
<p>For those of you who have used web.py, liked the idea and went on to write something better or found something better... care to point me to the source?</p>
<p>I'd like to hear about all the conspicuous, minimal yet powerful approaches.</p>
| 28
|
2009-02-27T21:20:50Z
| 596,910
|
<p>+1 to all the answers with WSGI.</p>
<p>Eric Florenzo wrote a great blog post lately you should read: <a href="http://www.eflorenzano.com/blog/post/writing-blazing-fast-infinitely-scalable-pure-wsgi/">Writing Blazing Fast, Infinitely Scalable, Pure-WSGI Utilities</a>. This will give you a better idea of pure WSGI beyond Hello World. Also pay attention to the comments, especially the first comment by Kevin Dangoor where he recommends at least adding <a href="http://pythonpaste.org/webob/">WebOb</a> to your toolset.</p>
| 8
|
2009-02-27T22:23:49Z
|
[
"python",
"performance",
"web.py"
] |
How do I use python for web development without relying on a framework?
| 596,729
|
<p>I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing <em>python</em>.</p>
<p>The only thing I have found so far that lets me do this in the most obvious way possible is <a href="http://webpy.org/">web.py</a> but I have slight concerns on its performance.</p>
<p>For those of you using nginx(or another flavour)+mod_wsgi+web.py... how's performance? Can it be improved further?</p>
<p>For those of you who have used web.py, liked the idea and went on to write something better or found something better... care to point me to the source?</p>
<p>I'd like to hear about all the conspicuous, minimal yet powerful approaches.</p>
| 28
|
2009-02-27T21:20:50Z
| 596,988
|
<p>I think it depends on the definition of what a framework is and what it should do for you.</p>
<p>As pointed out, a very minimal "framework" would be WSGI as it only defines one small interface for interfacing with a web server. But it's a powerful approach because of the middleware you can put between your app and the server. </p>
<p>If you want more slightly more, like some URL to function mapping, then you have some choices, some of which have been already mentioned. </p>
<p>If you go further you might come to Pylons or Turbogears or Django, after that maybe Zope but it grows bigger and maybe the pain as well as you always buy into the opinions of that framework.</p>
<p>What I recently use more and more (coming from Zope/Plone) is <a href="http://static.repoze.org/bfgdocs/" rel="nofollow">repoze.bfg</a>. It's very small, does not come with a ORM bundled (so you can use SQLAlchemy, Storm or simply go to an object database like the <a href="http://new.zope.org/projects/zodb" rel="nofollow">ZODB</a>). What it does is basically handling how you come from a URL to a view which is a function. It supports both URL Mapping (a la Routes) or object traversal, which IMHO is very powerful in some circumstances esp. if you have a not so strict mapping. The good thing is that it directly comes with an ACL based security framework which can use if you want to which IMHO is very practical to have. That way you don't need decorators which seem to be used mostly for such things.</p>
<p>And of course it's based on WSGI. Also look for the <a href="http://svn.repoze.org" rel="nofollow">repoze subversion repository</a> for quite a lot of middleware and the <a href="http://pythonpaste.org" rel="nofollow">Paste</a> stuff is also very useful for WSGI related tasks.</p>
| 1
|
2009-02-27T22:53:00Z
|
[
"python",
"performance",
"web.py"
] |
How do I use python for web development without relying on a framework?
| 596,729
|
<p>I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing <em>python</em>.</p>
<p>The only thing I have found so far that lets me do this in the most obvious way possible is <a href="http://webpy.org/">web.py</a> but I have slight concerns on its performance.</p>
<p>For those of you using nginx(or another flavour)+mod_wsgi+web.py... how's performance? Can it be improved further?</p>
<p>For those of you who have used web.py, liked the idea and went on to write something better or found something better... care to point me to the source?</p>
<p>I'd like to hear about all the conspicuous, minimal yet powerful approaches.</p>
| 28
|
2009-02-27T21:20:50Z
| 7,968,503
|
<p>Why do you have concerns about web.py's performance? As I mentioned <a href="http://stackoverflow.com/questions/7788149/web-py-deployment-for-ios-app-backend/7853705#7853705">here</a>, we use <a href="http://www.cherrypy.org/" rel="nofollow">CherryPy</a> (the web server "built into" web.py) behind <a href="http://nginx.org/" rel="nofollow">nginx</a> to serve most of the HTML at Oyster.com -- nginx splits the traffic across 2 or 3 web servers each running 4 Python processes, and we can easily handle 100s of requests per second.</p>
<p>Oyster.com is a high-volume website averaging 200,000 dynamically-generated pageviews/day, and peaking to much higher numbers than that. However, we do use a content delivery network (CDN) for our static resources like images and CSS.</p>
<p>We definitely care about performance (most of our pages render in less than 25ms), but web.py isn't the bottleneck. Our bottlenecks are template rendering (we use <a href="http://www.cheetahtemplate.org/" rel="nofollow">Cheetah</a>, which is fast enough but not other-worldly fast) and database queries (we cache heavily and keep the number of database queries per page to 0 or 1) and accessing our 3rd-party hotel pricing providers (these are accessed when you do a search with dates we don't already have cached).</p>
<p>Remember, premature optimization is the root of all evil -- unless you're serving google.com, web.py will probably work for you.</p>
| 2
|
2011-11-01T15:09:09Z
|
[
"python",
"performance",
"web.py"
] |
AttributeError: 'str' object has no attribute 'readline'
| 596,886
|
<p><strong>Update: My current question is how can I get my code to read to the EOF starting from the beginning with each new search phrase.</strong></p>
<p>This is an assignment I am doing and currently stuck on. Mind you this is a beginner's programming class using Python.</p>
<pre><code>jargon = open("jargonFile.txt","r")
searchPhrase = raw_input("Enter the search phrase: ")
while searchPhrase != "":
result = jargon.readline().find(searchPhrase)
if result == -1:
print "Cannot find this term."
else:
print result
searchPhrase = raw_input("Enter the search phrase: ")
jargon.close()
</code></pre>
<p>The assignment is to take a user's searchPhrase and find it in a file (jargonFile.txt) and then have it print the result (which is the line it occured and the character occurence). I will be using a counter to find the line number of the occurence but I will implement this later. For now my question is the error I am getting. I cann't find a way for it to search the entire file.</p>
<p>Sample run: </p>
<pre><code>Enter the search phrase: dog
16
Enter the search phrase: hack
Cannot find this term.
Enter the search phrase:
</code></pre>
<p>"dog" is found in the first line however it is also found in other lines of the jargonFile (multiple times as a string) but it is only showing the first occurence in the first line. The string hack is found numerous times in the jargonFile but my code is setup to only search the first line. How may I go about solving this problem?</p>
<p>If this is not clear enough I can post up the assignment if need be.</p>
| 4
|
2009-02-27T22:15:25Z
| 596,899
|
<p>Your file is <code>jargon</code>, not <code>jargonFile</code> (a string). That's probably what's causing your error message. You'll also need a second loop to read each line of the file from the beginning until you find the word you're looking for. Your code currently stops searching if the word is not found in the current line of the file.</p>
<p>How about trying to write code that only gives the user one chance to enter a string? Input that string, search the file until you find it (or not) and output a result. After you get that working you can go back and add the code that allows multiple searches and ends on an empty string.</p>
<p><strong>Update:</strong></p>
<p>To avoid iterating the file multiple times, you could start your program by slurping the entire file into a list of strings, one line at a time. Look up the <code>readlines</code> method of file objects. You can then search that list for each user input instead of re-reading the file.</p>
| 1
|
2009-02-27T22:20:13Z
|
[
"python",
"file",
"readline"
] |
AttributeError: 'str' object has no attribute 'readline'
| 596,886
|
<p><strong>Update: My current question is how can I get my code to read to the EOF starting from the beginning with each new search phrase.</strong></p>
<p>This is an assignment I am doing and currently stuck on. Mind you this is a beginner's programming class using Python.</p>
<pre><code>jargon = open("jargonFile.txt","r")
searchPhrase = raw_input("Enter the search phrase: ")
while searchPhrase != "":
result = jargon.readline().find(searchPhrase)
if result == -1:
print "Cannot find this term."
else:
print result
searchPhrase = raw_input("Enter the search phrase: ")
jargon.close()
</code></pre>
<p>The assignment is to take a user's searchPhrase and find it in a file (jargonFile.txt) and then have it print the result (which is the line it occured and the character occurence). I will be using a counter to find the line number of the occurence but I will implement this later. For now my question is the error I am getting. I cann't find a way for it to search the entire file.</p>
<p>Sample run: </p>
<pre><code>Enter the search phrase: dog
16
Enter the search phrase: hack
Cannot find this term.
Enter the search phrase:
</code></pre>
<p>"dog" is found in the first line however it is also found in other lines of the jargonFile (multiple times as a string) but it is only showing the first occurence in the first line. The string hack is found numerous times in the jargonFile but my code is setup to only search the first line. How may I go about solving this problem?</p>
<p>If this is not clear enough I can post up the assignment if need be.</p>
| 4
|
2009-02-27T22:15:25Z
| 596,901
|
<p>First you open the file and read it into a string with readline(). Later on you try to readline() from the string you obtained in the first step.</p>
<p>You need to take care what object (thing) you're handling: open() gave you a file "jargon", readline on jargon gave you the string "jargonFile".</p>
<p>So jargonFile.readline does not make sense anymore </p>
<p>Update as answer to comment:</p>
<p>Okay, now that the str error problem is solved think about the program structure:</p>
<pre><code>big loop
enter a search term
open file
inner loop
read a line
print result if string found
close file
</code></pre>
<p>You'd need to change your program so it follows that descripiton</p>
<p>Update II:</p>
<p>SD, if you want to avoid reopening the file you'd still need two loops, but this time one loop reads the file into memory, when that's done the second loop asks for the search term. So you would structure it like</p>
<pre><code>create empty list
open file
read loop:
read a line from the file
append the file to the list
close file
query loop:
ask the user for input
for each line in the array:
print result if string found
</code></pre>
<p>For extra points from your professor add some comments to your solution that mention both possible solutions and say why you choose the one you did. Hint: In this case it is a classic tradeoff between execution time (memory is fast) and memory usage (what if your jargon file contains 100 million entries ... ok, you'd use something more complicated than a flat file in that case, bu you can't load it in memory either.)</p>
<p>Oh and one more hint to the second solution: Python supports tuples ("a","b","c") and lists ["a","b","c"]. You want to use the latter one, because list can be modified (a tuple can't.)</p>
<pre><code>myList = ["Hello", "SD"]
myList.append("How are you?")
foreach line in myList:
print line
</code></pre>
<p>==></p>
<pre><code>Hello
SD
How are you?
</code></pre>
<p>Okay that last example contains all the new stuff (define list, append to list, loop over list) for the second solution of your program. Have fun putting it all together.</p>
| 3
|
2009-02-27T22:21:22Z
|
[
"python",
"file",
"readline"
] |
AttributeError: 'str' object has no attribute 'readline'
| 596,886
|
<p><strong>Update: My current question is how can I get my code to read to the EOF starting from the beginning with each new search phrase.</strong></p>
<p>This is an assignment I am doing and currently stuck on. Mind you this is a beginner's programming class using Python.</p>
<pre><code>jargon = open("jargonFile.txt","r")
searchPhrase = raw_input("Enter the search phrase: ")
while searchPhrase != "":
result = jargon.readline().find(searchPhrase)
if result == -1:
print "Cannot find this term."
else:
print result
searchPhrase = raw_input("Enter the search phrase: ")
jargon.close()
</code></pre>
<p>The assignment is to take a user's searchPhrase and find it in a file (jargonFile.txt) and then have it print the result (which is the line it occured and the character occurence). I will be using a counter to find the line number of the occurence but I will implement this later. For now my question is the error I am getting. I cann't find a way for it to search the entire file.</p>
<p>Sample run: </p>
<pre><code>Enter the search phrase: dog
16
Enter the search phrase: hack
Cannot find this term.
Enter the search phrase:
</code></pre>
<p>"dog" is found in the first line however it is also found in other lines of the jargonFile (multiple times as a string) but it is only showing the first occurence in the first line. The string hack is found numerous times in the jargonFile but my code is setup to only search the first line. How may I go about solving this problem?</p>
<p>If this is not clear enough I can post up the assignment if need be.</p>
| 4
|
2009-02-27T22:15:25Z
| 596,927
|
<p>Everytime you enter a search phrase, it looks for it on the <strong>next</strong> line, not the first one. You need to re-open the file for every search phrase, if you want it behave like you describe. </p>
| 1
|
2009-02-27T22:31:55Z
|
[
"python",
"file",
"readline"
] |
AttributeError: 'str' object has no attribute 'readline'
| 596,886
|
<p><strong>Update: My current question is how can I get my code to read to the EOF starting from the beginning with each new search phrase.</strong></p>
<p>This is an assignment I am doing and currently stuck on. Mind you this is a beginner's programming class using Python.</p>
<pre><code>jargon = open("jargonFile.txt","r")
searchPhrase = raw_input("Enter the search phrase: ")
while searchPhrase != "":
result = jargon.readline().find(searchPhrase)
if result == -1:
print "Cannot find this term."
else:
print result
searchPhrase = raw_input("Enter the search phrase: ")
jargon.close()
</code></pre>
<p>The assignment is to take a user's searchPhrase and find it in a file (jargonFile.txt) and then have it print the result (which is the line it occured and the character occurence). I will be using a counter to find the line number of the occurence but I will implement this later. For now my question is the error I am getting. I cann't find a way for it to search the entire file.</p>
<p>Sample run: </p>
<pre><code>Enter the search phrase: dog
16
Enter the search phrase: hack
Cannot find this term.
Enter the search phrase:
</code></pre>
<p>"dog" is found in the first line however it is also found in other lines of the jargonFile (multiple times as a string) but it is only showing the first occurence in the first line. The string hack is found numerous times in the jargonFile but my code is setup to only search the first line. How may I go about solving this problem?</p>
<p>If this is not clear enough I can post up the assignment if need be.</p>
| 4
|
2009-02-27T22:15:25Z
| 596,932
|
<p>Take a look at the documentation for File objects:</p>
<p><a href="http://docs.python.org/library/stdtypes.html#file-objects" rel="nofollow">http://docs.python.org/library/stdtypes.html#file-objects</a></p>
<p>You might be interested in the <code>readlines</code> method. For a simple case where your file is not enormous, you could use that to read all the lines into a list. Then, whenever you get a new search string, you can run through the whole list to see whether it's there.</p>
| 1
|
2009-02-27T22:33:56Z
|
[
"python",
"file",
"readline"
] |
AttributeError: 'str' object has no attribute 'readline'
| 596,886
|
<p><strong>Update: My current question is how can I get my code to read to the EOF starting from the beginning with each new search phrase.</strong></p>
<p>This is an assignment I am doing and currently stuck on. Mind you this is a beginner's programming class using Python.</p>
<pre><code>jargon = open("jargonFile.txt","r")
searchPhrase = raw_input("Enter the search phrase: ")
while searchPhrase != "":
result = jargon.readline().find(searchPhrase)
if result == -1:
print "Cannot find this term."
else:
print result
searchPhrase = raw_input("Enter the search phrase: ")
jargon.close()
</code></pre>
<p>The assignment is to take a user's searchPhrase and find it in a file (jargonFile.txt) and then have it print the result (which is the line it occured and the character occurence). I will be using a counter to find the line number of the occurence but I will implement this later. For now my question is the error I am getting. I cann't find a way for it to search the entire file.</p>
<p>Sample run: </p>
<pre><code>Enter the search phrase: dog
16
Enter the search phrase: hack
Cannot find this term.
Enter the search phrase:
</code></pre>
<p>"dog" is found in the first line however it is also found in other lines of the jargonFile (multiple times as a string) but it is only showing the first occurence in the first line. The string hack is found numerous times in the jargonFile but my code is setup to only search the first line. How may I go about solving this problem?</p>
<p>If this is not clear enough I can post up the assignment if need be.</p>
| 4
|
2009-02-27T22:15:25Z
| 597,178
|
<p>Hmm, I don't know anything at all about Python, but it looks to me like you are not iterating through all the lines of the file for the search string entered.</p>
<p>Typically, you need to do something like this:</p>
<pre><code>enter search string
open file
if file has data
start loop
get next line of file
search the line for your string and do something
Exit loop if line was end of file
</code></pre>
<p>So for your code:</p>
<pre><code>jargon = open("jargonFile.txt","r")
searchPhrase = raw_input("Enter the search phrase: ")
while searchPhrase != "":
<<if file has data?>>
<<while>>
result = jargon.readline().find(searchPhrase)
if result == -1:
print "Cannot find this term."
else:
print result
<<result is not end of file>>
searchPhrase = raw_input("Enter the search phrase: ")
jargon.close()
</code></pre>
<p>Cool, did a little research on the page DNS provided and Python happens to have the "with" keyword. Example:</p>
<pre><code>with open("hello.txt") as f:
for line in f:
print line
</code></pre>
<p>So another form of your code could be:</p>
<pre><code>searchPhrase = raw_input("Enter the search phrase: ")
while searchPhrase != "":
with open("jargonFile.txt") as f:
for line in f:
result = line.find(searchPhrase)
if result == -1:
print "Cannot find this term."
else:
print result
searchPhrase = raw_input("Enter the search phrase: ")
</code></pre>
<p>Note that "with" automatically closes the file when you're done.</p>
| 2
|
2009-02-28T00:21:41Z
|
[
"python",
"file",
"readline"
] |
AttributeError: 'str' object has no attribute 'readline'
| 596,886
|
<p><strong>Update: My current question is how can I get my code to read to the EOF starting from the beginning with each new search phrase.</strong></p>
<p>This is an assignment I am doing and currently stuck on. Mind you this is a beginner's programming class using Python.</p>
<pre><code>jargon = open("jargonFile.txt","r")
searchPhrase = raw_input("Enter the search phrase: ")
while searchPhrase != "":
result = jargon.readline().find(searchPhrase)
if result == -1:
print "Cannot find this term."
else:
print result
searchPhrase = raw_input("Enter the search phrase: ")
jargon.close()
</code></pre>
<p>The assignment is to take a user's searchPhrase and find it in a file (jargonFile.txt) and then have it print the result (which is the line it occured and the character occurence). I will be using a counter to find the line number of the occurence but I will implement this later. For now my question is the error I am getting. I cann't find a way for it to search the entire file.</p>
<p>Sample run: </p>
<pre><code>Enter the search phrase: dog
16
Enter the search phrase: hack
Cannot find this term.
Enter the search phrase:
</code></pre>
<p>"dog" is found in the first line however it is also found in other lines of the jargonFile (multiple times as a string) but it is only showing the first occurence in the first line. The string hack is found numerous times in the jargonFile but my code is setup to only search the first line. How may I go about solving this problem?</p>
<p>If this is not clear enough I can post up the assignment if need be.</p>
| 4
|
2009-02-27T22:15:25Z
| 598,010
|
<p>you shouldn't try to re-invent the wheel. just use the
<a href="http://docs.python.org/3.0/library/re.html?highlight=findall#re.findall" rel="nofollow">re module functions</a>.
your program could work better if you used:
result = jargon.read() .
instead of:
result = jargon.readline() .
then you could use the re.findall() function
and join the strings (with the indexes) you searched for with str.join()
this could get a little messy but if take some time to work it out, this could fix your problem.
the python documentation has this perfectly documented</p>
| 2
|
2009-02-28T13:14:32Z
|
[
"python",
"file",
"readline"
] |
xml.dom.minidom: Getting CDATA values
| 597,058
|
<p>I'm able to get the value in the image tag (see XML below), but not the Category tag. The difference is one is a CDATA section and the other is just a string. Any help would be appreciated.</p>
<pre><code>from xml.dom import minidom
xml = """<?xml version="1.0" ?>
<ProductData>
<ITEM Id="0471195">
<Category>
<![CDATA[Homogenizers]]>
</Category>
<Image>
0471195.jpg
</Image>
</ITEM>
<ITEM Id="0471195">
<Category>
<![CDATA[Homogenizers]]>
</Category>
<Image>
0471196.jpg
</Image>
</ITEM>
</ProductData>
"""
bad_xml_item_count = 0
data = {}
xml_data = minidom.parseString(xml).getElementsByTagName('ProductData')
parts = xml_data[0].getElementsByTagName('ITEM')
for p in parts:
try:
part_id = p.attributes['Id'].value.strip()
except(KeyError):
bad_xml_item_count += 1
continue
if not part_id:
bad_xml_item_count += 1
continue
part_image = p.getElementsByTagName('Image')[0].firstChild.nodeValue.strip()
part_category = p.getElementsByTagName('Category')[0].firstChild.data.strip()
print '\t'.join([part_id, part_category, part_image])
</code></pre>
| 10
|
2009-02-27T23:20:56Z
| 597,107
|
<blockquote>
<p>p.getElementsByTagName('Category')[0].firstChild</p>
</blockquote>
<p>minidom does not flatten away <![CDATA[ sections to plain text, it leaves them as DOM CDATASection nodes. (Arguably it should, at least optionally. DOM Level 3 LS defaults to flattening them, for what it's worth, but minidom is much older than DOM L3.)</p>
<p>So the firstChild of Category is a Text node representing the whitespace between the <Category> open tag and the start of the CDATA section. It has two siblings: the CDATASection node, and another trailing whitespace Text node.</p>
<p>What you probably want is the textual data of all children of Category. In DOM Level 3 Core you'd just call:</p>
<pre><code>p.getElementsByTagName('Category')[0].textContent
</code></pre>
<p>but minidom doesn't support that yet. Recent versions do, however, support another Level 3 method you can use to do the same thing in a more roundabout way:</p>
<pre><code>p.getElementsByTagName('Category')[0].firstChild.wholeText
</code></pre>
| 21
|
2009-02-27T23:40:50Z
|
[
"python",
"xml"
] |
xml.dom.minidom: Getting CDATA values
| 597,058
|
<p>I'm able to get the value in the image tag (see XML below), but not the Category tag. The difference is one is a CDATA section and the other is just a string. Any help would be appreciated.</p>
<pre><code>from xml.dom import minidom
xml = """<?xml version="1.0" ?>
<ProductData>
<ITEM Id="0471195">
<Category>
<![CDATA[Homogenizers]]>
</Category>
<Image>
0471195.jpg
</Image>
</ITEM>
<ITEM Id="0471195">
<Category>
<![CDATA[Homogenizers]]>
</Category>
<Image>
0471196.jpg
</Image>
</ITEM>
</ProductData>
"""
bad_xml_item_count = 0
data = {}
xml_data = minidom.parseString(xml).getElementsByTagName('ProductData')
parts = xml_data[0].getElementsByTagName('ITEM')
for p in parts:
try:
part_id = p.attributes['Id'].value.strip()
except(KeyError):
bad_xml_item_count += 1
continue
if not part_id:
bad_xml_item_count += 1
continue
part_image = p.getElementsByTagName('Image')[0].firstChild.nodeValue.strip()
part_category = p.getElementsByTagName('Category')[0].firstChild.data.strip()
print '\t'.join([part_id, part_category, part_image])
</code></pre>
| 10
|
2009-02-27T23:20:56Z
| 597,111
|
<p>CDATA is its own node, so the Category elements here actually have three children, a whitespace text node, the CDATA node, and another whitespace node. You're just looking at the wrong one, is all. I don't see any more obvious way to query for the CDATA node, but you can pull it out like this:</p>
<pre><code>[n for n in category.childNodes if n.nodeType==category.CDATA_SECTION_NODE][0]
</code></pre>
| 6
|
2009-02-27T23:44:06Z
|
[
"python",
"xml"
] |
xml.dom.minidom: Getting CDATA values
| 597,058
|
<p>I'm able to get the value in the image tag (see XML below), but not the Category tag. The difference is one is a CDATA section and the other is just a string. Any help would be appreciated.</p>
<pre><code>from xml.dom import minidom
xml = """<?xml version="1.0" ?>
<ProductData>
<ITEM Id="0471195">
<Category>
<![CDATA[Homogenizers]]>
</Category>
<Image>
0471195.jpg
</Image>
</ITEM>
<ITEM Id="0471195">
<Category>
<![CDATA[Homogenizers]]>
</Category>
<Image>
0471196.jpg
</Image>
</ITEM>
</ProductData>
"""
bad_xml_item_count = 0
data = {}
xml_data = minidom.parseString(xml).getElementsByTagName('ProductData')
parts = xml_data[0].getElementsByTagName('ITEM')
for p in parts:
try:
part_id = p.attributes['Id'].value.strip()
except(KeyError):
bad_xml_item_count += 1
continue
if not part_id:
bad_xml_item_count += 1
continue
part_image = p.getElementsByTagName('Image')[0].firstChild.nodeValue.strip()
part_category = p.getElementsByTagName('Category')[0].firstChild.data.strip()
print '\t'.join([part_id, part_category, part_image])
</code></pre>
| 10
|
2009-02-27T23:20:56Z
| 30,481,821
|
<p>I've ran into a similar problem. My solution was similar to what ironfroggy answered, but implemented in a more general fashion:</p>
<pre><code>for node in parentNode.childNodes:
if node.nodeType == 4:
cdataContent = node.data.strip()
</code></pre>
<p>CDATA's node type is 4 (<a href="https://developer.mozilla.org/en/docs/Web/API/Node/nodeType" rel="nofollow"><code>CDATA_SECTION_NODE</code></a>)</p>
| 2
|
2015-05-27T12:00:47Z
|
[
"python",
"xml"
] |
Converting an object into a subclass in Python?
| 597,199
|
<p>Lets say I have a library function that I cannot change that produces an object of class A, and I have created a class B that inherits from A. </p>
<p>What is the most straightforward way of using the library function to produce an object of class B?</p>
<p>edit- I was asked in a comment for more detail, so here goes:</p>
<p>PyTables is a package that handles hierarchical datasets in python. The bit I use most is its ability to manage data that is partially on disk. It provides an 'Array' type which only comes with extended slicing, but I need to select arbitrary rows. Numpy offers this capability - you can select by providing a boolean array of the same length as the array you are selecting from. Therefore, I wanted to subclass Array to add this new functionality.</p>
<p>In a more abstract sense this is a problem I have considered before. The usual solution is as has already been suggested- Have a constructor for B that takes an A and additional arguments, and then pulls out the relevant bits of A to insert into B. As it seemed like a fairly basic problem, I asked to question to see if there were any standard solutions I wasn't aware of.</p>
| 14
|
2009-02-28T00:34:11Z
| 597,243
|
<p>Since the library function returns an A, you can't make it return a B without changing it.</p>
<p>One thing you can do is write a function to take the fields of the A instance and copy them over into a new B instance:</p>
<pre><code>class A: # defined by the library
def __init__(self, field):
self.field = field
class B(A): # your fancy new class
def __init__(self, field, field2):
self.field = field
self.field2 = field2 # B has some fancy extra stuff
def b_from_a(a_instance, field2):
"""Given an instance of A, return a new instance of B."""
return B(a_instance.field, field2)
a = A("spam") # this could be your A instance from the library
b = b_from_a(a, "ham") # make a new B which has the data from a
print b.field, b.field2 # prints "spam ham"
</code></pre>
<p>Edit: depending on your situation, <strong>composition instead of inheritance</strong> could be a good bet; that is your B class could just contain an instance of A instead of inheriting:</p>
<pre><code>class B2: # doesn't have to inherit from A
def __init__(self, a, field2):
self._a = a # using composition instead
self.field2 = field2
@property
def field(self): # pass accesses to a
return self._a.field
# could provide setter, deleter, etc
a = A("spam")
b = B2(a, "ham")
print b.field, b.field2 # prints "spam ham"
</code></pre>
| 11
|
2009-02-28T00:57:05Z
|
[
"python"
] |
Converting an object into a subclass in Python?
| 597,199
|
<p>Lets say I have a library function that I cannot change that produces an object of class A, and I have created a class B that inherits from A. </p>
<p>What is the most straightforward way of using the library function to produce an object of class B?</p>
<p>edit- I was asked in a comment for more detail, so here goes:</p>
<p>PyTables is a package that handles hierarchical datasets in python. The bit I use most is its ability to manage data that is partially on disk. It provides an 'Array' type which only comes with extended slicing, but I need to select arbitrary rows. Numpy offers this capability - you can select by providing a boolean array of the same length as the array you are selecting from. Therefore, I wanted to subclass Array to add this new functionality.</p>
<p>In a more abstract sense this is a problem I have considered before. The usual solution is as has already been suggested- Have a constructor for B that takes an A and additional arguments, and then pulls out the relevant bits of A to insert into B. As it seemed like a fairly basic problem, I asked to question to see if there were any standard solutions I wasn't aware of.</p>
| 14
|
2009-02-28T00:34:11Z
| 597,249
|
<p>Monkeypatch the library?</p>
<p>For example,</p>
<pre><code>import other_library
other_library.function_or_class_to_replace = new_function
</code></pre>
<p>Poof, it returns whatever you want it to return.</p>
<p>Monkeypatch A.<strong>new</strong> to return an instance of B?</p>
<p>After you call obj = A(), change the result so obj.<strong>class</strong> = B?</p>
| 1
|
2009-02-28T00:59:08Z
|
[
"python"
] |
Converting an object into a subclass in Python?
| 597,199
|
<p>Lets say I have a library function that I cannot change that produces an object of class A, and I have created a class B that inherits from A. </p>
<p>What is the most straightforward way of using the library function to produce an object of class B?</p>
<p>edit- I was asked in a comment for more detail, so here goes:</p>
<p>PyTables is a package that handles hierarchical datasets in python. The bit I use most is its ability to manage data that is partially on disk. It provides an 'Array' type which only comes with extended slicing, but I need to select arbitrary rows. Numpy offers this capability - you can select by providing a boolean array of the same length as the array you are selecting from. Therefore, I wanted to subclass Array to add this new functionality.</p>
<p>In a more abstract sense this is a problem I have considered before. The usual solution is as has already been suggested- Have a constructor for B that takes an A and additional arguments, and then pulls out the relevant bits of A to insert into B. As it seemed like a fairly basic problem, I asked to question to see if there were any standard solutions I wasn't aware of.</p>
| 14
|
2009-02-28T00:34:11Z
| 597,324
|
<p>This can be done if the initializer of the subclass can handle it, or you write an explicit upgrader. Here is an example:</p>
<pre><code>class A(object):
def __init__(self):
self.x = 1
class B(A):
def __init__(self):
super(B, self).__init__()
self._init_B()
def _init_B(self):
self.x += 1
a = A()
b = a
b.__class__ = B
b._init_B()
assert b.x == 2
</code></pre>
| 13
|
2009-02-28T01:40:07Z
|
[
"python"
] |
Converting an object into a subclass in Python?
| 597,199
|
<p>Lets say I have a library function that I cannot change that produces an object of class A, and I have created a class B that inherits from A. </p>
<p>What is the most straightforward way of using the library function to produce an object of class B?</p>
<p>edit- I was asked in a comment for more detail, so here goes:</p>
<p>PyTables is a package that handles hierarchical datasets in python. The bit I use most is its ability to manage data that is partially on disk. It provides an 'Array' type which only comes with extended slicing, but I need to select arbitrary rows. Numpy offers this capability - you can select by providing a boolean array of the same length as the array you are selecting from. Therefore, I wanted to subclass Array to add this new functionality.</p>
<p>In a more abstract sense this is a problem I have considered before. The usual solution is as has already been suggested- Have a constructor for B that takes an A and additional arguments, and then pulls out the relevant bits of A to insert into B. As it seemed like a fairly basic problem, I asked to question to see if there were any standard solutions I wasn't aware of.</p>
| 14
|
2009-02-28T00:34:11Z
| 29,256,784
|
<p>you can actually change the <code>.__class__</code> attribute of the object <em>if you know what you're doing</em>:</p>
<pre class="lang-py prettyprint-override"><code>In [1]: class A(object):
...: def foo(self):
...: return "foo"
...:
In [2]: class B(object):
...: def foo(self):
...: return "bar"
...:
In [3]: a = A()
In [4]: a.foo()
Out[4]: 'foo'
In [5]: a.__class__
Out[5]: __main__.A
In [6]: a.__class__ = B
In [7]: a.foo()
Out[7]: 'bar'
</code></pre>
| 2
|
2015-03-25T13:16:41Z
|
[
"python"
] |
Python: Getting an IPv6 socket to receive packets destined for the Subnet-Routers Anycast address
| 597,225
|
<p>How do you get a socket to receive packets destined for the IPv6 Subnet-Routers Anycast address?</p>
<p>I haven't been able to find any informationn on how to do this.</p>
<p>In a fit of desparation, I've tried using socket.setsockopt as you would to join a multicast group:</p>
<pre><code># 7 is the interface number
s = socket(AF_INET6, SOCK_DGRAM)
packed_iface_num = struct.pack("I", 7)
group = inet_pton(AF_INET6, 'fd36:d00d:d00d:47cb::') + packed_iface_num
# socket.error: (22, 'Invalid argument')
s.setsockopt(IPPROTO_IPV6, IPV6_JOIN_GROUP, group)
</code></pre>
<p>And also using bind</p>
<pre><code># socket.error: (99, 'Cannot assign requested address')
s.bind(('fd36:773e:6b4c:47cb::', 9876))
</code></pre>
<p>As expected, neither of these worked. Is there a way to do this?</p>
| 5
|
2009-02-28T00:45:31Z
| 606,511
|
<p>Instead of <code>IPV6_JOIN_GROUP</code>, try passing <code>IPV6_JOIN_ANYCAST</code> to your <code>s.setsockopt()</code> code. Unfortunately the Python <code>socket</code> module doesn't define it but you should be able to pass the integer equivalent instead. In Linux <a href="http://lxr.linux.no/linux%2Bv2.6.28.7/include/linux/in6.h#L181" rel="nofollow"><code>IPV6_JOIN_ANYCAST</code></a> is <code>27</code> and <a href="http://lxr.linux.no/linux%2Bv2.6.28.7/include/linux/in6.h#L182" rel="nofollow"><code>IPV6_LEAVE_ANYCAST</code></a> is <code>28</code>. (defined in /usr/include/linux/in6.h)</p>
<p>The best documentation I could find is from this <a href="http://lkml.indiana.edu/hypermail/linux/net/0208.3/0028.html" rel="nofollow">lkml e-mail describing the anycast patch to the Linux kernel</a>:</p>
<blockquote>
The application interface for joining and leaving anycast groups is 2
new setsockopt() calls: IPV6_JOIN_ANYCAST and IPV6_LEAVE_ANYCAST. The arguments
are the same as the corresponding multicast operations.
</blockquote>
<p>May the dancing kame be with you!</p>
| 2
|
2009-03-03T14:11:59Z
|
[
"python",
"networking",
"ipv6"
] |
Python: Getting an IPv6 socket to receive packets destined for the Subnet-Routers Anycast address
| 597,225
|
<p>How do you get a socket to receive packets destined for the IPv6 Subnet-Routers Anycast address?</p>
<p>I haven't been able to find any informationn on how to do this.</p>
<p>In a fit of desparation, I've tried using socket.setsockopt as you would to join a multicast group:</p>
<pre><code># 7 is the interface number
s = socket(AF_INET6, SOCK_DGRAM)
packed_iface_num = struct.pack("I", 7)
group = inet_pton(AF_INET6, 'fd36:d00d:d00d:47cb::') + packed_iface_num
# socket.error: (22, 'Invalid argument')
s.setsockopt(IPPROTO_IPV6, IPV6_JOIN_GROUP, group)
</code></pre>
<p>And also using bind</p>
<pre><code># socket.error: (99, 'Cannot assign requested address')
s.bind(('fd36:773e:6b4c:47cb::', 9876))
</code></pre>
<p>As expected, neither of these worked. Is there a way to do this?</p>
| 5
|
2009-02-28T00:45:31Z
| 918,381
|
<p>The <code>IPV6_JOIN_ANYCAST</code> and <code>IPV6_LEAVE_ANYCAST</code> socket options are non-standard Linux-isms.</p>
<p>If you'd like your code to be <em>portable</em>, then you should probably do it the standard way, i.e. assign the subnet routers anycast address to the appropriate interface, then bind your socket to the wildcard address and discard everything not sent to the subnet router anycast address. Remember, you're not supposed to send packets with the anycast address in the source field, and you can't open a read-only socket in the standard sockets API.</p>
<p>Assigning an interface address should be a privileged operation on any reasonable operating system, and that's the part that isn't going to be standard whatever you do. If you must do that programmatically, then it will mean (on BSD for example) using something like the <code>SIOCAIFADDR_IN6</code> code and the <code>ioctl()</code> system call. Make sure to set the <code>IN6_IFF_ANYCAST</code> flag in the <code>ifra_flags</code> field of the interface alias request structure.</p>
| 0
|
2009-05-27T23:00:50Z
|
[
"python",
"networking",
"ipv6"
] |
Python: efficiently join chunks of bytes into one big chunk?
| 597,289
|
<p>I'm trying to jury-rig the <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134" rel="nofollow">Amazon S3 python library</a> to allow chunked handling of large files. Right now it does a "self.body = http_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any control over it.</p>
<p>My current approach is to try to keep the interface for the library the same but provide a callback after reading each chunk of data. Something like the following:</p>
<pre><code>data = []
while True:
chunk = http_response.read(CHUNKSIZE)
if not chunk:
break
if callback:
callback(chunk)
data.append(chunk)
</code></pre>
<p>Now I need to do something like:</p>
<pre><code>self.body = ''.join(data)
</code></pre>
<p>Is <em>join</em> the right way to do this or is there another (better) way of putting all the chunks together?</p>
| 1
|
2009-02-28T01:18:53Z
| 597,296
|
<p>In python3, <code>bytes</code> objects are distinct from <code>str</code>, but I don't know any reason why there would be anything wrong with this.</p>
| 0
|
2009-02-28T01:21:23Z
|
[
"python",
"amazon-s3"
] |
Python: efficiently join chunks of bytes into one big chunk?
| 597,289
|
<p>I'm trying to jury-rig the <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134" rel="nofollow">Amazon S3 python library</a> to allow chunked handling of large files. Right now it does a "self.body = http_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any control over it.</p>
<p>My current approach is to try to keep the interface for the library the same but provide a callback after reading each chunk of data. Something like the following:</p>
<pre><code>data = []
while True:
chunk = http_response.read(CHUNKSIZE)
if not chunk:
break
if callback:
callback(chunk)
data.append(chunk)
</code></pre>
<p>Now I need to do something like:</p>
<pre><code>self.body = ''.join(data)
</code></pre>
<p>Is <em>join</em> the right way to do this or is there another (better) way of putting all the chunks together?</p>
| 1
|
2009-02-28T01:18:53Z
| 597,302
|
<p><code>join</code> seems fine if you really do need to put the entire string together, but then you just wind up storing the whole thing in RAM anyway. In a situation like this, I would try to see if there's a way to process each part of the string and then discard the processed part, so you only need to hold a fixed number of bytes in memory at a time. That's usually the point of the callback approach. (If you can only process part of a chunk at a time, use a buffer as a queue to store the unprocessed data.)</p>
| 0
|
2009-02-28T01:24:43Z
|
[
"python",
"amazon-s3"
] |
Python: efficiently join chunks of bytes into one big chunk?
| 597,289
|
<p>I'm trying to jury-rig the <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134" rel="nofollow">Amazon S3 python library</a> to allow chunked handling of large files. Right now it does a "self.body = http_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any control over it.</p>
<p>My current approach is to try to keep the interface for the library the same but provide a callback after reading each chunk of data. Something like the following:</p>
<pre><code>data = []
while True:
chunk = http_response.read(CHUNKSIZE)
if not chunk:
break
if callback:
callback(chunk)
data.append(chunk)
</code></pre>
<p>Now I need to do something like:</p>
<pre><code>self.body = ''.join(data)
</code></pre>
<p>Is <em>join</em> the right way to do this or is there another (better) way of putting all the chunks together?</p>
| 1
|
2009-02-28T01:18:53Z
| 597,304
|
<p>''join() is the best method for joining chunks of data. The alternative boils down to repeated concatenation, which is O(n**2) due to the immutability of strings and the need to create more at every concatenation. Given, this repeated concatenation is optimized by recent versions of CPython if used with += to become O(n), but that optimization only gives it a rough equivalent to ''.join() anyway, which is explicitly O(n) over the number of bytes.</p>
| 3
|
2009-02-28T01:24:44Z
|
[
"python",
"amazon-s3"
] |
Python: efficiently join chunks of bytes into one big chunk?
| 597,289
|
<p>I'm trying to jury-rig the <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134" rel="nofollow">Amazon S3 python library</a> to allow chunked handling of large files. Right now it does a "self.body = http_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any control over it.</p>
<p>My current approach is to try to keep the interface for the library the same but provide a callback after reading each chunk of data. Something like the following:</p>
<pre><code>data = []
while True:
chunk = http_response.read(CHUNKSIZE)
if not chunk:
break
if callback:
callback(chunk)
data.append(chunk)
</code></pre>
<p>Now I need to do something like:</p>
<pre><code>self.body = ''.join(data)
</code></pre>
<p>Is <em>join</em> the right way to do this or is there another (better) way of putting all the chunks together?</p>
| 1
|
2009-02-28T01:18:53Z
| 597,338
|
<p>hm - what problem are you trying to solve? I suspect the answer depends on what you are trying to do with the data.</p>
<p>Since in general you don't want a whole 3Gb file in memory, I'd not store the chunks in an array, but iterate over the http_response and write it straight to disk, in a temporary or persistent file using the normal write() method on an appropriate file handle.</p>
<p>if you do want two copies of the data in memory, your method will require be at least 6Gb for your hypothetical 3Gb file, which presumably is significant for most hardware. I know that array join methods are fast and all that, but since this is a really ram-constrained process maybe you want to find some way of doing it better? StringIO (<a href="http://docs.python.org/library/stringio.html" rel="nofollow">http://docs.python.org/library/stringio.html</a>) creates string objects that can be appended to in memory; the pure python one, since it has to work with immutable strings, just uses your array join trick internally, but the c-based cStringIO might actually append to a memory buffer internall. I don't have its source code to hand, so that would bear checking.</p>
<p>if you do wish to do some kind of analysis on the data and really wish to keep in in memory with minimal overhead, you might want to consider some of the byte array objets from Numeric/NumPy as an alternative to StringIO. they are high-performance code optimised for large arrays and might be what you need.</p>
<p>as a useful example, for a general-purpose file-handling object which has memory-efficient iterator-friendly approach you might want to check out the django File obeject chunk handling code:
<a href="http://code.djangoproject.com/browser/django/trunk/django/core/files/base.py" rel="nofollow">http://code.djangoproject.com/browser/django/trunk/django/core/files/base.py</a>.</p>
| 2
|
2009-02-28T01:52:52Z
|
[
"python",
"amazon-s3"
] |
FOSS HTML to PDF in Python, .Net or command line?
| 597,348
|
<p>I have google as much as I possible, checked stackoverflow several times, and yet I can not find a good <strong>html to pdf converter</strong> that can handle css. Is there a free and open source solution (even for commercial usage)? There are many solutions, with huge variety of price ranges, but I was looking for something open source and free. I have tried PISA for Python and it works fairly well, but is not free for commercial usage. Is there anything for .Net? I have not had success with iTextSharp. </p>
| 0
|
2009-02-28T01:56:26Z
| 597,355
|
<p>I've wkhtmltopdf used on a couple of projects. <a href="http://code.google.com/p/wkhtmltopdf/" rel="nofollow">http://code.google.com/p/wkhtmltopdf/</a>. It uses the webkit rendering engine, which powers the Safari browser. You'll get completely up to date rendering just like a web browser with CSS and all.</p>
<p>Oh, and it's open source.</p>
| 5
|
2009-02-28T02:01:12Z
|
[
"c#",
".net",
"python",
"html-to-pdf"
] |
FOSS HTML to PDF in Python, .Net or command line?
| 597,348
|
<p>I have google as much as I possible, checked stackoverflow several times, and yet I can not find a good <strong>html to pdf converter</strong> that can handle css. Is there a free and open source solution (even for commercial usage)? There are many solutions, with huge variety of price ranges, but I was looking for something open source and free. I have tried PISA for Python and it works fairly well, but is not free for commercial usage. Is there anything for .Net? I have not had success with iTextSharp. </p>
| 0
|
2009-02-28T01:56:26Z
| 597,361
|
<p>I haven't found a good FOSS solution, but I can say that <a href="http://www.princexml.com/" rel="nofollow">PrinceXML</a> works very well, provides quite a bit of functionality through the command-line and is priced very reasonably. IIRC, the free version appends a cover page to each PDF you produce, which may or may not be a deal-killer for you, but you should definitely check it out.</p>
| 2
|
2009-02-28T02:05:04Z
|
[
"c#",
".net",
"python",
"html-to-pdf"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.