title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
Calling from a parent file in python | 403,822 | <p>I have a file called main.py and a file called classes.py</p>
<p>main.py contains the application and what's happening while class.py contains some classes.</p>
<p>main.py has the following code</p>
<p><strong>main.py</strong></p>
<pre><code>import classes
def addItem(text):
print text
myClass = classes.ExampleClass()
</code></pre>
<p>And then we have classes.py</p>
<p><strong>classes.py</strong></p>
<pre><code>class ExampleClass (object):
def __init__(self):
addItem('bob')
</code></pre>
<p>Surprisingly enough that's not the actual code I am using because I've stripped out anything that'd get in the way of you seeing what I want to do. I want to be able to call a method that's defined in main.py from a class within classes.py. How do I do this?</p>
<p>Thanks in advance</p>
| 3 | 2008-12-31T19:14:59Z | 403,839 | <p>I would suggest putting common functions either in classes.py, or probably even better in a third module, perhaps utils.py.</p>
| 1 | 2008-12-31T19:22:40Z | [
"python"
] |
Calling from a parent file in python | 403,822 | <p>I have a file called main.py and a file called classes.py</p>
<p>main.py contains the application and what's happening while class.py contains some classes.</p>
<p>main.py has the following code</p>
<p><strong>main.py</strong></p>
<pre><code>import classes
def addItem(text):
print text
myClass = classes.ExampleClass()
</code></pre>
<p>And then we have classes.py</p>
<p><strong>classes.py</strong></p>
<pre><code>class ExampleClass (object):
def __init__(self):
addItem('bob')
</code></pre>
<p>Surprisingly enough that's not the actual code I am using because I've stripped out anything that'd get in the way of you seeing what I want to do. I want to be able to call a method that's defined in main.py from a class within classes.py. How do I do this?</p>
<p>Thanks in advance</p>
| 3 | 2008-12-31T19:14:59Z | 403,850 | <p>All your executable code should be inside a <code>if __name__ == "__main__"</code> . This will prevent it from being execucted when imported as a module. In main.py</p>
<pre><code>if __name__=="__main__":
myClass = classes.ExampleClass()
</code></pre>
<p>However, as dF states, it is probably better to refactor at this stage than to try to resolve cyclic dependencies.</p>
| 1 | 2008-12-31T19:26:31Z | [
"python"
] |
Calling from a parent file in python | 403,822 | <p>I have a file called main.py and a file called classes.py</p>
<p>main.py contains the application and what's happening while class.py contains some classes.</p>
<p>main.py has the following code</p>
<p><strong>main.py</strong></p>
<pre><code>import classes
def addItem(text):
print text
myClass = classes.ExampleClass()
</code></pre>
<p>And then we have classes.py</p>
<p><strong>classes.py</strong></p>
<pre><code>class ExampleClass (object):
def __init__(self):
addItem('bob')
</code></pre>
<p>Surprisingly enough that's not the actual code I am using because I've stripped out anything that'd get in the way of you seeing what I want to do. I want to be able to call a method that's defined in main.py from a class within classes.py. How do I do this?</p>
<p>Thanks in advance</p>
| 3 | 2008-12-31T19:14:59Z | 403,875 | <p>The suggestions to refactor are good ones. If you have to leave the files as they are, then you can edit main.py to make sure that nothing is executed simply by importing the file, then import main in the function that needs it:</p>
<pre><code>class ExampleClass (object):
def __init__(self):
import main
main.addItem('bob')
</code></pre>
<p>This avoids the circular imports, but isn't as nice as refactoring in the first place...</p>
| 3 | 2008-12-31T19:38:23Z | [
"python"
] |
using results from a sql query in a python program in another sql query | 403,897 | <p>sorry for my previous question which was very ambiguous, but i think if i get the answer to this question I can work it out.
In the program below i have selected the barcodes of products where the amount is less than the quantity. I want to say, that if the barcodes(in the fridge table) match barcodes in another table(products), set the stock field equal to 0. The problem Im getting is that the program is trying to match all the barcodes that it found in the query against single barcodes in the products table(thats what I think). does anyone know what to do. thanks a million. lincoln.</p>
<pre><code>import MySQLdb
def order():
db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge')
cursor = db.cursor()
cursor.execute('select barcode from fridge where amount < quantity')
db.commit()
row = cursor.fetchall()
cursor.execute('update products set stock = 0 where barcode = %s', row)
</code></pre>
| 0 | 2008-12-31T19:44:58Z | 403,941 | <pre><code>UPDATE products SET stock = 0 WHERE barcode IN (
SELECT fridge.barcode FROM fridge WHERE fridge.amount < fridge.quantity );
</code></pre>
<p>I know this doesn't answer the question exactly but two SQL statements are not required.</p>
<p>To do it in python:</p>
<pre><code>import MySQLdb
def order():
db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge')
cursor = db.cursor()
cursor.execute('select barcode from fridge where amount < quantity')
db.commit()
rows = cursor.fetchall()
for row in rows
cursor.execute('update products set stock = 0 where barcode = %s', row[0])
</code></pre>
| 5 | 2008-12-31T20:03:09Z | [
"python",
"sql"
] |
using results from a sql query in a python program in another sql query | 403,897 | <p>sorry for my previous question which was very ambiguous, but i think if i get the answer to this question I can work it out.
In the program below i have selected the barcodes of products where the amount is less than the quantity. I want to say, that if the barcodes(in the fridge table) match barcodes in another table(products), set the stock field equal to 0. The problem Im getting is that the program is trying to match all the barcodes that it found in the query against single barcodes in the products table(thats what I think). does anyone know what to do. thanks a million. lincoln.</p>
<pre><code>import MySQLdb
def order():
db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge')
cursor = db.cursor()
cursor.execute('select barcode from fridge where amount < quantity')
db.commit()
row = cursor.fetchall()
cursor.execute('update products set stock = 0 where barcode = %s', row)
</code></pre>
| 0 | 2008-12-31T19:44:58Z | 403,947 | <p>This is more of SQL query than Python, but still I will try to answer that:
(I haven't worked with MySQL but PostgreSQL, so there might slight variation in interpretation of things here).</p>
<p>when you did</p>
<pre><code>cursor.execute('select barcode from fridge where amount < quantity')
db.commit()
row = cursor.fetchall()
</code></pre>
<p>the variable 'row' now is a resultset (to understand: a list of rows from the database)
something like [(barcode1), (barcode2), (barcode3)..]</p>
<p>when you do the update statement</p>
<pre><code>cursor.execute('update products set stock = 0 where barcode = %s', row)
</code></pre>
<p>this turns into something like:</p>
<pre><code>update products set stock = 0 where barcode = [(barcode1), (barcode2), (barcode3)..]
</code></pre>
<p>which is not a correct SQL statement.</p>
<p>you should do something like this:</p>
<pre><code>cursor.execute('update products set stock = 0 where barcode in (%s)', ','.join([each[0] for each in row]))
</code></pre>
<p>or better, the optimized thing:</p>
<pre><code>import MySQLdb
def order():
db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge')
cursor = db.cursor()
cursor.execute('update products set stock = 0 where barcode in (select barcode from fridge where amount < quantity)')
db.commit()
</code></pre>
<p>Well, to add more you have a db.commit() after a select query and not after an update query, thats a basic fault. Select is idempotent, doesn't need commit, whereas Update does. I will strongly recommend you to go through some SQL before continuing.</p>
| 4 | 2008-12-31T20:09:21Z | [
"python",
"sql"
] |
All code in one file | 403,934 | <p>After asking <a href="http://stackoverflow.com/questions/391879/organising-my-python-project">organising my Python project</a> and then <a href="http://stackoverflow.com/questions/403822/calling-from-a-parent-file-in-python">calling from a parent file in Python</a> it's occurring to me that it'll be so much easier to put all my code in one file (data will be read in externally).</p>
<p>I've always thought that this was bad project organisation but it seems to be the easiest way to deal with the problems I'm thinking I will face. Have I simply gotten the wrong end of the stick with file count or have I not seen some great guide on large (for me) projects?</p>
| 5 | 2008-12-31T19:59:29Z | 403,944 | <p>If you are planning to use any kind of SCM then you are going to be screwed. Having one file is a guaranteed way to have lots of collisions and merges that will be painstaking to deal with over time.</p>
<p>Stick to conventions and break apart your files. If nothing more than to save the guy who will one day have to maintain your code...</p>
| 12 | 2008-12-31T20:04:33Z | [
"python",
"version-control",
"project-management"
] |
All code in one file | 403,934 | <p>After asking <a href="http://stackoverflow.com/questions/391879/organising-my-python-project">organising my Python project</a> and then <a href="http://stackoverflow.com/questions/403822/calling-from-a-parent-file-in-python">calling from a parent file in Python</a> it's occurring to me that it'll be so much easier to put all my code in one file (data will be read in externally).</p>
<p>I've always thought that this was bad project organisation but it seems to be the easiest way to deal with the problems I'm thinking I will face. Have I simply gotten the wrong end of the stick with file count or have I not seen some great guide on large (for me) projects?</p>
| 5 | 2008-12-31T19:59:29Z | 403,949 | <p>If your code is going to work together all the time anyway, and isn't useful separately, there's nothing wrong with keeping everything in one file. I can think of at least popular package (BeautifulSoup) that does this. Sure makes installation easier.</p>
<p>Of course, if it seems, down the road, that you could use part of your code with another project, or if maintainance starts to be an issue, then worry about organizing your project differently. </p>
<p>It seems to me from the questions you've been asking lately that you're worrying about all of this a bit prematurely. Often, for me, these sorts of issues are better tackled a little later on in the solution. Especially for smaller projects, my goal is to get a solution that is correct, and <em>then</em> optimal.</p>
| 4 | 2008-12-31T20:11:12Z | [
"python",
"version-control",
"project-management"
] |
All code in one file | 403,934 | <p>After asking <a href="http://stackoverflow.com/questions/391879/organising-my-python-project">organising my Python project</a> and then <a href="http://stackoverflow.com/questions/403822/calling-from-a-parent-file-in-python">calling from a parent file in Python</a> it's occurring to me that it'll be so much easier to put all my code in one file (data will be read in externally).</p>
<p>I've always thought that this was bad project organisation but it seems to be the easiest way to deal with the problems I'm thinking I will face. Have I simply gotten the wrong end of the stick with file count or have I not seen some great guide on large (for me) projects?</p>
| 5 | 2008-12-31T19:59:29Z | 403,952 | <p>It's always a now verses then argument. If you're under the gun to get it done, do it. Source control will be a problem later, as with many things there's no black and white answer. You need to be responsible to both your deadline and the long term maintenance of the code.</p>
| 2 | 2008-12-31T20:14:52Z | [
"python",
"version-control",
"project-management"
] |
All code in one file | 403,934 | <p>After asking <a href="http://stackoverflow.com/questions/391879/organising-my-python-project">organising my Python project</a> and then <a href="http://stackoverflow.com/questions/403822/calling-from-a-parent-file-in-python">calling from a parent file in Python</a> it's occurring to me that it'll be so much easier to put all my code in one file (data will be read in externally).</p>
<p>I've always thought that this was bad project organisation but it seems to be the easiest way to deal with the problems I'm thinking I will face. Have I simply gotten the wrong end of the stick with file count or have I not seen some great guide on large (for me) projects?</p>
| 5 | 2008-12-31T19:59:29Z | 404,003 | <p>If that's the best way to organise it, you're probably doing something wrong.</p>
<p>If it's more than just a toy program or a simple script, then you should break it up into separate files, etc. It's the only sane way of doing it. When your project gets big enough that you need someone else helping on it, then it will make the SCM a whole bunch easier.</p>
<p>Additionally, sooner or later you are going to need to add a separate utility to your project, that is going to need some common code/structures. It's far easier to do this if you have separate source files than if you have just one big one.</p>
| 2 | 2008-12-31T20:40:50Z | [
"python",
"version-control",
"project-management"
] |
All code in one file | 403,934 | <p>After asking <a href="http://stackoverflow.com/questions/391879/organising-my-python-project">organising my Python project</a> and then <a href="http://stackoverflow.com/questions/403822/calling-from-a-parent-file-in-python">calling from a parent file in Python</a> it's occurring to me that it'll be so much easier to put all my code in one file (data will be read in externally).</p>
<p>I've always thought that this was bad project organisation but it seems to be the easiest way to deal with the problems I'm thinking I will face. Have I simply gotten the wrong end of the stick with file count or have I not seen some great guide on large (for me) projects?</p>
| 5 | 2008-12-31T19:59:29Z | 404,095 | <p>Since <a href="http://stackoverflow.com/questions/403822/calling-from-a-parent-file-in-python">Calling from a parent file in Python</a> indicates serious design problems, I'd say that you have two choices.</p>
<ol>
<li><p>Don't have a library module try to call back to main. You'll have to rewrite things to fix this. </p>
<p>[An imported component calling the main program is an improper dependency. And Python doesn't support it because it's a poor design.]</p></li>
<li><p>Put it all in one file until you figure out a better design with proper one-way dependencies. Then you'll have to rewrite it to fix the dependency problems.</p></li>
</ol>
<p>A module (a single file) should be a logical piece of related code. Not everything. Not a single class definition. There's a middle ground of modularity. </p>
<p>Additionally, there should be a proper one-way dependency graph from main program to components (which do NOT depend on the main program) to utility libraries and what-not (that do not know about the components OR the main program. </p>
<p>Circular (or mutual) dependencies often indicate a design problem. Callbacks are one way out of the problem. Another way is to decompose the circular elements to get a proper one-way graph.</p>
| 2 | 2008-12-31T21:42:25Z | [
"python",
"version-control",
"project-management"
] |
All code in one file | 403,934 | <p>After asking <a href="http://stackoverflow.com/questions/391879/organising-my-python-project">organising my Python project</a> and then <a href="http://stackoverflow.com/questions/403822/calling-from-a-parent-file-in-python">calling from a parent file in Python</a> it's occurring to me that it'll be so much easier to put all my code in one file (data will be read in externally).</p>
<p>I've always thought that this was bad project organisation but it seems to be the easiest way to deal with the problems I'm thinking I will face. Have I simply gotten the wrong end of the stick with file count or have I not seen some great guide on large (for me) projects?</p>
| 5 | 2008-12-31T19:59:29Z | 404,228 | <p>Looking at your earlier questions I would say <strong>all code in one file would be a good intermediate state</strong> on the way to a <strong>complete refactoring of your project</strong>. To do this you'll need a <strong>regression test suite</strong> to make sure you don't break the project while refactoring it.</p>
<p><strong>Once all your code is in one file</strong>, I suggest iterating on the following:</p>
<ol>
<li><p>Identify a small group of interdependent classes.</p></li>
<li><p>Pull those classes into a separate file.</p></li>
<li><p><strong>Add unit tests</strong> for the new separate file.</p></li>
<li><p>Retest the entire project.</p></li>
</ol>
<p>Depending on the size of your project, <strong>it shouldn't take too many iterations</strong> for you to reach something reasonable.</p>
| 2 | 2008-12-31T23:02:44Z | [
"python",
"version-control",
"project-management"
] |
Python program to calculate harmonic series | 404,346 | <p>Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4...</p>
| 4 | 2009-01-01T00:55:16Z | 404,354 | <p>This ought to do the trick.</p>
<pre><code>def calc_harmonic(n):
return sum(1.0/d for d in range(2,n+1))
</code></pre>
| 3 | 2009-01-01T00:59:15Z | [
"python",
"math"
] |
Python program to calculate harmonic series | 404,346 | <p>Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4...</p>
| 4 | 2009-01-01T00:55:16Z | 404,361 | <p>How about this:</p>
<pre><code>partialsum = 0
for i in xrange(1,1000000):
partialsum += 1.0 / i
print partialsum
</code></pre>
<p>where 1000000 is the upper bound.</p>
| 1 | 2009-01-01T01:00:40Z | [
"python",
"math"
] |
Python program to calculate harmonic series | 404,346 | <p>Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4...</p>
| 4 | 2009-01-01T00:55:16Z | 404,364 | <p>The harmonic series diverges, i.e. its sum is infinity..</p>
<p>edit: Unless you want partial sums, but you weren't really clear about that.</p>
| 4 | 2009-01-01T01:02:21Z | [
"python",
"math"
] |
Python program to calculate harmonic series | 404,346 | <p>Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4...</p>
| 4 | 2009-01-01T00:55:16Z | 404,371 | <p>Homework? </p>
<p>It's a divergent series, so it's impossible to sum it for all terms.</p>
<p>I don't know Python, but I know how to write it in Java.</p>
<pre><code>public class Harmonic
{
private static final int DEFAULT_NUM_TERMS = 10;
public static void main(String[] args)
{
int numTerms = ((args.length > 0) ? Integer.parseInt(args[0]) : DEFAULT_NUM_TERMS);
System.out.println("sum of " + numTerms + " terms=" + sum(numTerms));
}
public static double sum(int numTerms)
{
double sum = 0.0;
if (numTerms > 0)
{
for (int k = 1; k <= numTerms; ++k)
{
sum += 1.0/k;
}
}
return sum;
}
}
</code></pre>
| 0 | 2009-01-01T01:06:44Z | [
"python",
"math"
] |
Python program to calculate harmonic series | 404,346 | <p>Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4...</p>
| 4 | 2009-01-01T00:55:16Z | 404,425 | <p><a href="http://stackoverflow.com/questions/404346/python-program-to-calculate-harmonic-series#404354">@recursive's solution</a> is correct for a floating point approximation. If you prefer, you can get the exact answer in Python 3.0 using the fractions module:</p>
<pre><code>>>> from fractions import Fraction
>>> def calc_harmonic(n):
... return sum(Fraction(1, d) for d in range(1, n + 1))
...
>>> calc_harmonic(20) # sum of the first 20 terms
Fraction(55835135, 15519504)
</code></pre>
<p>Note that the number of digits grows quickly so this will require a lot of memory for large n. You could also use a generator to look at the series of partial sums if you wanted to get really fancy.</p>
| 12 | 2009-01-01T02:31:41Z | [
"python",
"math"
] |
Python program to calculate harmonic series | 404,346 | <p>Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4...</p>
| 4 | 2009-01-01T00:55:16Z | 404,587 | <p>Just a footnote on the other answers that used floating point; starting with the largest divisor and iterating <strong>downward</strong> (toward the reciprocals with largest value) will put off accumulated round-off error as much as possible.</p>
| 4 | 2009-01-01T05:35:22Z | [
"python",
"math"
] |
Python program to calculate harmonic series | 404,346 | <p>Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4...</p>
| 4 | 2009-01-01T00:55:16Z | 404,843 | <p><a href="http://stackoverflow.com/questions/404346/python-program-to-calculate-harmonic-series#404425">@Kiv's answer</a> is correct but it is slow for large n if you don't need an infinite precision. It is better to use an <a href="http://en.wikipedia.org/wiki/Harmonic_number">asymptotic formula</a> in this case:</p>
<p><img src="http://upload.wikimedia.org/math/0/5/1/0516d4c5d9a19f09ffcfc04a6a596928.png" alt="asymptotic expansion for harmonic number" /></p>
<pre><code>#!/usr/bin/env python
from math import log
def H(n):
"""Returns an approximate value of n-th harmonic number.
http://en.wikipedia.org/wiki/Harmonic_number
"""
# Euler-Mascheroni constant
gamma = 0.57721566490153286060651209008240243104215933593992
return gamma + log(n) + 0.5/n - 1./(12*n**2) + 1./(120*n**4)
</code></pre>
<p><a href="http://stackoverflow.com/questions/404346/python-program-to-calculate-harmonic-series#404425">@Kiv's answer</a> for Python 2.6:</p>
<pre><code>from fractions import Fraction
harmonic_number = lambda n: sum(Fraction(1, d) for d in xrange(1, n+1))
</code></pre>
<p>Example:</p>
<pre><code>>>> N = 100
>>> h_exact = harmonic_number(N)
>>> h = H(N)
>>> rel_err = (abs(h - h_exact) / h_exact)
>>> print n, "%r" % h, "%.2g" % rel_err
100 5.1873775176396242 6.8e-16
</code></pre>
<p>At <code>N = 100</code> relative error is less then <code>1e-15</code>.</p>
| 17 | 2009-01-01T10:47:42Z | [
"python",
"math"
] |
Python program to calculate harmonic series | 404,346 | <p>Does anyone know how to write a program in Python that will calculate the addition of the harmonic series. i.e. 1 + 1/2 +1/3 +1/4...</p>
| 4 | 2009-01-01T00:55:16Z | 27,683,292 | <p>A fast, accurate, smooth, complex-valued version of the H function can be calculated using the digamma function as explained <a href="https://en.wikipedia.org/wiki/Harmonic_number#Generalization_to_the_complex_plane" rel="nofollow" title="here">here</a>. The Euler-Mascheroni (gamma) constant and the digamma function are available in the numpy and scipy libraries, respectively.</p>
<pre><code>from numpy import euler_gamma
from scipy.special import digamma
def digamma_H(s):
""" If s is complex the result becomes complex. """
return digamma(s + 1) + euler_gamma
from fractions import Fraction
def Kiv_H(n):
return sum(Fraction(1, d) for d in xrange(1, n + 1))
def J_F_Sebastian_H(n):
return euler_gamma + log(n) + 0.5/n - 1./(12*n**2) + 1./(120*n**4)
</code>
</pre>
<p>Here's a comparison of the three methods for speed and precision (with Kiv_H for reference):</p>
<p><code>
Kiv_H(x) J_F_Sebastian_H(x) digamma_H(x)
x seconds bits seconds bits seconds bits
1 5.06e-05 exact 2.47e-06 8.8 1.16e-05 exact
10 4.45e-04 exact 3.25e-06 29.5 1.17e-05 52.6
100 7.64e-03 exact 3.65e-06 50.4 1.17e-05 exact
1000 7.62e-01 exact 5.92e-06 52.9 1.19e-05 exact
</code></p>
| 3 | 2014-12-29T04:12:19Z | [
"python",
"math"
] |
Python globals, locals, and UnboundLocalError | 404,534 | <p>I ran across this case of <code>UnboundLocalError</code> recently, which seems strange:</p>
<pre><code>import pprint
def main():
if 'pprint' in globals(): print 'pprint is in globals()'
pprint.pprint('Spam')
from pprint import pprint
pprint('Eggs')
if __name__ == '__main__': main()
</code></pre>
<p>Which produces:</p>
<pre><code>pprint is in globals()
Traceback (most recent call last):
File "weird.py", line 9, in <module>
if __name__ == '__main__': main()
File "weird.py", line 5, in main
pprint.pprint('Spam')
UnboundLocalError: local variable 'pprint' referenced before assignment
</code></pre>
<p><code>pprint</code> is clearly bound in <code>globals</code>, and is going to be bound in <code>locals</code> in the following statement. Can someone offer an explanation of why it isn't happy resolving <code>pprint</code> to the binding in <code>globals</code> here?</p>
<p><strong>Edit:</strong> Thanks to the good responses I can clarify my question with relevant terminology:</p>
<p>At compile time the identifier <code>pprint</code> is marked as local to the frame. Does the execution model have no distinction <em>where</em> within the frame the local identifier is bound? Can it say, "refer to the global binding up until this bytecode instruction, at which point it has been rebound to a local binding," or does the execution model not account for this?</p>
| 8 | 2009-01-01T04:48:54Z | 404,610 | <p>Looks like Python sees the <code>from pprint import pprint</code> line and marks <code>pprint</code> as a name local to <code>main()</code> <em>before</em> executing any code. Since Python thinks pprint ought to be a local variable, referencing it with <code>pprint.pprint()</code> before "assigning" it with the <code>from..import</code> statement, it throws that error. </p>
<p>That's as much sense as I can make of that. </p>
<p>The moral, of course, is to always put those <code>import</code> statements at the top of the scope.</p>
| 4 | 2009-01-01T06:02:48Z | [
"python",
"binding",
"scope",
"identifier"
] |
Python globals, locals, and UnboundLocalError | 404,534 | <p>I ran across this case of <code>UnboundLocalError</code> recently, which seems strange:</p>
<pre><code>import pprint
def main():
if 'pprint' in globals(): print 'pprint is in globals()'
pprint.pprint('Spam')
from pprint import pprint
pprint('Eggs')
if __name__ == '__main__': main()
</code></pre>
<p>Which produces:</p>
<pre><code>pprint is in globals()
Traceback (most recent call last):
File "weird.py", line 9, in <module>
if __name__ == '__main__': main()
File "weird.py", line 5, in main
pprint.pprint('Spam')
UnboundLocalError: local variable 'pprint' referenced before assignment
</code></pre>
<p><code>pprint</code> is clearly bound in <code>globals</code>, and is going to be bound in <code>locals</code> in the following statement. Can someone offer an explanation of why it isn't happy resolving <code>pprint</code> to the binding in <code>globals</code> here?</p>
<p><strong>Edit:</strong> Thanks to the good responses I can clarify my question with relevant terminology:</p>
<p>At compile time the identifier <code>pprint</code> is marked as local to the frame. Does the execution model have no distinction <em>where</em> within the frame the local identifier is bound? Can it say, "refer to the global binding up until this bytecode instruction, at which point it has been rebound to a local binding," or does the execution model not account for this?</p>
| 8 | 2009-01-01T04:48:54Z | 404,709 | <p>Well, that was interesting enough for me to experiment a bit and I read through <a href="http://docs.python.org/reference/executionmodel.html" rel="nofollow">http://docs.python.org/reference/executionmodel.html</a></p>
<p>Then did some tinkering with your code here and there, this is what i could find:</p>
<p>code:</p>
<pre><code>import pprint
def two():
from pprint import pprint
print globals()['pprint']
pprint('Eggs')
print globals()['pprint']
def main():
if 'pprint' in globals():
print 'pprint is in globals()'
global pprint
print globals()['pprint']
pprint.pprint('Spam')
from pprint import pprint
print globals()['pprint']
pprint('Eggs')
def three():
print globals()['pprint']
pprint.pprint('Spam')
if __name__ == '__main__':
two()
print('\n')
three()
print('\n')
main()
</code></pre>
<p>output:</p>
<pre><code><module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>
'Eggs'
<module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>
<module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>
'Spam'
pprint is in globals()
<module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>
'Spam'
<function pprint at 0xb7d596f4>
'Eggs'
</code></pre>
<p>In the method <code>two()</code> <code>from pprint import pprint</code> but does not override the name <code>pprint</code> in <code>globals</code>, since the <code>global</code> keyword is <strong>not</strong> used in the scope of <code>two()</code>.</p>
<p>In method <code>three()</code> since there is no declaration of <code>pprint</code> name in local scope it defaults to the global name <code>pprint</code> which is a module</p>
<p>Whereas in <code>main()</code>, at first the keyword <code>global</code> <strong>is used</strong> so all references to <code>pprint</code> in the scope of method <code>main()</code> will refer to the <code>global</code> name <code>pprint</code>. Which as we can see is a module at first and is overriden in the <code>global</code> <code>namespace</code> with a method as we do the <code>from pprint import pprint</code> </p>
<p>Though this may not be answering the question as such, but nevertheless its some interesting fact I think.</p>
<p>=====================</p>
<p><strong>Edit</strong> Another interesting thing.</p>
<p>If you have a module say:</p>
<p><code>mod1</code></p>
<pre><code>from datetime import datetime
def foo():
print "bar"
</code></pre>
<p>and another method say:</p>
<p><code>mod2</code></p>
<pre><code>import datetime
from mod1 import *
if __name__ == '__main__':
print datetime.datetime.now()
</code></pre>
<p>which at first sight is seemingly correct since you have imported the module <code>datetime</code> in <code>mod2</code>.</p>
<p>now if you try to run mod2 as a script it will throw an error:</p>
<pre><code>Traceback (most recent call last):
File "mod2.py", line 5, in <module>
print datetime.datetime.now()
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
</code></pre>
<p>because the second import <code>from mod2 import *</code> has overriden the name <code>datetime</code> in the namespace, hence the first <code>import datetime</code> is not valid anymore. </p>
<p>Moral: Thus the order of imports, the nature of imports (from x import *) and the awareness of imports within imported modules - <strong>matters</strong>.</p>
| 5 | 2009-01-01T08:21:10Z | [
"python",
"binding",
"scope",
"identifier"
] |
Python globals, locals, and UnboundLocalError | 404,534 | <p>I ran across this case of <code>UnboundLocalError</code> recently, which seems strange:</p>
<pre><code>import pprint
def main():
if 'pprint' in globals(): print 'pprint is in globals()'
pprint.pprint('Spam')
from pprint import pprint
pprint('Eggs')
if __name__ == '__main__': main()
</code></pre>
<p>Which produces:</p>
<pre><code>pprint is in globals()
Traceback (most recent call last):
File "weird.py", line 9, in <module>
if __name__ == '__main__': main()
File "weird.py", line 5, in main
pprint.pprint('Spam')
UnboundLocalError: local variable 'pprint' referenced before assignment
</code></pre>
<p><code>pprint</code> is clearly bound in <code>globals</code>, and is going to be bound in <code>locals</code> in the following statement. Can someone offer an explanation of why it isn't happy resolving <code>pprint</code> to the binding in <code>globals</code> here?</p>
<p><strong>Edit:</strong> Thanks to the good responses I can clarify my question with relevant terminology:</p>
<p>At compile time the identifier <code>pprint</code> is marked as local to the frame. Does the execution model have no distinction <em>where</em> within the frame the local identifier is bound? Can it say, "refer to the global binding up until this bytecode instruction, at which point it has been rebound to a local binding," or does the execution model not account for this?</p>
| 8 | 2009-01-01T04:48:54Z | 404,789 | <p>Where's the surprise? <em>Any</em> variable global to a scope that you reassign within that scope is marked local to that scope by the compiler. </p>
<p>If imports would be handled differently, <em>that</em> would be surprising imho.</p>
<p>It may make a case for not naming modules after symbols used therein, or vice versa, though.</p>
| 6 | 2009-01-01T09:42:23Z | [
"python",
"binding",
"scope",
"identifier"
] |
Python globals, locals, and UnboundLocalError | 404,534 | <p>I ran across this case of <code>UnboundLocalError</code> recently, which seems strange:</p>
<pre><code>import pprint
def main():
if 'pprint' in globals(): print 'pprint is in globals()'
pprint.pprint('Spam')
from pprint import pprint
pprint('Eggs')
if __name__ == '__main__': main()
</code></pre>
<p>Which produces:</p>
<pre><code>pprint is in globals()
Traceback (most recent call last):
File "weird.py", line 9, in <module>
if __name__ == '__main__': main()
File "weird.py", line 5, in main
pprint.pprint('Spam')
UnboundLocalError: local variable 'pprint' referenced before assignment
</code></pre>
<p><code>pprint</code> is clearly bound in <code>globals</code>, and is going to be bound in <code>locals</code> in the following statement. Can someone offer an explanation of why it isn't happy resolving <code>pprint</code> to the binding in <code>globals</code> here?</p>
<p><strong>Edit:</strong> Thanks to the good responses I can clarify my question with relevant terminology:</p>
<p>At compile time the identifier <code>pprint</code> is marked as local to the frame. Does the execution model have no distinction <em>where</em> within the frame the local identifier is bound? Can it say, "refer to the global binding up until this bytecode instruction, at which point it has been rebound to a local binding," or does the execution model not account for this?</p>
| 8 | 2009-01-01T04:48:54Z | 2,146,410 | <p>This question got answered several weeks ago, but I think I can clarify the answers a little. First some facts.</p>
<p>1: In Python,</p>
<pre><code>import foo
</code></pre>
<p>is almost exactly the same as</p>
<pre><code>foo = __import__("foo", globals(), locals(), [], -1)
</code></pre>
<p>2: When executing code in a function, if Python encounters a variable that hasn't been defined in the function yet, it looks in the global scope.</p>
<p>3: Python has an optimization it uses for functions called "locals". When Python tokenizes a function, it keeps track of all the variables you assign to. It assigns each of these variables a number from a local monotonically increasing integer. When Python runs the function, it creates an array with as many slots as there are local variables, and it assigns each slot a special value that means "has not been assigned to yet", and that's where the values for those variables are stored. If you reference a local that hasn't been assigned to yet, Python sees that special value and throws an UnboundLocalValue exception.</p>
<p>The stage is now set. Your "from pprint import pprint" is really a form of assignment. So Python creates a local variable called "pprint" which occludes the global variable. Then, when you refer to "pprint.pprint" in the function, you hit the special value and Python throws the exception. If you didn't have that import statement in the function, Python would use the normal look-in-locals-first-then-look-in-globals resolution and find the pprint module in globals.</p>
<p>To disambiguate this you can use the "global" keyword. Of course by now you've already worked past your problem, and I don't know whether you really needed "global" or if some other approach was called for.</p>
| 4 | 2010-01-27T11:25:45Z | [
"python",
"binding",
"scope",
"identifier"
] |
Determining application path in a Python EXE generated by pyInstaller | 404,744 | <p>I have an application that resides in a single .py file. I've been able to get pyInstaller to bundle it successfully into an EXE for Windows. The problem is, the application requires a .cfg file that always sits directly beside the application in the same directory.</p>
<p>Normally, I build the path using the following code:</p>
<pre><code>import os
config_name = 'myapp.cfg'
config_path = os.path.join(sys.path[0], config_name)
</code></pre>
<p>However, it seems the sys.path is blank when its called from an EXE generated by pyInstaller. This same behaviour occurs when you run the python interactive command line and try to fetch sys.path[0].</p>
<p>Is there a more concrete way of getting the path of the currently running application so that I can find files that are relative to it?</p>
| 30 | 2009-01-01T08:50:22Z | 404,750 | <p>I found a solution. You need to check if the application is running as a script or as a frozen exe:</p>
<pre><code>import os
import sys
config_name = 'myapp.cfg'
# determine if application is a script file or frozen exe
if getattr(sys, 'frozen', False):
application_path = os.path.dirname(sys.executable)
elif __file__:
application_path = os.path.dirname(__file__)
config_path = os.path.join(application_path, config_name)
</code></pre>
| 62 | 2009-01-01T08:53:20Z | [
"python",
"executable",
"relative-path",
"pyinstaller"
] |
Determining application path in a Python EXE generated by pyInstaller | 404,744 | <p>I have an application that resides in a single .py file. I've been able to get pyInstaller to bundle it successfully into an EXE for Windows. The problem is, the application requires a .cfg file that always sits directly beside the application in the same directory.</p>
<p>Normally, I build the path using the following code:</p>
<pre><code>import os
config_name = 'myapp.cfg'
config_path = os.path.join(sys.path[0], config_name)
</code></pre>
<p>However, it seems the sys.path is blank when its called from an EXE generated by pyInstaller. This same behaviour occurs when you run the python interactive command line and try to fetch sys.path[0].</p>
<p>Is there a more concrete way of getting the path of the currently running application so that I can find files that are relative to it?</p>
| 30 | 2009-01-01T08:50:22Z | 14,372,748 | <pre><code>os.path.dirname(sys.argv[0])
</code></pre>
<p>That works for me.</p>
| 3 | 2013-01-17T05:31:57Z | [
"python",
"executable",
"relative-path",
"pyinstaller"
] |
LBYL vs EAFP in Java? | 404,795 | <p>I was recently teaching myself Python and discovered the LBYL/EAFP idioms with regards to error checking before code execution. In Python, it seems the accepted style is EAFP, and it seems to work well with the language.</p>
<p>LBYL (<strong><em>L</strong>ook <strong>B</strong>efore <strong>Y</strong>ou <strong>L</strong>eap</em>):</p>
<pre><code>def safe_divide_1(x, y):
if y == 0:
print "Divide-by-0 attempt detected"
return None
else:
return x/y
</code></pre>
<p>EAFP (<em>it's <strong>E</strong>asier to <strong>A</strong>sk <strong>F</strong>orgiveness than <strong>P</strong>ermission</em>):</p>
<pre><code>def safe_divide_2(x, y):
try:
return x/y
except ZeroDivisionError:
print "Divide-by-0 attempt detected"
return None
</code></pre>
<p>My question is this: I had never even heard of using EAFP as the primary data validation construct, coming from a Java and C++ background. Is EAFP something that is wise to use in Java? Or is there too much overhead from exceptions? I know that there is only overhead when an exception is actually thrown, so I'm unsure as to why the simpler method of EAFP is not used. Is it just preference?</p>
| 39 | 2009-01-01T09:50:56Z | 404,802 | <p>Personally, and I think this is backed up by convention, EAFP is never a good way to go.
You can look at it as an equivalent to the following:</p>
<pre><code>if (o != null)
o.doSomething();
else
// handle
</code></pre>
<p>as opposed to:</p>
<pre><code>try {
o.doSomething()
}
catch (NullPointerException npe) {
// handle
}
</code></pre>
<p>Moreover, consider the following:</p>
<pre><code>if (a != null)
if (b != null)
if (c != null)
a.getB().getC().doSomething();
else
// handle c null
else
// handle b null
else
// handle a null
</code></pre>
<p>This may look a lot less elegant (and yes this is a crude example - bear with me), but it gives you much greater granularity in handling the error, as opposed to wrapping it all in a try-catch to get that <code>NullPointerException</code>, and then try to figure out where and why you got it.</p>
<p>The way I see it EAFP should never be used, except for rare situations. Also, since you raised the issue: <strong>yes, the try-catch block does incur some overhead</strong> even if the exception is not thrown.</p>
| 5 | 2009-01-01T09:57:00Z | [
"java",
"python",
"error-handling",
"idioms"
] |
LBYL vs EAFP in Java? | 404,795 | <p>I was recently teaching myself Python and discovered the LBYL/EAFP idioms with regards to error checking before code execution. In Python, it seems the accepted style is EAFP, and it seems to work well with the language.</p>
<p>LBYL (<strong><em>L</strong>ook <strong>B</strong>efore <strong>Y</strong>ou <strong>L</strong>eap</em>):</p>
<pre><code>def safe_divide_1(x, y):
if y == 0:
print "Divide-by-0 attempt detected"
return None
else:
return x/y
</code></pre>
<p>EAFP (<em>it's <strong>E</strong>asier to <strong>A</strong>sk <strong>F</strong>orgiveness than <strong>P</strong>ermission</em>):</p>
<pre><code>def safe_divide_2(x, y):
try:
return x/y
except ZeroDivisionError:
print "Divide-by-0 attempt detected"
return None
</code></pre>
<p>My question is this: I had never even heard of using EAFP as the primary data validation construct, coming from a Java and C++ background. Is EAFP something that is wise to use in Java? Or is there too much overhead from exceptions? I know that there is only overhead when an exception is actually thrown, so I'm unsure as to why the simpler method of EAFP is not used. Is it just preference?</p>
| 39 | 2009-01-01T09:50:56Z | 404,999 | <p>Exceptions are handled more efficiently in Python than in Java, which is at least <em>partly</em> why you see that construct in Python. In Java, it's more inefficient (in terms of performance) to use exceptions in that way.</p>
| 10 | 2009-01-01T14:30:19Z | [
"java",
"python",
"error-handling",
"idioms"
] |
LBYL vs EAFP in Java? | 404,795 | <p>I was recently teaching myself Python and discovered the LBYL/EAFP idioms with regards to error checking before code execution. In Python, it seems the accepted style is EAFP, and it seems to work well with the language.</p>
<p>LBYL (<strong><em>L</strong>ook <strong>B</strong>efore <strong>Y</strong>ou <strong>L</strong>eap</em>):</p>
<pre><code>def safe_divide_1(x, y):
if y == 0:
print "Divide-by-0 attempt detected"
return None
else:
return x/y
</code></pre>
<p>EAFP (<em>it's <strong>E</strong>asier to <strong>A</strong>sk <strong>F</strong>orgiveness than <strong>P</strong>ermission</em>):</p>
<pre><code>def safe_divide_2(x, y):
try:
return x/y
except ZeroDivisionError:
print "Divide-by-0 attempt detected"
return None
</code></pre>
<p>My question is this: I had never even heard of using EAFP as the primary data validation construct, coming from a Java and C++ background. Is EAFP something that is wise to use in Java? Or is there too much overhead from exceptions? I know that there is only overhead when an exception is actually thrown, so I'm unsure as to why the simpler method of EAFP is not used. Is it just preference?</p>
| 39 | 2009-01-01T09:50:56Z | 405,220 | <p>If you are accessing files, EAFP is more reliable than LBYL, because the operations involved in LBYL are not atomic, and the file system might change between the time you look and the time you leap. Actually, the standard name is TOCTOU - Time of Check, Time of Use; bugs caused by inaccurate checking are TOCTOU bugs.</p>
<p>Consider creating a temporary file that must have a unique name. The best way to find out whether the chosen file name exists yet is to try creating it - making sure you use options to ensure that your operation fails if the file does already exist (in POSIX/Unix terms, the O_EXCL flag to <code>open()</code>). If you try to test whether the file already exists (probably using <code>access()</code>), then between the time when that says "No" and the time you try to create the file, someone or something else may have created the file.</p>
<p>Conversely, suppose that you try to read an existing file. Your check that the file exists (LBYL) may say "it is there", but when you actually open it, you find "it is not there".</p>
<p>In both these cases, you have to check the final operation - and the LBYL didn't automatically help.</p>
<p>(If you are messing with SUID or SGID programs, <code>access()</code> asks a different question; it may be relevant to LBYL, but the code still has to take into account the possibility of failure.)</p>
| 89 | 2009-01-01T17:52:24Z | [
"java",
"python",
"error-handling",
"idioms"
] |
LBYL vs EAFP in Java? | 404,795 | <p>I was recently teaching myself Python and discovered the LBYL/EAFP idioms with regards to error checking before code execution. In Python, it seems the accepted style is EAFP, and it seems to work well with the language.</p>
<p>LBYL (<strong><em>L</strong>ook <strong>B</strong>efore <strong>Y</strong>ou <strong>L</strong>eap</em>):</p>
<pre><code>def safe_divide_1(x, y):
if y == 0:
print "Divide-by-0 attempt detected"
return None
else:
return x/y
</code></pre>
<p>EAFP (<em>it's <strong>E</strong>asier to <strong>A</strong>sk <strong>F</strong>orgiveness than <strong>P</strong>ermission</em>):</p>
<pre><code>def safe_divide_2(x, y):
try:
return x/y
except ZeroDivisionError:
print "Divide-by-0 attempt detected"
return None
</code></pre>
<p>My question is this: I had never even heard of using EAFP as the primary data validation construct, coming from a Java and C++ background. Is EAFP something that is wise to use in Java? Or is there too much overhead from exceptions? I know that there is only overhead when an exception is actually thrown, so I'm unsure as to why the simpler method of EAFP is not used. Is it just preference?</p>
| 39 | 2009-01-01T09:50:56Z | 408,305 | <p>In addition to the relative cost of exceptions in Python and Java, keep in mind that there's a difference in philosophy / attitude between them. Java tries to be very strict about types (and everything else), requiring explicit, detailed declarations of class/method signatures. It assumes that you should know, at any point, exactly what type of object you're using and what it is capable of doing. In contrast, Python's "duck typing" means that you don't know for sure (and shouldn't care) what the manifest type of an object is, you only need to care that it quacks when you ask it to. In this kind of permissive environment, the only sane attitude is to presume that things will work, but be ready to deal with the consequences if they don't. Java's natural restrictiveness doesn't fit well with such a casual approach. (This is not intended to disparage either approach or language, but rather to say that these attitudes are part of each language's idiom, and copying idioms between different languages can often lead to awkwardness and poor communication...)</p>
| 37 | 2009-01-02T23:31:52Z | [
"java",
"python",
"error-handling",
"idioms"
] |
I need help--lists and Python | 404,825 | <p>How to return a list in Python???</p>
<p>When I tried returning a list,I got an empty list.What's the reason???</p>
| -3 | 2009-01-01T10:28:31Z | 404,837 | <p>to wit:</p>
<pre><code>In [1]: def pants():
...: return [1, 2, 'steve']
...:
In [2]: pants()
Out[2]: [1, 2, 'steve']
</code></pre>
| 0 | 2009-01-01T10:42:02Z | [
"python",
"list",
"return"
] |
I need help--lists and Python | 404,825 | <p>How to return a list in Python???</p>
<p>When I tried returning a list,I got an empty list.What's the reason???</p>
| -3 | 2009-01-01T10:28:31Z | 404,874 | <p>As Andrew commented, you will receive better answers if you show us the code you are currently using. Also if you could state what version of Python you are using that would be great.</p>
<p>There are a few ways you can return a list. Say for example we have a function called retlist.</p>
<pre><code>def retlist():
return []
</code></pre>
<p>will return the empty list</p>
<pre><code>def retlist():
a = list()
a.append(5)
return a
</code></pre>
<p>will return [5].</p>
<p>You can also use list comprehension to return a list</p>
<pre><code>def retlist():
return [x*x for x in range(10)]
</code></pre>
<p>There are plenty of ways to return a list. But basically it involves return .</p>
<p>If you are after a more detailed response, comment for what you need.</p>
<p>Good Luck</p>
| 2 | 2009-01-01T11:26:36Z | [
"python",
"list",
"return"
] |
Line reading chokes on 0x1A | 405,058 | <p>I have the following file:</p>
<pre><code>abcde
kwakwa
<0x1A>
line3
linllll
</code></pre>
<p>Where <code><0x1A></code> represents a byte with the hex value of 0x1A. When attempting to read this file in Python as:</p>
<pre><code>for line in open('t.txt'):
print line,
</code></pre>
<p>It only reads the first two lines, and exits the loop.</p>
<p>The solution seems to be to open the file in binary (or universal newline mode) - 'rb' or 'rU'. Can you explain this behavior ?</p>
| 12 | 2009-01-01T15:29:35Z | 405,061 | <p>0x1A is Ctrl-Z, and DOS historically used that as an end-of-file marker. For example, try using a command prompt, and "type"ing your file. It will only display the content up the Ctrl-Z. </p>
<p>Python uses the Windows CRT function _wfopen, which implements the "Ctrl-Z is EOF" semantics.</p>
| 26 | 2009-01-01T15:31:38Z | [
"python",
"windows",
"binary-data"
] |
Line reading chokes on 0x1A | 405,058 | <p>I have the following file:</p>
<pre><code>abcde
kwakwa
<0x1A>
line3
linllll
</code></pre>
<p>Where <code><0x1A></code> represents a byte with the hex value of 0x1A. When attempting to read this file in Python as:</p>
<pre><code>for line in open('t.txt'):
print line,
</code></pre>
<p>It only reads the first two lines, and exits the loop.</p>
<p>The solution seems to be to open the file in binary (or universal newline mode) - 'rb' or 'rU'. Can you explain this behavior ?</p>
| 12 | 2009-01-01T15:29:35Z | 405,169 | <p><a href="http://stackoverflow.com/questions/405058/line-reading-chokes-on-0x1a#405061">Ned</a> is of course correct.</p>
<p>If your curiosity runs a little deeper, the root cause is backwards compatibility taken to an extreme. Windows is compatible with DOS, which used Ctrl-Z as an optional end of file marker for text files. What you might not know is that DOS was compatible with CP/M, which was popular on small computers before the PC. CP/M's file system didn't keep track of file sizes down to the byte level, it only kept track by the number of floppy disk sectors. If your file wasn't an exact multiple of 128 bytes, you needed a way to mark the end of the text. <a href="http://en.wikipedia.org/wiki/Ascii">This Wikipedia article</a> implies that the selection of Ctrl-Z was based on an even older convention used by DEC.</p>
| 8 | 2009-01-01T17:13:22Z | [
"python",
"windows",
"binary-data"
] |
I can't but help get the idea I'm doing it all wrong (Python, again) | 405,106 | <p>All of the questions that I've asked recently about Python have been for this project. I have realised that the reason I'm asking so many questions may not be because I'm so new to Python (but I know a good bit of PHP) and is probably not because Python has some inherent flaw.</p>
<p>Thus I will now say what the project is and what my current idea is and you can either tell me I'm doing it all wrong, that there's a few things I need to learn or that Python is simply not suited to dealing with this type of project and language XYZ would be better in this instance or even that there's some open source project I might want to get involved in.</p>
<p><strong>The project</strong><br>
I run a free turn based strategy game (think the campaign mode from the total war series but with even more complexity and depth) and am creating a combat simulator for it (again, think total war as an idea of how it'd work). I'm in no way deluded enough to think that I'll ever make anything as good as the Total war games alone but I do think that I can automate a process that I currently do by hand.</p>
<p><strong>What will it do</strong><br>
It will have to take into account a large range of variables for the units, equipment, training, weather, terrain and so on and so forth. I'm aware it's a big task and I plan to do it a piece at a time in my free time. I've zero budget but it's a hobby that I'm prepared to put time into (and have already).</p>
<p><strong>My current stumbling block</strong><br>
In PHP everything can access everything else, "wrong" though some might consider this it's really really handy for this. If I have an array of equipment for use by the units, I can get hold of that array from anywhere. With Python I have to remake that array each time I import the relevant data file and this seems quite a silly solution for a language that from my experience is well thought out. I've put in a system of logging function calls and class creation (because I know from a very basic version of this that I did in PHP once that it'll help a lot down the line) and the way that I've kept the data in one place is to pass each of my classes an instance to my logging list, smells like a hack to me but it's the only way I've gotten it to work.</p>
<p>Thus I conclude I'm missing something and would very much appreciate the insight of anybody willing to give it. Thank you.</p>
<p><strong>Code samples</strong></p>
<p>This creates a list of formations, so far there's only one value (besides the name) but I anticipate adding more on which is why they're a list of classes rather than just a standard list. This is found within data.py</p>
<pre><code>formations = []
formationsHash = []
def createFormations(logger):
"""This creates all the formations that will be used"""
# Standard close quarter formation, maximum number of people per square metre
formationsHash.append('Tight')
formations.append(Formation(logger, 'Tight', tightness = 1))
# Standard ranged combat formation, good people per square metre but not too cramped
formationsHash.append('Loose')
formations.append(Formation(logger, 'Loose', tightness = 0.5))
# Standard skirmishing formation, very good for moving around terrain and avoiding missile fire
formationsHash.append('Skirmish')
formations.append(Formation(logger, 'Skirmish', tightness = 0.1))
# Very unflexible but good for charges
formationsHash.append('Arrowhead')
formations.append(Formation(logger, 'Arrowhead', tightness = 1))
def getFormation(searchFor):
"""Returns the fomation object with this name"""
indexValue = formationsHash.index(searchFor)
return formations[indexValue]
</code></pre>
<p>I don't have a code sample of when I'd need to access it because I've not gotten as far as making it but I anticipate the code looking something like the following:</p>
<pre><code>Python
tempFormation = data.getFormation(unit.formationType)
tempTerrain = data.getTerrain(unit.currentTerrain)
unit.attackDamage = unit.attackDamage * tempTerrain.tighnessBonus(tempFormation.tightness)
</code></pre>
<p>The unit contains an integer that links to the index/key of the relevant terrain, formation and whatnot in the master list. Temporary variables are used to make the 3rd line shorter but in the long run will possibly cause issues if I forget to get one and it's use a value from earlier which is then incorrect (that's where the logging comes in handy). </p>
<pre><code>PHP
$unit->attackDamage *= $terrain[$unit->currentTerrain]->tighnessBonus($unit->currentTerrain)
</code></pre>
<p>The unit class contains the index (probably a string) of the relevant terrain it's on and the formation it's in.</p>
<p>Maybe this will show some massive flaw in my understanding of Python (6 months vs the 3 years of PHP).</p>
| 2 | 2009-01-01T16:27:44Z | 405,129 | <p>I have narrowed your issue down to:</p>
<blockquote>
<p>With Python I have to remake that
array each time I import the relevant
data file</p>
</blockquote>
<p>Well you have two choices really, the first and easiest is to keep the structure in memory. That way (just like PHP) you can in theory access it from "anywhere", you are slightly limited by namespacing, but that is for your own good. It would translate as "anywhere you would like to".</p>
<p>The second choice is to have some data abstraction (like a database, or data file as you have) which stores and you retrieve data from this. This may be better than the first choice, as you might have far too much data to fit in memory at once. Again the way of getting this data will be available "anywhere" just like PHP.</p>
<p>You can either pass these things directly to instances in an explicit way, or you can use module-level globals and import them into places where you need them, as you go on to say:</p>
<blockquote>
<p>and the way that I've kept the data in
one place is to pass each of my
classes an instance to my logging list</p>
</blockquote>
<p>I can assure you that this is not a hack. It's quite reasonable, depending on the use, eg a config object can be used in the same way, as you may want to test your application with simultaneous different configs. Logging might be better suited as a module-level global that is just imported and called, as you probably only ever want one way of logging, but again, it depends on your requirements.</p>
<p>I guess to sum up, you really are on the right track. Try not to give in to that "hackish" smell especially when using languages you are not altogether familiar with. A hack in one language might be the gold-standard in another. And of course, best of luck with your project - it sounds fun.</p>
| 3 | 2009-01-01T16:43:47Z | [
"php",
"python",
"project",
"project-planning"
] |
I can't but help get the idea I'm doing it all wrong (Python, again) | 405,106 | <p>All of the questions that I've asked recently about Python have been for this project. I have realised that the reason I'm asking so many questions may not be because I'm so new to Python (but I know a good bit of PHP) and is probably not because Python has some inherent flaw.</p>
<p>Thus I will now say what the project is and what my current idea is and you can either tell me I'm doing it all wrong, that there's a few things I need to learn or that Python is simply not suited to dealing with this type of project and language XYZ would be better in this instance or even that there's some open source project I might want to get involved in.</p>
<p><strong>The project</strong><br>
I run a free turn based strategy game (think the campaign mode from the total war series but with even more complexity and depth) and am creating a combat simulator for it (again, think total war as an idea of how it'd work). I'm in no way deluded enough to think that I'll ever make anything as good as the Total war games alone but I do think that I can automate a process that I currently do by hand.</p>
<p><strong>What will it do</strong><br>
It will have to take into account a large range of variables for the units, equipment, training, weather, terrain and so on and so forth. I'm aware it's a big task and I plan to do it a piece at a time in my free time. I've zero budget but it's a hobby that I'm prepared to put time into (and have already).</p>
<p><strong>My current stumbling block</strong><br>
In PHP everything can access everything else, "wrong" though some might consider this it's really really handy for this. If I have an array of equipment for use by the units, I can get hold of that array from anywhere. With Python I have to remake that array each time I import the relevant data file and this seems quite a silly solution for a language that from my experience is well thought out. I've put in a system of logging function calls and class creation (because I know from a very basic version of this that I did in PHP once that it'll help a lot down the line) and the way that I've kept the data in one place is to pass each of my classes an instance to my logging list, smells like a hack to me but it's the only way I've gotten it to work.</p>
<p>Thus I conclude I'm missing something and would very much appreciate the insight of anybody willing to give it. Thank you.</p>
<p><strong>Code samples</strong></p>
<p>This creates a list of formations, so far there's only one value (besides the name) but I anticipate adding more on which is why they're a list of classes rather than just a standard list. This is found within data.py</p>
<pre><code>formations = []
formationsHash = []
def createFormations(logger):
"""This creates all the formations that will be used"""
# Standard close quarter formation, maximum number of people per square metre
formationsHash.append('Tight')
formations.append(Formation(logger, 'Tight', tightness = 1))
# Standard ranged combat formation, good people per square metre but not too cramped
formationsHash.append('Loose')
formations.append(Formation(logger, 'Loose', tightness = 0.5))
# Standard skirmishing formation, very good for moving around terrain and avoiding missile fire
formationsHash.append('Skirmish')
formations.append(Formation(logger, 'Skirmish', tightness = 0.1))
# Very unflexible but good for charges
formationsHash.append('Arrowhead')
formations.append(Formation(logger, 'Arrowhead', tightness = 1))
def getFormation(searchFor):
"""Returns the fomation object with this name"""
indexValue = formationsHash.index(searchFor)
return formations[indexValue]
</code></pre>
<p>I don't have a code sample of when I'd need to access it because I've not gotten as far as making it but I anticipate the code looking something like the following:</p>
<pre><code>Python
tempFormation = data.getFormation(unit.formationType)
tempTerrain = data.getTerrain(unit.currentTerrain)
unit.attackDamage = unit.attackDamage * tempTerrain.tighnessBonus(tempFormation.tightness)
</code></pre>
<p>The unit contains an integer that links to the index/key of the relevant terrain, formation and whatnot in the master list. Temporary variables are used to make the 3rd line shorter but in the long run will possibly cause issues if I forget to get one and it's use a value from earlier which is then incorrect (that's where the logging comes in handy). </p>
<pre><code>PHP
$unit->attackDamage *= $terrain[$unit->currentTerrain]->tighnessBonus($unit->currentTerrain)
</code></pre>
<p>The unit class contains the index (probably a string) of the relevant terrain it's on and the formation it's in.</p>
<p>Maybe this will show some massive flaw in my understanding of Python (6 months vs the 3 years of PHP).</p>
| 2 | 2009-01-01T16:27:44Z | 405,158 | <blockquote>
<p>With Python I have to remake that
array each time I import the relevant
data file</p>
</blockquote>
<p>You're missing a subtle point of Python semantics here. When you import a module for a second time, you aren't re-executing the code in that module. The name is found in a list of all modules imported, and the same module is returned to you. So the second time you import your module, you'll get a reference to the same list (in Python, don't say array, say list).</p>
<p>You'll probably need to post specific code samples to get more help, it seems like there are a few Python misconceptions mixed into this, and once those are cleared up you'll have a simpler time.</p>
| 5 | 2009-01-01T17:03:41Z | [
"php",
"python",
"project",
"project-planning"
] |
I can't but help get the idea I'm doing it all wrong (Python, again) | 405,106 | <p>All of the questions that I've asked recently about Python have been for this project. I have realised that the reason I'm asking so many questions may not be because I'm so new to Python (but I know a good bit of PHP) and is probably not because Python has some inherent flaw.</p>
<p>Thus I will now say what the project is and what my current idea is and you can either tell me I'm doing it all wrong, that there's a few things I need to learn or that Python is simply not suited to dealing with this type of project and language XYZ would be better in this instance or even that there's some open source project I might want to get involved in.</p>
<p><strong>The project</strong><br>
I run a free turn based strategy game (think the campaign mode from the total war series but with even more complexity and depth) and am creating a combat simulator for it (again, think total war as an idea of how it'd work). I'm in no way deluded enough to think that I'll ever make anything as good as the Total war games alone but I do think that I can automate a process that I currently do by hand.</p>
<p><strong>What will it do</strong><br>
It will have to take into account a large range of variables for the units, equipment, training, weather, terrain and so on and so forth. I'm aware it's a big task and I plan to do it a piece at a time in my free time. I've zero budget but it's a hobby that I'm prepared to put time into (and have already).</p>
<p><strong>My current stumbling block</strong><br>
In PHP everything can access everything else, "wrong" though some might consider this it's really really handy for this. If I have an array of equipment for use by the units, I can get hold of that array from anywhere. With Python I have to remake that array each time I import the relevant data file and this seems quite a silly solution for a language that from my experience is well thought out. I've put in a system of logging function calls and class creation (because I know from a very basic version of this that I did in PHP once that it'll help a lot down the line) and the way that I've kept the data in one place is to pass each of my classes an instance to my logging list, smells like a hack to me but it's the only way I've gotten it to work.</p>
<p>Thus I conclude I'm missing something and would very much appreciate the insight of anybody willing to give it. Thank you.</p>
<p><strong>Code samples</strong></p>
<p>This creates a list of formations, so far there's only one value (besides the name) but I anticipate adding more on which is why they're a list of classes rather than just a standard list. This is found within data.py</p>
<pre><code>formations = []
formationsHash = []
def createFormations(logger):
"""This creates all the formations that will be used"""
# Standard close quarter formation, maximum number of people per square metre
formationsHash.append('Tight')
formations.append(Formation(logger, 'Tight', tightness = 1))
# Standard ranged combat formation, good people per square metre but not too cramped
formationsHash.append('Loose')
formations.append(Formation(logger, 'Loose', tightness = 0.5))
# Standard skirmishing formation, very good for moving around terrain and avoiding missile fire
formationsHash.append('Skirmish')
formations.append(Formation(logger, 'Skirmish', tightness = 0.1))
# Very unflexible but good for charges
formationsHash.append('Arrowhead')
formations.append(Formation(logger, 'Arrowhead', tightness = 1))
def getFormation(searchFor):
"""Returns the fomation object with this name"""
indexValue = formationsHash.index(searchFor)
return formations[indexValue]
</code></pre>
<p>I don't have a code sample of when I'd need to access it because I've not gotten as far as making it but I anticipate the code looking something like the following:</p>
<pre><code>Python
tempFormation = data.getFormation(unit.formationType)
tempTerrain = data.getTerrain(unit.currentTerrain)
unit.attackDamage = unit.attackDamage * tempTerrain.tighnessBonus(tempFormation.tightness)
</code></pre>
<p>The unit contains an integer that links to the index/key of the relevant terrain, formation and whatnot in the master list. Temporary variables are used to make the 3rd line shorter but in the long run will possibly cause issues if I forget to get one and it's use a value from earlier which is then incorrect (that's where the logging comes in handy). </p>
<pre><code>PHP
$unit->attackDamage *= $terrain[$unit->currentTerrain]->tighnessBonus($unit->currentTerrain)
</code></pre>
<p>The unit class contains the index (probably a string) of the relevant terrain it's on and the formation it's in.</p>
<p>Maybe this will show some massive flaw in my understanding of Python (6 months vs the 3 years of PHP).</p>
| 2 | 2009-01-01T16:27:44Z | 405,328 | <p>Please don't reinvent the wheel. Your <code>formationsHash</code> as a list of key values isn't helpful and it duplicates the features of a dictionary.</p>
<pre><code>def createFormations(logger):
"""This creates all the formations that will be used"""
formations = {}
formations['Tight']= Formation(logger, 'Tight', tightness = 1)
formations['Loose']= Formation(logger, 'Loose', tightness = 0.5)
formations['Skirmish']= Formation(logger, 'Skirmish', tightness = 0.1)
formations['Arrowhead']= Formation(logger, 'Arrowhead', tightness = 1)
return formations
</code></pre>
<p>Note, you don't actually need <code>getFormation</code>, since it does you no good. You can simply use something like this.</p>
<pre><code>formations = createFormations( whatever )
f= formations[name]
</code></pre>
| 3 | 2009-01-01T19:12:45Z | [
"php",
"python",
"project",
"project-planning"
] |
I can't but help get the idea I'm doing it all wrong (Python, again) | 405,106 | <p>All of the questions that I've asked recently about Python have been for this project. I have realised that the reason I'm asking so many questions may not be because I'm so new to Python (but I know a good bit of PHP) and is probably not because Python has some inherent flaw.</p>
<p>Thus I will now say what the project is and what my current idea is and you can either tell me I'm doing it all wrong, that there's a few things I need to learn or that Python is simply not suited to dealing with this type of project and language XYZ would be better in this instance or even that there's some open source project I might want to get involved in.</p>
<p><strong>The project</strong><br>
I run a free turn based strategy game (think the campaign mode from the total war series but with even more complexity and depth) and am creating a combat simulator for it (again, think total war as an idea of how it'd work). I'm in no way deluded enough to think that I'll ever make anything as good as the Total war games alone but I do think that I can automate a process that I currently do by hand.</p>
<p><strong>What will it do</strong><br>
It will have to take into account a large range of variables for the units, equipment, training, weather, terrain and so on and so forth. I'm aware it's a big task and I plan to do it a piece at a time in my free time. I've zero budget but it's a hobby that I'm prepared to put time into (and have already).</p>
<p><strong>My current stumbling block</strong><br>
In PHP everything can access everything else, "wrong" though some might consider this it's really really handy for this. If I have an array of equipment for use by the units, I can get hold of that array from anywhere. With Python I have to remake that array each time I import the relevant data file and this seems quite a silly solution for a language that from my experience is well thought out. I've put in a system of logging function calls and class creation (because I know from a very basic version of this that I did in PHP once that it'll help a lot down the line) and the way that I've kept the data in one place is to pass each of my classes an instance to my logging list, smells like a hack to me but it's the only way I've gotten it to work.</p>
<p>Thus I conclude I'm missing something and would very much appreciate the insight of anybody willing to give it. Thank you.</p>
<p><strong>Code samples</strong></p>
<p>This creates a list of formations, so far there's only one value (besides the name) but I anticipate adding more on which is why they're a list of classes rather than just a standard list. This is found within data.py</p>
<pre><code>formations = []
formationsHash = []
def createFormations(logger):
"""This creates all the formations that will be used"""
# Standard close quarter formation, maximum number of people per square metre
formationsHash.append('Tight')
formations.append(Formation(logger, 'Tight', tightness = 1))
# Standard ranged combat formation, good people per square metre but not too cramped
formationsHash.append('Loose')
formations.append(Formation(logger, 'Loose', tightness = 0.5))
# Standard skirmishing formation, very good for moving around terrain and avoiding missile fire
formationsHash.append('Skirmish')
formations.append(Formation(logger, 'Skirmish', tightness = 0.1))
# Very unflexible but good for charges
formationsHash.append('Arrowhead')
formations.append(Formation(logger, 'Arrowhead', tightness = 1))
def getFormation(searchFor):
"""Returns the fomation object with this name"""
indexValue = formationsHash.index(searchFor)
return formations[indexValue]
</code></pre>
<p>I don't have a code sample of when I'd need to access it because I've not gotten as far as making it but I anticipate the code looking something like the following:</p>
<pre><code>Python
tempFormation = data.getFormation(unit.formationType)
tempTerrain = data.getTerrain(unit.currentTerrain)
unit.attackDamage = unit.attackDamage * tempTerrain.tighnessBonus(tempFormation.tightness)
</code></pre>
<p>The unit contains an integer that links to the index/key of the relevant terrain, formation and whatnot in the master list. Temporary variables are used to make the 3rd line shorter but in the long run will possibly cause issues if I forget to get one and it's use a value from earlier which is then incorrect (that's where the logging comes in handy). </p>
<pre><code>PHP
$unit->attackDamage *= $terrain[$unit->currentTerrain]->tighnessBonus($unit->currentTerrain)
</code></pre>
<p>The unit class contains the index (probably a string) of the relevant terrain it's on and the formation it's in.</p>
<p>Maybe this will show some massive flaw in my understanding of Python (6 months vs the 3 years of PHP).</p>
| 2 | 2009-01-01T16:27:44Z | 405,356 | <p>"data.py creates an array (well, list), to use this list from another file I need to import data.py and remake said list."</p>
<p>I can't figure out what you're talking about. Seriously.</p>
<p>Here's a main program, which imports the data, and another module.</p>
<p>SomeMainProgram.py</p>
<pre><code>import data
import someOtherModule
print data.formations['Arrowhead']
someOtherModule.function()
</code></pre>
<p>someOtherModule.py</p>
<pre><code>import data
def function():
print data.formations['Tight']
</code></pre>
<p>data.py</p>
<pre><code>import theLoggerThing
class Formation( object ):
pass # details omitted.
def createFormations( logger ):
pass # details omitted
formations= createFormations( theLoggerThing.logger )
</code></pre>
<p>So the main program works like this.</p>
<ol>
<li><p><code>import data</code>. The <code>data</code> module is imported.</p>
<p>a. <code>import theLoggerThing</code>. Whatever this is.</p>
<p>b. <code>class Formation( object ):</code>. Create a class <code>Formations</code>.</p>
<p>c. <code>def createFormations( logger ):</code>. Create a function <code>createFormations</code>.</p>
<p>d. <code>formations =</code>. Create an object, <code>formations</code>.</p></li>
<li><p><code>import someOtherModule</code>. The <code>someOtherModule</code> is imported.</p>
<p>a. <code>import data</code>. Nothing happens. <code>data</code> is already available globally. This is a reference to what is -- effectively -- a <strong>Singleton</strong>. All Python modules are <strong>Singletons</strong>.</p>
<p>b. <code>def function</code>. Create a function <code>function</code>.</p></li>
<li><p><code>print data.formations['Arrowhead']</code>. Evaluate <code>data.formations</code>, which is a dictionary object. Do a <code>get('Arrowhead')</code> on the dictionary which does some magical lookup and returns the object found there (an instance of <code>Formation</code>).</p></li>
<li><p><code>someOtherModule.function()</code>.</p>
<p>What happens during this function evaluation.</p>
<p>a. <code>print data.formations['Tight']</code>. Evaluate <code>data.formations</code>, which is a dictionary object. Do a <code>get('Tight')</code> on the dictionary which does some magical lookup and returns the object found there (an instance of <code>Formation</code>).</p></li>
</ol>
| 1 | 2009-01-01T19:35:40Z | [
"php",
"python",
"project",
"project-planning"
] |
Please advise on Ruby vs Python, for someone who likes LISP a lot | 405,165 | <p>I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature.</p>
<p>Which one is closer to LISP: Python or Ruby? </p>
<p>I can't seem to be able to choose from Python and Ruby: they seem very similar but apparently Ruby is more functional and object-oriented, which are good things, while Python is more like Perl: a simple scripting language. Do I have the right impression?</p>
<p>PS - This might seem like a flame bait but it's not really, I'm just trying not to go crazy from OCD about switching from RoR to Python/Django and back.</p>
| 20 | 2009-01-01T17:12:12Z | 405,188 | <p>I'd go with Ruby. It's got all kinds of metaprogramming and duck punching hacks that make it really easy to extend. Features like blocks may not seem like much at first, but they make for some really clean syntax if you use them right. Open classes can be debugging hell if you screw them up, but if you're a responsible programmer, you can do things like <code>2.days.from_now</code> (example from Rails) really easily (Python can do this too, I think, but with a bit more pain)</p>
<p>PS: Check out <a href="http://www.randomhacks.net/articles/2005/12/03/why-ruby-is-an-acceptable-lisp">"Why Ruby is an acceptable LISP"</a>.</p>
| 24 | 2009-01-01T17:24:30Z | [
"python",
"ruby",
"lisp"
] |
Please advise on Ruby vs Python, for someone who likes LISP a lot | 405,165 | <p>I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature.</p>
<p>Which one is closer to LISP: Python or Ruby? </p>
<p>I can't seem to be able to choose from Python and Ruby: they seem very similar but apparently Ruby is more functional and object-oriented, which are good things, while Python is more like Perl: a simple scripting language. Do I have the right impression?</p>
<p>PS - This might seem like a flame bait but it's not really, I'm just trying not to go crazy from OCD about switching from RoR to Python/Django and back.</p>
| 20 | 2009-01-01T17:12:12Z | 405,206 | <p><a href="http://norvig.com">Peter Norvig</a>, <a href="http://norvig.com/paip.html">a famous and great lisper</a>, converted to Python. He wrote the article <a href="http://norvig.com/python-lisp.html">Python for Lisp Programmers</a>, which you might find interesting with its detailed comparison of features.</p>
<p>Python looks like executable pseudo-code. It's easy to pick up, and often using your intuition will just work. Python allows you to easily put your ideas into code.</p>
<p>Now, for web development, Python might seem like a more scattered option than Ruby, with the plethora of Python web frameworks available. Still, in general, Python is a very nice and useful language to know. As Ruby and Python's niches overlap, I agree with Kiv that it is partly a matter of personal taste which one you pick.</p>
| 31 | 2009-01-01T17:40:13Z | [
"python",
"ruby",
"lisp"
] |
Please advise on Ruby vs Python, for someone who likes LISP a lot | 405,165 | <p>I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature.</p>
<p>Which one is closer to LISP: Python or Ruby? </p>
<p>I can't seem to be able to choose from Python and Ruby: they seem very similar but apparently Ruby is more functional and object-oriented, which are good things, while Python is more like Perl: a simple scripting language. Do I have the right impression?</p>
<p>PS - This might seem like a flame bait but it's not really, I'm just trying not to go crazy from OCD about switching from RoR to Python/Django and back.</p>
| 20 | 2009-01-01T17:12:12Z | 405,211 | <p>I also recommend the article by <a href="http://norvig.com/python-lisp.html" rel="nofollow">Peter Norvig</a> that namin posted. If you want to look at functional programming in Python check out the <a href="http://docs.python.org/dev/3.0/library/functools.html" rel="nofollow">functools</a> module in the standard library. </p>
<p>There is also a lot of room to hack around in Python; private variables are by convention and not enforced, so you can poke around in the internal state of objects if you feel like it. Usually this is not necessary, though. </p>
<p>Both Ruby and Python are very object-oriented and support functional programming; I wouldn't say either one is clearly superior for your project; it's partly a matter of personal taste. </p>
| 3 | 2009-01-01T17:42:31Z | [
"python",
"ruby",
"lisp"
] |
Please advise on Ruby vs Python, for someone who likes LISP a lot | 405,165 | <p>I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature.</p>
<p>Which one is closer to LISP: Python or Ruby? </p>
<p>I can't seem to be able to choose from Python and Ruby: they seem very similar but apparently Ruby is more functional and object-oriented, which are good things, while Python is more like Perl: a simple scripting language. Do I have the right impression?</p>
<p>PS - This might seem like a flame bait but it's not really, I'm just trying not to go crazy from OCD about switching from RoR to Python/Django and back.</p>
| 20 | 2009-01-01T17:12:12Z | 405,228 | <p>Speaking as a "Rubyist", I'd agree with Kiv. The two languages both grant a nice amount of leeway when it comes to programming paradigms, but are also have benefits/shortcomings. I think that the compromises you make either way are a lot about your own programming style and taste.</p>
<p>Personally, I think Ruby can read more like pseudo-code than Python. First, Python has active whitespace, which while elegant in the eyes of many, doesn't tend to enter the equation when writing pseudo-code. Also, Ruby's syntax is quite flexible. That flexibility causes a lot of quirks that can confuse, but also allows code that's quite expressive and pretty to look at.</p>
<p>Finally, I'd really say that Ruby feels more Perl-ish to me. That's partly because I'm far more comfortable with it, so I can hack out scripts rather quickly. A lot of Ruby's syntax was borrowed from Perl though, and I haven't seen much Python code that feels similar (though again, I have little experience with Python).</p>
<p>Depending on the approach to web programming you'd like to take, I think that the types of web frameworks available in each language could perhaps be a factor in deciding as well. I'd say try them both. You can get a working knowledge of each of them in an afternoon, and while you won't be writing awesome Ruby or Python, you can probably establish a feel for each, and decide which you like more.</p>
<p><strong>Update:</strong> I think your question should actually be two separate discussions: one with Ruby, one with Python. The comparisons are less important because you start debating the merits of the differences, as opposed to which language will work better for you. If you have questions about Ruby, I'd be more than happy to answer as best I can.</p>
| 12 | 2009-01-01T18:00:04Z | [
"python",
"ruby",
"lisp"
] |
Please advise on Ruby vs Python, for someone who likes LISP a lot | 405,165 | <p>I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature.</p>
<p>Which one is closer to LISP: Python or Ruby? </p>
<p>I can't seem to be able to choose from Python and Ruby: they seem very similar but apparently Ruby is more functional and object-oriented, which are good things, while Python is more like Perl: a simple scripting language. Do I have the right impression?</p>
<p>PS - This might seem like a flame bait but it's not really, I'm just trying not to go crazy from OCD about switching from RoR to Python/Django and back.</p>
| 20 | 2009-01-01T17:12:12Z | 405,310 | <p>Both Ruby and Python are fairly distant from the Lisp traditions of immutable data, programs as data, and macros. But Ruby is very nearly a clone of Smalltalk (and I hope will grow more like Smalltalk as the Perlish cruft is deprecated), and Smalltalk, like Lisp, is a language that takes one idea to extremes. Based on your desire to do <strong>cool hacks on the language level</strong> I'd go with Ruby, as it inherits a lot of the metaprogramming mindset from Smalltalk, and that mindset <em>is</em> connected to the Lisp tradition.</p>
| 8 | 2009-01-01T19:01:50Z | [
"python",
"ruby",
"lisp"
] |
Please advise on Ruby vs Python, for someone who likes LISP a lot | 405,165 | <p>I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature.</p>
<p>Which one is closer to LISP: Python or Ruby? </p>
<p>I can't seem to be able to choose from Python and Ruby: they seem very similar but apparently Ruby is more functional and object-oriented, which are good things, while Python is more like Perl: a simple scripting language. Do I have the right impression?</p>
<p>PS - This might seem like a flame bait but it's not really, I'm just trying not to go crazy from OCD about switching from RoR to Python/Django and back.</p>
| 20 | 2009-01-01T17:12:12Z | 405,312 | <p>Alex Martelli gives a <a href="http://groups.google.com/group/comp.lang.python/msg/28422d707512283" rel="nofollow">good analysis of the subject</a>. It's a bit dated now, but I agree with the basic gist of it: <strong>Python and Ruby are two different ways of implementing the same thing</strong>. Sure there are some things you can do in Ruby that you can't do in Python. And sure Python's syntax is (arguably) better than Ruby's. But when you get down to it, there's not a whole lot of objective, scientific reason to prefer one over the other.</p>
<p>A common thing that you will hear is this: the platform is more important than the language and Python has a better platform than Ruby (this argument works both ways so don't vote me down, all you rubyists). And there is some truth to it. Unfortunately, it's not very relevant though. If you dislike the platform for either languages, there are implementations of both in Java and .Net, so you can use those if you have concerns about the platform.</p>
| 5 | 2009-01-01T19:03:23Z | [
"python",
"ruby",
"lisp"
] |
Please advise on Ruby vs Python, for someone who likes LISP a lot | 405,165 | <p>I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature.</p>
<p>Which one is closer to LISP: Python or Ruby? </p>
<p>I can't seem to be able to choose from Python and Ruby: they seem very similar but apparently Ruby is more functional and object-oriented, which are good things, while Python is more like Perl: a simple scripting language. Do I have the right impression?</p>
<p>PS - This might seem like a flame bait but it's not really, I'm just trying not to go crazy from OCD about switching from RoR to Python/Django and back.</p>
| 20 | 2009-01-01T17:12:12Z | 405,317 | <p>If you need Unicode support, remember to check how well supported it is. AFAIK, Python's support for Unicode is better than Ruby's, especially since Python 3.0. On the other hand, Python 3 is still missing some popular packages and 3rd party libraries, so that might play against.</p>
| 1 | 2009-01-01T19:06:39Z | [
"python",
"ruby",
"lisp"
] |
Please advise on Ruby vs Python, for someone who likes LISP a lot | 405,165 | <p>I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature.</p>
<p>Which one is closer to LISP: Python or Ruby? </p>
<p>I can't seem to be able to choose from Python and Ruby: they seem very similar but apparently Ruby is more functional and object-oriented, which are good things, while Python is more like Perl: a simple scripting language. Do I have the right impression?</p>
<p>PS - This might seem like a flame bait but it's not really, I'm just trying not to go crazy from OCD about switching from RoR to Python/Django and back.</p>
| 20 | 2009-01-01T17:12:12Z | 405,342 | <p><strong>Devils Advocate: Who Cares?</strong></p>
<p>They are both good systems and have an ecosystem of good web frameworks and active developer communities. I'm guessing that you're framing your decision based on the wrong criteria. The question sounds like you're fretting about whether you will hit implementation problems or other difficulties by choosing one over the other. <strong>Don't.</strong> </p>
<p>This is similar to Java/.Net decisions. There may be compelling reasons in a specific instance, but soft factors like the architect's familiarity with the platform are a much stronger predictor of project success.</p>
<p>I will admit that I've used Python much more than Ruby, but I wouldn't say that I have any great preference between the two apart from familiarity. I've used Python off and on since about 1998 and I like the Smalltalkish-ness of Ruby as I used Smalltalk briefly about 15 years ago. They both do similar things slightly differently.</p>
<p>I would like certain features from Ruby (or Smalltalk for that matter) but Python doesn't work that way. Instead, it has other features and language idioms are slightly different from Ruby or Smalltalk. <a href="http://stackoverflow.com/questions/405165/please-advise-on-ruby-vs-python-for-someone-who-likes-lisp-a-lot#405206">Several</a> of the <a href="http://stackoverflow.com/questions/405165/please-advise-on-ruby-vs-python-for-someone-who-likes-lisp-a-lot#405188">other</a> <a href="http://stackoverflow.com/questions/405165/please-advise-on-ruby-vs-python-for-someone-who-likes-lisp-a-lot#405312">posters</a> have linked out to articles that compare the two.</p>
<p>If you're worrying about Rails vs. Django, that suggests you're looking for a platform for web applications. Both languages have good tool support and an active developer community. Django seems to be the winner of the Python web framework melee and Rails seems to be in the process of 'crossing the chasm' and bringing Ruby along with it. Both are reasonably mature systems and have been demonstrated to work well for respectable traffic volumes.</p>
<p><strong>ProTip:</strong> The presence of religious wars is a good indicator that neither side has a compelling arguement.</p>
<p>So, I'm going to play devil's advocate and say that worrying about the choice is pointless. The languages have advantages and disadvantages with respect to each other but nothing that could be viewed as compelling in the general case. Fretting about the detailed merits of one platform or the other is framing the decision wrongly.</p>
<p>Pick one and use it. You will be able to build systems effectively with either.</p>
| 17 | 2009-01-01T19:23:00Z | [
"python",
"ruby",
"lisp"
] |
Please advise on Ruby vs Python, for someone who likes LISP a lot | 405,165 | <p>I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature.</p>
<p>Which one is closer to LISP: Python or Ruby? </p>
<p>I can't seem to be able to choose from Python and Ruby: they seem very similar but apparently Ruby is more functional and object-oriented, which are good things, while Python is more like Perl: a simple scripting language. Do I have the right impression?</p>
<p>PS - This might seem like a flame bait but it's not really, I'm just trying not to go crazy from OCD about switching from RoR to Python/Django and back.</p>
| 20 | 2009-01-01T17:12:12Z | 405,382 | <p>I am a Pythonista; however, based on your requirements, especially the "cool hacks on the language level", I would suggest you work on Ruby. Ruby is more flexible in the Perl way and you can do a lot of hacks; Python is targeted towards <em>readability</em>, which is a very good thing, and generally language hacks are a little frowned upon. Ruby's basic types can be modified in a hackish way that typically prototype languages allow, while Python's basic types are more suited for subclassing.</p>
<p>By the way, I would add a minor correction: both Ruby and Python are very, very object-oriented, and neither is intended to be used for quick-and-dirty scripts the Perl way. Among the two, Ruby is syntactically more similar to Perl than Python.</p>
| 3 | 2009-01-01T19:56:37Z | [
"python",
"ruby",
"lisp"
] |
Please advise on Ruby vs Python, for someone who likes LISP a lot | 405,165 | <p>I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature.</p>
<p>Which one is closer to LISP: Python or Ruby? </p>
<p>I can't seem to be able to choose from Python and Ruby: they seem very similar but apparently Ruby is more functional and object-oriented, which are good things, while Python is more like Perl: a simple scripting language. Do I have the right impression?</p>
<p>PS - This might seem like a flame bait but it's not really, I'm just trying not to go crazy from OCD about switching from RoR to Python/Django and back.</p>
| 20 | 2009-01-01T17:12:12Z | 405,474 | <p>I'm a Rubyist who chose the language based on very similar criteria. Python is a good language and I enjoy working with it too, but I think Ruby is somewhat more Lispy in the degree of freedom it gives to the programmer. Python seems to impose its opinions a little bit more (which can be a good thing, but isn't according to our criteria here).</p>
<p>Python certainly isn't more Perlishâ Ruby is essentially a Smalltalk/Perl mashup (some of its less-used features are pulled directly from Perl), whereas Python is only distantly related to either.</p>
| 0 | 2009-01-01T20:58:37Z | [
"python",
"ruby",
"lisp"
] |
Please advise on Ruby vs Python, for someone who likes LISP a lot | 405,165 | <p>I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature.</p>
<p>Which one is closer to LISP: Python or Ruby? </p>
<p>I can't seem to be able to choose from Python and Ruby: they seem very similar but apparently Ruby is more functional and object-oriented, which are good things, while Python is more like Perl: a simple scripting language. Do I have the right impression?</p>
<p>PS - This might seem like a flame bait but it's not really, I'm just trying not to go crazy from OCD about switching from RoR to Python/Django and back.</p>
| 20 | 2009-01-01T17:12:12Z | 405,577 | <p>pick the most popular one for your domain so your work gets the most visibility. some might say ruby/rails for web, python for everything else. picking a language just because its like lisp is really not appropriate for a professional.</p>
| 0 | 2009-01-01T22:27:38Z | [
"python",
"ruby",
"lisp"
] |
Please advise on Ruby vs Python, for someone who likes LISP a lot | 405,165 | <p>I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature.</p>
<p>Which one is closer to LISP: Python or Ruby? </p>
<p>I can't seem to be able to choose from Python and Ruby: they seem very similar but apparently Ruby is more functional and object-oriented, which are good things, while Python is more like Perl: a simple scripting language. Do I have the right impression?</p>
<p>PS - This might seem like a flame bait but it's not really, I'm just trying not to go crazy from OCD about switching from RoR to Python/Django and back.</p>
| 20 | 2009-01-01T17:12:12Z | 6,325,009 | <p>If you like lisp, I think you'll be better like ruby but c++ reminds me more of python. I've posted a small post about this subject : <a href="http://hartator.wordpress.com/2011/06/12/ruby-vs-python-2011/" rel="nofollow">http://hartator.wordpress.com/2011/06/12/ruby-vs-python-2011/</a></p>
| 0 | 2011-06-12T22:06:54Z | [
"python",
"ruby",
"lisp"
] |
Many instances of a class | 405,282 | <p>I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be.</p>
<p>So, my question:</p>
<p>How can I automatically give a name to an object?</p>
<p>I was thinking of creating a "Herd" class which could be all the animals of that type alive at the same time...</p>
| 3 | 2009-01-01T18:47:32Z | 405,292 | <p>Hm, well you normally just stuff all those instances in a list and then iterate over that list if you want to do something with them. If you want to automatically keep track of each instance created you can also make the adding to the list implicit in the class' constructor or create a factory method that keeps track of the created instances.</p>
| 7 | 2009-01-01T18:52:03Z | [
"python",
"class",
"object",
"multiple-instances"
] |
Many instances of a class | 405,282 | <p>I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be.</p>
<p>So, my question:</p>
<p>How can I automatically give a name to an object?</p>
<p>I was thinking of creating a "Herd" class which could be all the animals of that type alive at the same time...</p>
| 3 | 2009-01-01T18:47:32Z | 405,297 | <p>you could make an 'animal' class with a name attribute.</p>
<p>Or</p>
<p>you could programmically define the class like so:</p>
<pre><code>
from new import classobj
my_class=classobj('Foo',(object,),{})
</code></pre>
<p>Found this:
<a href="http://www.gamedev.net/community/forums/topic.asp?topic_id=445037" rel="nofollow">http://www.gamedev.net/community/forums/topic.asp?topic_id=445037</a></p>
| 2 | 2009-01-01T18:53:15Z | [
"python",
"class",
"object",
"multiple-instances"
] |
Many instances of a class | 405,282 | <p>I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be.</p>
<p>So, my question:</p>
<p>How can I automatically give a name to an object?</p>
<p>I was thinking of creating a "Herd" class which could be all the animals of that type alive at the same time...</p>
| 3 | 2009-01-01T18:47:32Z | 405,331 | <p>Like this?</p>
<pre><code>class Animal( object ):
pass # lots of details omitted
herd= [ Animal() for i in range(10000) ]
</code></pre>
<p>At this point, herd will have 10,000 distinct instances of the <code>Animal</code> class.</p>
| 3 | 2009-01-01T19:17:31Z | [
"python",
"class",
"object",
"multiple-instances"
] |
Many instances of a class | 405,282 | <p>I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be.</p>
<p>So, my question:</p>
<p>How can I automatically give a name to an object?</p>
<p>I was thinking of creating a "Herd" class which could be all the animals of that type alive at the same time...</p>
| 3 | 2009-01-01T18:47:32Z | 405,575 | <p>If you need a way to refer to them individually, it's relatively common to have the class give each instance a unique identifier on initialization:</p>
<pre><code>>>> import itertools
>>> class Animal(object):
... id_iter = itertools.count(1)
... def __init__(self):
... self.id = self.id_iter.next()
...
>>> print(Animal().id)
1
>>> print(Animal().id)
2
>>> print(Animal().id)
3
</code></pre>
| 3 | 2009-01-01T22:26:20Z | [
"python",
"class",
"object",
"multiple-instances"
] |
Many instances of a class | 405,282 | <p>I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be.</p>
<p>So, my question:</p>
<p>How can I automatically give a name to an object?</p>
<p>I was thinking of creating a "Herd" class which could be all the animals of that type alive at the same time...</p>
| 3 | 2009-01-01T18:47:32Z | 405,759 | <p>Any instance could have a name attribute. So it sounds like you may be asking how to dynamically name a <em>class</em>, not an <em>instance</em>. If that's the case, you can explicitly set the __name__ attribute of a class, or better yet just create the class with the builtin <a href="http://docs.python.org/library/functions.html#type" rel="nofollow">type</a> (with 3 args).</p>
<pre><code>class Ungulate(Mammal):
hoofed = True
</code></pre>
<p>would be equivalent to</p>
<pre><code>cls = type('Ungulate', (Mammal,), {'hoofed': True})
</code></pre>
| 1 | 2009-01-02T00:44:58Z | [
"python",
"class",
"object",
"multiple-instances"
] |
Mysql connection pooling question: is it worth it? | 405,352 | <p>I recall hearing that the connection process in mysql was designed to be very fast compared to other RDBMSes, and that therefore using <a href="http://www.sqlalchemy.org/">a library that provides connection pooling</a> (SQLAlchemy) won't actually help you that much if you enable the connection pool.</p>
<p>Does anyone have any experience with this?</p>
<p>I'm leery of enabling it because of the possibility that if some code does something stateful to a db connection and (perhaps mistakenly) doesn't clean up after itself, that state which would normally get cleaned up upon closing the connection will instead get propagated to subsequent code that gets a recycled connection.</p>
| 15 | 2009-01-01T19:32:29Z | 405,357 | <p>Even if the connection part of MySQL itself is pretty slick, presumably there's still a network connection involved (whether that's loopback or physical). If you're making a <em>lot</em> of requests, that could get significantly expensive. It will depend (as is so often the case) on exactly what your application does, of course - if you're doing a lot of work per connection, then that will dominate and you won't gain a lot.</p>
<p>When in doubt, benchmark - but I would by-and-large trust that a connection pooling library (at least, a reputable one) should work properly and reset things appropriately.</p>
| 6 | 2009-01-01T19:37:35Z | [
"python",
"mysql",
"sqlalchemy",
"connection-pooling"
] |
Mysql connection pooling question: is it worth it? | 405,352 | <p>I recall hearing that the connection process in mysql was designed to be very fast compared to other RDBMSes, and that therefore using <a href="http://www.sqlalchemy.org/">a library that provides connection pooling</a> (SQLAlchemy) won't actually help you that much if you enable the connection pool.</p>
<p>Does anyone have any experience with this?</p>
<p>I'm leery of enabling it because of the possibility that if some code does something stateful to a db connection and (perhaps mistakenly) doesn't clean up after itself, that state which would normally get cleaned up upon closing the connection will instead get propagated to subsequent code that gets a recycled connection.</p>
| 15 | 2009-01-01T19:32:29Z | 405,398 | <p>The connection pool speeds things up in that fact that you do not have create a java.sql.Connection object every time you do a database query. I use the Tomcat connection pool to a mysql database for web applications that do a lot of queries, during high user load there is noticeable speed improvement. </p>
| 0 | 2009-01-01T20:02:42Z | [
"python",
"mysql",
"sqlalchemy",
"connection-pooling"
] |
Mysql connection pooling question: is it worth it? | 405,352 | <p>I recall hearing that the connection process in mysql was designed to be very fast compared to other RDBMSes, and that therefore using <a href="http://www.sqlalchemy.org/">a library that provides connection pooling</a> (SQLAlchemy) won't actually help you that much if you enable the connection pool.</p>
<p>Does anyone have any experience with this?</p>
<p>I'm leery of enabling it because of the possibility that if some code does something stateful to a db connection and (perhaps mistakenly) doesn't clean up after itself, that state which would normally get cleaned up upon closing the connection will instead get propagated to subsequent code that gets a recycled connection.</p>
| 15 | 2009-01-01T19:32:29Z | 405,914 | <p>There's no need to worry about residual state on a connection when using SQLA's connection pool, unless your application is changing connectionwide options like transaction isolation levels (which generally is not the case). SQLA's connection pool issues a connection.rollback() on the connection when its checked back in, so that any transactional state or locks are cleared.</p>
<p>It is possible that MySQL's connection time is pretty fast, especially if you're connecting over unix sockets on the same machine. If you do use a connection pool, you also want to ensure that connections are recycled after some period of time as MySQL's client library will shut down connections that are idle for more than 8 hours automatically (in SQLAlchemy this is the pool_recycle option).</p>
<p>You can quickly do some benching of connection pool vs. non with a SQLA application by changing the pool implementation from the default of QueuePool to NullPool, which is a pool implementation that doesn't actually pool anything - it connects and disconnects for real when the proxied connection is acquired and later closed.</p>
| 10 | 2009-01-02T02:41:50Z | [
"python",
"mysql",
"sqlalchemy",
"connection-pooling"
] |
Mysql connection pooling question: is it worth it? | 405,352 | <p>I recall hearing that the connection process in mysql was designed to be very fast compared to other RDBMSes, and that therefore using <a href="http://www.sqlalchemy.org/">a library that provides connection pooling</a> (SQLAlchemy) won't actually help you that much if you enable the connection pool.</p>
<p>Does anyone have any experience with this?</p>
<p>I'm leery of enabling it because of the possibility that if some code does something stateful to a db connection and (perhaps mistakenly) doesn't clean up after itself, that state which would normally get cleaned up upon closing the connection will instead get propagated to subsequent code that gets a recycled connection.</p>
| 15 | 2009-01-01T19:32:29Z | 415,006 | <p>Short answer: you need to benchmark it.</p>
<p>Long answer: it depends. MySQL is fast for connection setup, so avoiding that cost is not a good reason to go for connection pooling. Where you win there is if the queries run are few and fast because then you will see a win with pooling.</p>
<p>The other worry is how the application treats the SQL thread. If it does no SQL transactions, and makes no assumptions about the state of the thread, then pooling won't be a problem. OTOH, code that relies on the closing of the thread to discard temporary tables or to rollback transactions will have a lot of problems with pooling.</p>
| 2 | 2009-01-06T00:10:55Z | [
"python",
"mysql",
"sqlalchemy",
"connection-pooling"
] |
Mysql connection pooling question: is it worth it? | 405,352 | <p>I recall hearing that the connection process in mysql was designed to be very fast compared to other RDBMSes, and that therefore using <a href="http://www.sqlalchemy.org/">a library that provides connection pooling</a> (SQLAlchemy) won't actually help you that much if you enable the connection pool.</p>
<p>Does anyone have any experience with this?</p>
<p>I'm leery of enabling it because of the possibility that if some code does something stateful to a db connection and (perhaps mistakenly) doesn't clean up after itself, that state which would normally get cleaned up upon closing the connection will instead get propagated to subsequent code that gets a recycled connection.</p>
| 15 | 2009-01-01T19:32:29Z | 7,840,841 | <p>I made a simple RESTful service with Django and tested it with and without connection pooling. In my case, the difference was quite noticeable.</p>
<p>In a LAN, without it, response time was between 1 and 5 seconds. With it, less than 20 ms.
Results may vary, but the configuration I'm using for the MySQL & Apache servers is pretty standard low-end.</p>
<p>If you're serving UI pages over the internet the extra time may not be noticeable to the user, but in my case it was unacceptable, so I opted for using the pool. Hope this helps you.</p>
| 0 | 2011-10-20T19:00:38Z | [
"python",
"mysql",
"sqlalchemy",
"connection-pooling"
] |
Python update object from dictionary | 405,489 | <p>Is there a built-in function/operator I could use to unpack values from a dictionary and assign it into instance variables?</p>
<p>This is what I intend to do:</p>
<pre><code>c = MyClass()
c.foo = 123
c.bar = 123
# c.foo == 123 and c.bar == 123
d = {'bar': 456}
c.update(d)
# c.foo == 123 and c.bar == 456
</code></pre>
<p>Something akin to dictionary <code>update()</code> which load values from another dictionary but for plain object/class instance?</p>
| 11 | 2009-01-01T21:12:51Z | 405,492 | <p>Have you tried</p>
<pre><code>f.__dict__.update( b )
</code></pre>
<p>?</p>
| 21 | 2009-01-01T21:14:32Z | [
"python",
"iterable-unpacking"
] |
Python update object from dictionary | 405,489 | <p>Is there a built-in function/operator I could use to unpack values from a dictionary and assign it into instance variables?</p>
<p>This is what I intend to do:</p>
<pre><code>c = MyClass()
c.foo = 123
c.bar = 123
# c.foo == 123 and c.bar == 123
d = {'bar': 456}
c.update(d)
# c.foo == 123 and c.bar == 456
</code></pre>
<p>Something akin to dictionary <code>update()</code> which load values from another dictionary but for plain object/class instance?</p>
| 11 | 2009-01-01T21:12:51Z | 405,498 | <p>Also, maybe it would be good style to have a wrapper around the dict's update method:</p>
<pre><code>def update(self, b):
self.__dict__.update(b)
</code></pre>
<p>PS: Sorry for not commenting at @<a href="http://stackoverflow.com/users/10661/s-lott">S.Lott</a> 's post but I don't have the rep yet.</p>
| 4 | 2009-01-01T21:21:15Z | [
"python",
"iterable-unpacking"
] |
Python update object from dictionary | 405,489 | <p>Is there a built-in function/operator I could use to unpack values from a dictionary and assign it into instance variables?</p>
<p>This is what I intend to do:</p>
<pre><code>c = MyClass()
c.foo = 123
c.bar = 123
# c.foo == 123 and c.bar == 123
d = {'bar': 456}
c.update(d)
# c.foo == 123 and c.bar == 456
</code></pre>
<p>Something akin to dictionary <code>update()</code> which load values from another dictionary but for plain object/class instance?</p>
| 11 | 2009-01-01T21:12:51Z | 408,016 | <p>there is also another way of doing it by looping through the items in d. this doesn't have the same assuption that they will get stored in <code>c.__dict__</code> which isn't always true. </p>
<pre><code>d = {'bar': 456}
for key,value in d.items():
setattr(c,key,value)
</code></pre>
<p>or you could write a <code>update</code> method as part of <code>MyClass</code> so that <code>c.update(d)</code> works like you expected it to.</p>
<pre><code>def update(self,newdata):
for key,value in newdata:
setattr(self,key,value)
</code></pre>
<p>check out the help for setattr</p>
<blockquote>
<pre><code>setattr(...)
setattr(object, name, value)
Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
''x.y = v''.
</code></pre>
</blockquote>
| 24 | 2009-01-02T21:02:16Z | [
"python",
"iterable-unpacking"
] |
Hiding implementation details on an email templating system written in Python | 405,509 | <p>I am writing an application where one of the features is to allow the user to write an email template using Markdown syntax.</p>
<p>Besides formatting, the user must be able to use placeholders for a couple of variables that would get replaced at runtime. </p>
<p>The way this is currently working is very simple: the templates have the Pythonic %(var)s placeholders and I replace those with a dictionary before applying Markdown2 formatting.</p>
<p>Turns out that the end user of this system will be a tech-savvy user and I wouldn't like to make it obvious to everyone that it's written in Python. </p>
<p>It's not that I don't like Python... I actually think Python is the perfect tool for the job, I just don't want to expose that to the user (would like the same even if it were written in Java, Perl, Ruby or anything else).</p>
<p>So I'd like to ask for insights on what would be, in your opinion, the best way to expose placeholders for the users:</p>
<ol>
<li><p>What do you think is the best placeholder format (thinks like ${var}, $(var) or #{var})?</p></li>
<li><p>What would be the best way to replace those placeholders?</p></li>
</ol>
<p>I though of using a Regular Expression to change - for instance - ${var} into %(var)s and then applying the regular Python templating substitution, but I am not sure that's the best approach.</p>
<p>If you go that way, it would be very nice if you could indicate me what is a draft of that regular expression as well.</p>
<p>Thanks!</p>
<p><strong>Update</strong>: An user pointed out using full-blown templating systems, but I think that may not be worth it, since all I need is placeholders substitution: I won't have loops or anything like that.</p>
<p><strong>Final Update</strong>: I have chosen not to use any template engines at this time. I chose to go with the simpler string.Template approach (as pointed out on a comment by <a href="http://stackoverflow.com/users/49032/hyperboreean">hyperboreean</a>). Truth is that I don't like to pick a solution because sometime in the future there may be a need. I will keep all those suggestions on my sleeve, and if on the lifespan of the application there is a clear need for one or more features offered by them, I'll revisit the idea. Right now, I really think it's an overkill. Having full blown templates that <strong>the end user</strong> can edit as he wants is, at least on my point of view, more trouble than benefit. Nevertheless, it feels much nicer being aware of the reasons I did not went down that path, than just not researching anything and choosing it. </p>
<p>Thanks a lot for all the input.</p>
| 0 | 2009-01-01T21:34:26Z | 405,513 | <p>Use a real template tool: <a href="http://www.makotemplates.org/" rel="nofollow">mako</a> or <a href="http://jinja.pocoo.org/" rel="nofollow">jinja</a>. Don't roll your own. Not worth it.</p>
| 6 | 2009-01-01T21:36:53Z | [
"python",
"email",
"formatting",
"templates"
] |
Hiding implementation details on an email templating system written in Python | 405,509 | <p>I am writing an application where one of the features is to allow the user to write an email template using Markdown syntax.</p>
<p>Besides formatting, the user must be able to use placeholders for a couple of variables that would get replaced at runtime. </p>
<p>The way this is currently working is very simple: the templates have the Pythonic %(var)s placeholders and I replace those with a dictionary before applying Markdown2 formatting.</p>
<p>Turns out that the end user of this system will be a tech-savvy user and I wouldn't like to make it obvious to everyone that it's written in Python. </p>
<p>It's not that I don't like Python... I actually think Python is the perfect tool for the job, I just don't want to expose that to the user (would like the same even if it were written in Java, Perl, Ruby or anything else).</p>
<p>So I'd like to ask for insights on what would be, in your opinion, the best way to expose placeholders for the users:</p>
<ol>
<li><p>What do you think is the best placeholder format (thinks like ${var}, $(var) or #{var})?</p></li>
<li><p>What would be the best way to replace those placeholders?</p></li>
</ol>
<p>I though of using a Regular Expression to change - for instance - ${var} into %(var)s and then applying the regular Python templating substitution, but I am not sure that's the best approach.</p>
<p>If you go that way, it would be very nice if you could indicate me what is a draft of that regular expression as well.</p>
<p>Thanks!</p>
<p><strong>Update</strong>: An user pointed out using full-blown templating systems, but I think that may not be worth it, since all I need is placeholders substitution: I won't have loops or anything like that.</p>
<p><strong>Final Update</strong>: I have chosen not to use any template engines at this time. I chose to go with the simpler string.Template approach (as pointed out on a comment by <a href="http://stackoverflow.com/users/49032/hyperboreean">hyperboreean</a>). Truth is that I don't like to pick a solution because sometime in the future there may be a need. I will keep all those suggestions on my sleeve, and if on the lifespan of the application there is a clear need for one or more features offered by them, I'll revisit the idea. Right now, I really think it's an overkill. Having full blown templates that <strong>the end user</strong> can edit as he wants is, at least on my point of view, more trouble than benefit. Nevertheless, it feels much nicer being aware of the reasons I did not went down that path, than just not researching anything and choosing it. </p>
<p>Thanks a lot for all the input.</p>
| 0 | 2009-01-01T21:34:26Z | 405,515 | <p>Have a light templating system ... I am not sure if you can use some of the ones TurboGears provides (Kid or Genshi)</p>
| 2 | 2009-01-01T21:39:26Z | [
"python",
"email",
"formatting",
"templates"
] |
Hiding implementation details on an email templating system written in Python | 405,509 | <p>I am writing an application where one of the features is to allow the user to write an email template using Markdown syntax.</p>
<p>Besides formatting, the user must be able to use placeholders for a couple of variables that would get replaced at runtime. </p>
<p>The way this is currently working is very simple: the templates have the Pythonic %(var)s placeholders and I replace those with a dictionary before applying Markdown2 formatting.</p>
<p>Turns out that the end user of this system will be a tech-savvy user and I wouldn't like to make it obvious to everyone that it's written in Python. </p>
<p>It's not that I don't like Python... I actually think Python is the perfect tool for the job, I just don't want to expose that to the user (would like the same even if it were written in Java, Perl, Ruby or anything else).</p>
<p>So I'd like to ask for insights on what would be, in your opinion, the best way to expose placeholders for the users:</p>
<ol>
<li><p>What do you think is the best placeholder format (thinks like ${var}, $(var) or #{var})?</p></li>
<li><p>What would be the best way to replace those placeholders?</p></li>
</ol>
<p>I though of using a Regular Expression to change - for instance - ${var} into %(var)s and then applying the regular Python templating substitution, but I am not sure that's the best approach.</p>
<p>If you go that way, it would be very nice if you could indicate me what is a draft of that regular expression as well.</p>
<p>Thanks!</p>
<p><strong>Update</strong>: An user pointed out using full-blown templating systems, but I think that may not be worth it, since all I need is placeholders substitution: I won't have loops or anything like that.</p>
<p><strong>Final Update</strong>: I have chosen not to use any template engines at this time. I chose to go with the simpler string.Template approach (as pointed out on a comment by <a href="http://stackoverflow.com/users/49032/hyperboreean">hyperboreean</a>). Truth is that I don't like to pick a solution because sometime in the future there may be a need. I will keep all those suggestions on my sleeve, and if on the lifespan of the application there is a clear need for one or more features offered by them, I'll revisit the idea. Right now, I really think it's an overkill. Having full blown templates that <strong>the end user</strong> can edit as he wants is, at least on my point of view, more trouble than benefit. Nevertheless, it feels much nicer being aware of the reasons I did not went down that path, than just not researching anything and choosing it. </p>
<p>Thanks a lot for all the input.</p>
| 0 | 2009-01-01T21:34:26Z | 406,723 | <p>I would recommend <a href="http://jinja.pocoo.org/2/" rel="nofollow">jinja2</a>.</p>
<p>It shouldn't create runtime performance issue since it compiles templates to python. It would offer much greater flexibility. As for <em>maintainability</em>; it depends much on the coder, but theoretically (and admittedly superficially) I can't see why it should be harder to maintain.</p>
<p>With a little more work you can give your tech-savvy user the ability to define the substitution style herself. Or choose one from defaults you supply.</p>
| 1 | 2009-01-02T12:56:21Z | [
"python",
"email",
"formatting",
"templates"
] |
Hiding implementation details on an email templating system written in Python | 405,509 | <p>I am writing an application where one of the features is to allow the user to write an email template using Markdown syntax.</p>
<p>Besides formatting, the user must be able to use placeholders for a couple of variables that would get replaced at runtime. </p>
<p>The way this is currently working is very simple: the templates have the Pythonic %(var)s placeholders and I replace those with a dictionary before applying Markdown2 formatting.</p>
<p>Turns out that the end user of this system will be a tech-savvy user and I wouldn't like to make it obvious to everyone that it's written in Python. </p>
<p>It's not that I don't like Python... I actually think Python is the perfect tool for the job, I just don't want to expose that to the user (would like the same even if it were written in Java, Perl, Ruby or anything else).</p>
<p>So I'd like to ask for insights on what would be, in your opinion, the best way to expose placeholders for the users:</p>
<ol>
<li><p>What do you think is the best placeholder format (thinks like ${var}, $(var) or #{var})?</p></li>
<li><p>What would be the best way to replace those placeholders?</p></li>
</ol>
<p>I though of using a Regular Expression to change - for instance - ${var} into %(var)s and then applying the regular Python templating substitution, but I am not sure that's the best approach.</p>
<p>If you go that way, it would be very nice if you could indicate me what is a draft of that regular expression as well.</p>
<p>Thanks!</p>
<p><strong>Update</strong>: An user pointed out using full-blown templating systems, but I think that may not be worth it, since all I need is placeholders substitution: I won't have loops or anything like that.</p>
<p><strong>Final Update</strong>: I have chosen not to use any template engines at this time. I chose to go with the simpler string.Template approach (as pointed out on a comment by <a href="http://stackoverflow.com/users/49032/hyperboreean">hyperboreean</a>). Truth is that I don't like to pick a solution because sometime in the future there may be a need. I will keep all those suggestions on my sleeve, and if on the lifespan of the application there is a clear need for one or more features offered by them, I'll revisit the idea. Right now, I really think it's an overkill. Having full blown templates that <strong>the end user</strong> can edit as he wants is, at least on my point of view, more trouble than benefit. Nevertheless, it feels much nicer being aware of the reasons I did not went down that path, than just not researching anything and choosing it. </p>
<p>Thanks a lot for all the input.</p>
| 0 | 2009-01-01T21:34:26Z | 406,786 | <p>You could try Python 2.6/3.0's new str.format() method: <a href="http://docs.python.org/library/string.html#formatstrings" rel="nofollow">http://docs.python.org/library/string.html#formatstrings</a></p>
<p>This looks a bit different to %-formatting and might not be as instantly recognisable as Python:</p>
<pre><code>'fish{chips}'.format(chips= 'x')
</code></pre>
| 0 | 2009-01-02T13:27:39Z | [
"python",
"email",
"formatting",
"templates"
] |
if all in list == something | 405,516 | <p>Using python 2.6
is there a way to check if all the items of a sequence equals a given value, in one statement?</p>
<pre><code>[pseudocode]
my_sequence = (2,5,7,82,35)
if all the values in (type(i) for i in my_sequence) == int:
do()
</code></pre>
<p>instead of, say:</p>
<pre><code>my_sequence = (2,5,7,82,35)
all_int = True
for i in my_sequence:
if type(i) is not int:
all_int = False
break
if all_int:
do()
</code></pre>
| 13 | 2009-01-01T21:41:22Z | 405,519 | <p>Do you mean</p>
<pre><code>all( type(i) is int for i in my_list )
</code></pre>
<p>?</p>
<p>Edit: Changed to <code>is</code>. Slightly faster.</p>
| 13 | 2009-01-01T21:43:29Z | [
"python",
"python-2.6"
] |
if all in list == something | 405,516 | <p>Using python 2.6
is there a way to check if all the items of a sequence equals a given value, in one statement?</p>
<pre><code>[pseudocode]
my_sequence = (2,5,7,82,35)
if all the values in (type(i) for i in my_sequence) == int:
do()
</code></pre>
<p>instead of, say:</p>
<pre><code>my_sequence = (2,5,7,82,35)
all_int = True
for i in my_sequence:
if type(i) is not int:
all_int = False
break
if all_int:
do()
</code></pre>
| 13 | 2009-01-01T21:41:22Z | 405,520 | <p>Use: </p>
<pre><code>all( type(i) is int for i in lst )
</code></pre>
<p>Example:</p>
<pre><code>In [1]: lst = range(10)
In [2]: all( type(i) is int for i in lst )
Out[2]: True
In [3]: lst.append('steve')
In [4]: all( type(i) is int for i in lst )
Out[4]: False
</code></pre>
<p>[Edit]. Made cleaner as per comments.</p>
| 34 | 2009-01-01T21:45:31Z | [
"python",
"python-2.6"
] |
if all in list == something | 405,516 | <p>Using python 2.6
is there a way to check if all the items of a sequence equals a given value, in one statement?</p>
<pre><code>[pseudocode]
my_sequence = (2,5,7,82,35)
if all the values in (type(i) for i in my_sequence) == int:
do()
</code></pre>
<p>instead of, say:</p>
<pre><code>my_sequence = (2,5,7,82,35)
all_int = True
for i in my_sequence:
if type(i) is not int:
all_int = False
break
if all_int:
do()
</code></pre>
| 13 | 2009-01-01T21:41:22Z | 405,649 | <p>I would suggest:</p>
<pre><code>if all(isinstance(i, int) for i in my_list):
</code></pre>
<p><a href="http://www.python.org/doc/current/library/functions.html#all"><code>all</code></a> and <a href="http://www.python.org/doc/current/library/functions.html#any"><code>any</code></a> first appeared in Python 2.5. If you're using an older version of Python, the links provide sample implementations.</p>
<p>I also suggest using <code>isinstance</code> since it will also catch subclasses of <code>int</code>.</p>
| 5 | 2009-01-01T23:06:42Z | [
"python",
"python-2.6"
] |
if all in list == something | 405,516 | <p>Using python 2.6
is there a way to check if all the items of a sequence equals a given value, in one statement?</p>
<pre><code>[pseudocode]
my_sequence = (2,5,7,82,35)
if all the values in (type(i) for i in my_sequence) == int:
do()
</code></pre>
<p>instead of, say:</p>
<pre><code>my_sequence = (2,5,7,82,35)
all_int = True
for i in my_sequence:
if type(i) is not int:
all_int = False
break
if all_int:
do()
</code></pre>
| 13 | 2009-01-01T21:41:22Z | 18,727,943 | <p>For the sake of completeness I thought I would add the fact that numpy's 'all' is different from the built-in 'all'. If for example running Python through Python(x,y), numpy is loaded automatically (and cannot be unloaded afaik), so when trying to run the above code it produces rather unexpected results:</p>
<pre><code>>>> if (all(v == 0 for v in [0,1])):
... print 'this should not happen'
... this should not happen
</code></pre>
<p>More info on this here: <a href="http://stackoverflow.com/questions/14391501/numpy-all-differing-from-builtin-all">numpy all differing from builtin all</a>. As a solution you can either surround the generator with brackets to produce a list:</p>
<blockquote>
<blockquote>
<blockquote>
<p>all( [v == 0 for v in [0,1]] )<br>
False</p>
</blockquote>
</blockquote>
</blockquote>
<p>Or call the built-in function explicitly:</p>
<pre><code>>>> __builtins__.all(v == 0 for v in [0,1,'2'])
False
</code></pre>
<p>Edit: Found a way to stop Spyder from importing numpy per default:
<a href="http://stackoverflow.com/questions/14400993/spyder-default-module-import-list">Spyder default module import list</a></p>
| 0 | 2013-09-10T20:13:05Z | [
"python",
"python-2.6"
] |
What is a cyclic data structure good for? | 405,540 | <p>I was just reading through <a href="http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false" rel="nofollow">"Learning Python" by Mark Lutz and came across this code sample</a>:</p>
<pre><code>
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
</code></pre>
<p>It was identified as a cyclic data structure.</p>
<p>So I was wondering, and here is my question:</p>
<h2><strong>What is a 'cyclic data structure' used for in real life programming?</strong></h2>
<p>There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L</p>
<pre><code>
>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'
</code></pre>
| 13 | 2009-01-01T22:06:09Z | 405,559 | <p>Erm, I am not sure as I a haven't used them at all in real life, but it could be used to simulate a nested data structure? See <a href="http://www.cs.nott.ac.uk/~nhn/TFP2006/Papers/27-GhaniHamanaUustaluVene-CyclicStructuresAsNestedDatatypes.pdf" rel="nofollow">this</a> link</p>
| 1 | 2009-01-01T22:15:06Z | [
"python",
"data-structures",
"recursion",
"cyclic-reference"
] |
What is a cyclic data structure good for? | 405,540 | <p>I was just reading through <a href="http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false" rel="nofollow">"Learning Python" by Mark Lutz and came across this code sample</a>:</p>
<pre><code>
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
</code></pre>
<p>It was identified as a cyclic data structure.</p>
<p>So I was wondering, and here is my question:</p>
<h2><strong>What is a 'cyclic data structure' used for in real life programming?</strong></h2>
<p>There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L</p>
<pre><code>
>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'
</code></pre>
| 13 | 2009-01-01T22:06:09Z | 405,562 | <p>One example would be a linked list where the last item points the first. This would allow you to create a fixed number of items but always be able to get a next item.</p>
| 0 | 2009-01-01T22:17:08Z | [
"python",
"data-structures",
"recursion",
"cyclic-reference"
] |
What is a cyclic data structure good for? | 405,540 | <p>I was just reading through <a href="http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false" rel="nofollow">"Learning Python" by Mark Lutz and came across this code sample</a>:</p>
<pre><code>
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
</code></pre>
<p>It was identified as a cyclic data structure.</p>
<p>So I was wondering, and here is my question:</p>
<h2><strong>What is a 'cyclic data structure' used for in real life programming?</strong></h2>
<p>There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L</p>
<pre><code>
>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'
</code></pre>
| 13 | 2009-01-01T22:06:09Z | 405,564 | <p>Lots of things. Circular buffer, for example: you have some collection of data with a front and a back, but an arbitrary number of nodes, and the "next" item from the last should take you back to the first.</p>
<p>Graph structures are often cyclic; acyclicity is a special case. Consider, for example, a graph containing all the cities and roads in a traveling salesman problem.</p>
<p><hr></p>
<p>Okay, here's a particular example for you. I set up a collection of towns here in Colorado:</p>
<pre><code>V=["Boulder", "Denver", "Colorado Springs", "Pueblo", "Limon"]
</code></pre>
<p>I then set up pairs of cities where there is a road connecting them.</p>
<pre><code>E=[["Boulder", "Denver"],
["Denver", "Colorado Springs"],
["Colorado Springs", "Pueblo"],
["Denver", "Limon"],
["Colorado Springs", "Limon"]]
</code></pre>
<p>This has a bunch of cycles. For example, you can drive from Colorado Springs, to Limon, to Denver, and back to Colorado Springs.</p>
<p>If you create a data structure that contains all the cities in V and all the roads in E, that's a <em>graph</em> data structure. This graph would have cycles.</p>
| 18 | 2009-01-01T22:17:30Z | [
"python",
"data-structures",
"recursion",
"cyclic-reference"
] |
What is a cyclic data structure good for? | 405,540 | <p>I was just reading through <a href="http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false" rel="nofollow">"Learning Python" by Mark Lutz and came across this code sample</a>:</p>
<pre><code>
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
</code></pre>
<p>It was identified as a cyclic data structure.</p>
<p>So I was wondering, and here is my question:</p>
<h2><strong>What is a 'cyclic data structure' used for in real life programming?</strong></h2>
<p>There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L</p>
<pre><code>
>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'
</code></pre>
| 13 | 2009-01-01T22:06:09Z | 405,565 | <p>when doing lattice simulations cyclic/toroidal boundary conditions are often used. usually a simple <code>lattice[i%L]</code> would suffice, but i suppose one could create the lattice to be cyclic.</p>
| 0 | 2009-01-01T22:17:42Z | [
"python",
"data-structures",
"recursion",
"cyclic-reference"
] |
What is a cyclic data structure good for? | 405,540 | <p>I was just reading through <a href="http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false" rel="nofollow">"Learning Python" by Mark Lutz and came across this code sample</a>:</p>
<pre><code>
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
</code></pre>
<p>It was identified as a cyclic data structure.</p>
<p>So I was wondering, and here is my question:</p>
<h2><strong>What is a 'cyclic data structure' used for in real life programming?</strong></h2>
<p>There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L</p>
<pre><code>
>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'
</code></pre>
| 13 | 2009-01-01T22:06:09Z | 405,566 | <p>A nested structure could be used in a test case for a garbage collector.</p>
| 1 | 2009-01-01T22:18:04Z | [
"python",
"data-structures",
"recursion",
"cyclic-reference"
] |
What is a cyclic data structure good for? | 405,540 | <p>I was just reading through <a href="http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false" rel="nofollow">"Learning Python" by Mark Lutz and came across this code sample</a>:</p>
<pre><code>
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
</code></pre>
<p>It was identified as a cyclic data structure.</p>
<p>So I was wondering, and here is my question:</p>
<h2><strong>What is a 'cyclic data structure' used for in real life programming?</strong></h2>
<p>There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L</p>
<pre><code>
>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'
</code></pre>
| 13 | 2009-01-01T22:06:09Z | 405,571 | <p>I recently created a cyclic data structure to represent the eight cardinal and ordinal directions. Its useful for each direction to know its neighbors. For instance, Direction.North knows that Direction.NorthEast and Direction.NorthWest are its neighbors. </p>
<p>This is cyclic because each neighor knows its neighbors until it goes full swing around (the "->" represents clockwise):</p>
<p>North -> NorthEast -> East -> SouthEast -> South -> SouthWest -> West -> NorthWest -> North -> ...</p>
<p>Notice we came back to North.</p>
<p>That allows me to do stuff like this (in C#):</p>
<pre><code>public class Direction
{
...
public IEnumerable<Direction> WithTwoNeighbors
{
get {
yield return this;
yield return this.CounterClockwise;
yield return this.Clockwise;
}
}
}
...
public void TryToMove (Direction dir)
{
dir = dir.WithTwoNeighbors.Where (d => CanMove (d)).First ()
Move (dir);
}
</code></pre>
<p>This turned out to be quite handy and made a lot of things much less complicated.</p>
| 6 | 2009-01-01T22:21:42Z | [
"python",
"data-structures",
"recursion",
"cyclic-reference"
] |
What is a cyclic data structure good for? | 405,540 | <p>I was just reading through <a href="http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false" rel="nofollow">"Learning Python" by Mark Lutz and came across this code sample</a>:</p>
<pre><code>
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
</code></pre>
<p>It was identified as a cyclic data structure.</p>
<p>So I was wondering, and here is my question:</p>
<h2><strong>What is a 'cyclic data structure' used for in real life programming?</strong></h2>
<p>There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L</p>
<pre><code>
>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'
</code></pre>
| 13 | 2009-01-01T22:06:09Z | 405,592 | <p>Suppose you have limited storage, and data constantly accumulates. In many real life cases, you don't mind getting rid of old data, but you don't want to move data. You can use a cyclic vector; implemented using a vector v of size N with two special indices: begin and end, which initiate on 0.</p>
<p>Insertion of "new" data now goes like this:</p>
<pre><code>v[end] = a;
end = (end+1) % N;
if (begin == end)
begin = (begin+1) % N;
</code></pre>
<p>You can insert "old" data and erase "old" or "new" data in a similar way.
Scanning the vector goes like this</p>
<pre><code>for (i=begin; i != end; i = (i+1) % N) {
// do stuff
}
</code></pre>
| 0 | 2009-01-01T22:37:49Z | [
"python",
"data-structures",
"recursion",
"cyclic-reference"
] |
What is a cyclic data structure good for? | 405,540 | <p>I was just reading through <a href="http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false" rel="nofollow">"Learning Python" by Mark Lutz and came across this code sample</a>:</p>
<pre><code>
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
</code></pre>
<p>It was identified as a cyclic data structure.</p>
<p>So I was wondering, and here is my question:</p>
<h2><strong>What is a 'cyclic data structure' used for in real life programming?</strong></h2>
<p>There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L</p>
<pre><code>
>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'
</code></pre>
| 13 | 2009-01-01T22:06:09Z | 918,091 | <p>Cyclic data structures are usually used to represent circular relationships. That sounds obvious, but it happens more than you think. I can't think of any times I've used terribly complicated cyclical data structures, but bidirectional relationships are fairly common. For example, suppose I wanted to make an IM client. I could do something like this:</p>
<pre><code>class Client(object):
def set_remote(self, remote_client):
self.remote_client = remote_client
def send(self, msg):
self.remote_client.receive(msg)
def receive(self, msg):
print msg
Jill = Client()
Bob = Client()
Bob.set_remote(Jill)
Jill.set_remote(Bob)
</code></pre>
<p>Then if Bob wanted to send a message to Jill, you could just do this:</p>
<pre><code>Bob.send("Hi, Jill!")
</code></pre>
<p>Of course, Jill may want to send a message back, so she could do this:</p>
<pre><code>Jill.send("Hi, Bob!")
</code></pre>
<p>Admittedly, this is a bit of a contrived example, but it should give you an example of when you may want to use a cyclical data structure.</p>
| 0 | 2009-05-27T21:27:11Z | [
"python",
"data-structures",
"recursion",
"cyclic-reference"
] |
What is a cyclic data structure good for? | 405,540 | <p>I was just reading through <a href="http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false" rel="nofollow">"Learning Python" by Mark Lutz and came across this code sample</a>:</p>
<pre><code>
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
</code></pre>
<p>It was identified as a cyclic data structure.</p>
<p>So I was wondering, and here is my question:</p>
<h2><strong>What is a 'cyclic data structure' used for in real life programming?</strong></h2>
<p>There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L</p>
<pre><code>
>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'
</code></pre>
| 13 | 2009-01-01T22:06:09Z | 918,114 | <p>Any kind of object hierarchy where parents know about their children and children know about their parents. I'm always having to deal with this in ORMs because I want databases to know their tables and tables to know what database they're a part of, and so on.</p>
| 0 | 2009-05-27T21:32:23Z | [
"python",
"data-structures",
"recursion",
"cyclic-reference"
] |
What is a cyclic data structure good for? | 405,540 | <p>I was just reading through <a href="http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false" rel="nofollow">"Learning Python" by Mark Lutz and came across this code sample</a>:</p>
<pre><code>
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
</code></pre>
<p>It was identified as a cyclic data structure.</p>
<p>So I was wondering, and here is my question:</p>
<h2><strong>What is a 'cyclic data structure' used for in real life programming?</strong></h2>
<p>There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L</p>
<pre><code>
>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'
</code></pre>
| 13 | 2009-01-01T22:06:09Z | 918,223 | <p>It is a bit confusing since it is a list that contains itself, but the way I made sense of it is to not think of L as a list, but a node, and instead of things in a list, you think of it as other nodes reachable by this node.</p>
<p>To put a more real world example, think of them as flight paths from a city.</p>
<p>So chicago = [denver, los angeles, new york city, chicago] (realistically you wouldn't list chicago in itself, but for the sake of example you can reach chicago from chicago)</p>
<p>Then you have denver = [phoenix, philedelphia] and so on.</p>
<p>phoenix = [chicago, new york city]</p>
<p>Now you have cyclic data both from </p>
<blockquote>
<p>chicago -> chicago</p>
</blockquote>
<p>but also </p>
<blockquote>
<p>chicago -> denver -> phoenix -> chicago</p>
</blockquote>
<p>Now you have:</p>
<pre><code>chicago[0] == denver
chicago[0][0] == phoenix
chicago[0][0][0] == chicago
</code></pre>
| 1 | 2009-05-27T21:58:11Z | [
"python",
"data-structures",
"recursion",
"cyclic-reference"
] |
What is a cyclic data structure good for? | 405,540 | <p>I was just reading through <a href="http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false" rel="nofollow">"Learning Python" by Mark Lutz and came across this code sample</a>:</p>
<pre><code>
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
</code></pre>
<p>It was identified as a cyclic data structure.</p>
<p>So I was wondering, and here is my question:</p>
<h2><strong>What is a 'cyclic data structure' used for in real life programming?</strong></h2>
<p>There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L</p>
<pre><code>
>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'
</code></pre>
| 13 | 2009-01-01T22:06:09Z | 918,340 | <p><code>L</code> just contains a reference to itself as one of it's elements. Nothing really special about this. </p>
<p>There are some obvious uses of cyclical structures where the last element knows about the first element. But this functionality is already covered by regular python lists.</p>
<p>You can get the last element of <code>L</code> by using <code>[-1]</code>. You can use python lists as queues with <code>append()</code> and <code>pop()</code>. You can split python lists. Which are the regular uses of a cyclical data structure.</p>
<pre><code>>>> L = ['foo', 'bar']
>>> L.append(L)
>>> L
['foo', 'bar', [...]]
>>> L[0]
'foo'
>>> L[1]
'bar'
>>> L[2]
['foo', 'bar', [...]]
>>> L[2].append('baz')
>>> L
['foo', 'bar', [...], 'baz']
>>> L[2]
['foo', 'bar', [...], 'baz']
>>> L[2].pop()
'baz'
>>> L
['foo', 'bar', [...]]
>>> L[2]
['foo', 'bar', [...]]
</code></pre>
| 1 | 2009-05-27T22:38:53Z | [
"python",
"data-structures",
"recursion",
"cyclic-reference"
] |
What is a cyclic data structure good for? | 405,540 | <p>I was just reading through <a href="http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false" rel="nofollow">"Learning Python" by Mark Lutz and came across this code sample</a>:</p>
<pre><code>
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
</code></pre>
<p>It was identified as a cyclic data structure.</p>
<p>So I was wondering, and here is my question:</p>
<h2><strong>What is a 'cyclic data structure' used for in real life programming?</strong></h2>
<p>There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L</p>
<pre><code>
>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'
</code></pre>
| 13 | 2009-01-01T22:06:09Z | 918,508 | <p>The data structures iterated by <a href="http://en.wikipedia.org/wiki/Deterministic%5FFinite%5FAutomaton" rel="nofollow">deterministic finite automata</a> are often cyclical.</p>
| 1 | 2009-05-27T23:35:20Z | [
"python",
"data-structures",
"recursion",
"cyclic-reference"
] |
What is a cyclic data structure good for? | 405,540 | <p>I was just reading through <a href="http://books.google.com/books?id=1HxWGezDZcgC&lpg=PP1&dq=learning%20python&pg=PA254#v=onepage&q=cyclic&f=false" rel="nofollow">"Learning Python" by Mark Lutz and came across this code sample</a>:</p>
<pre><code>
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
</code></pre>
<p>It was identified as a cyclic data structure.</p>
<p>So I was wondering, and here is my question:</p>
<h2><strong>What is a 'cyclic data structure' used for in real life programming?</strong></h2>
<p>There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L</p>
<pre><code>
>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'
</code></pre>
| 13 | 2009-01-01T22:06:09Z | 919,535 | <p>Let's look at a single practical example.</p>
<p>Let us say we're programming a menu navigation for a game. We want to store for each menu-item</p>
<ol>
<li>The entry's name</li>
<li>The other menu we'll reach after pressing it.</li>
<li>The action that would be performed when pressing the menu.</li>
</ol>
<p>When a menu-item is pressed, we'll activate the menu-item action and then move to the next menu. So our menu would be a simple list of dictionaries, like so:</p>
<pre><code>options,start_menu,about = [],[],[]
def do_nothing(): pass
about += [
{'name':"copyright by...",'action':None,'menu':about},
{'name':"back",'action':do_nothing,'menu':start_menu}
]
options += [
{'name':"volume up",'action':volumeUp,'menu':options},
{'name':"save",'action':save,'menu':start_menu},
{'name':"back without save",'action':do_nothing,'menu':start_menu}
]
start_menu += [
{'name':"Exit",'action':f,'menu':None}, # no next menu since we quite
{'name':"Options",'action':do_nothing,'menu':options},
{'name':"About",'action':do_nothing,'menu':about}
]
</code></pre>
<p>See how <code>about</code> is cyclic:</p>
<pre><code>>>> print about
[{'action': None, 'menu': [...], 'name': 'copyright by...'},#etc.
# see the ellipsis (...)
</code></pre>
<p>When a menu item is pressed we'll issue the following on-click function:</p>
<pre><code>def menu_item_pressed(item):
log("menu item '%s' pressed" % item['name'])
item['action']()
set_next_menu(item['menu'])
</code></pre>
<p>Now, if we wouldn't have cyclic data structures, we wouldn't be able to have a menu item that points to itself, and, for instance, after pressing the volume-up function we would have to leave the options menu.</p>
<p>If cyclic data structures wouldn't be possible, we'll have to implement it ourselves, for example the menu item would be:</p>
<pre><code>class SelfReferenceMarkerClass: pass
#singleton global marker for self reference
SelfReferenceMarker = SelfReferenceMarkerClass()
about += [
{'name':"copyright by...",'action':None,'menu':srm},
{'name':"back",'action':do_nothing,'menu':start_menu}
]
</code></pre>
<p>the <code>menu_item_pressed</code> function would be:</p>
<pre><code>def menu_item_pressed(item):
item['action']()
if (item['menu'] == SelfReferenceMarker):
set_next_menu(get_previous_menu())
else:
set_next_menu(item['menu'])
</code></pre>
<p>The first example is a little bit nicer, but yes, not supporting self references is not such a big deal IMHO, as it's easy to overcome this limitation.</p>
<p>The menus example is like a graph with self references, where we store the graph by lists of vertex pointers (every vertex is a list of pointers to other vertices). In this example we needed self edges (a vertex that points to itself), thus python's support for cyclic data structures is useful.</p>
| 0 | 2009-05-28T07:00:04Z | [
"python",
"data-structures",
"recursion",
"cyclic-reference"
] |
Function and class documentation best practices for Python | 405,582 | <p>I am looking for best practices for function/class/module documentation, i.e. comments in the code itself. Ideally I would like a comment template which is both human readable and consumable by Python documentation utilities.</p>
<p>I have read the <a href="http://docs.python.org/tutorial/controlflow.html">Python documentation on docstrings</a>.</p>
<p>I understand this part:</p>
<blockquote>
<p>The first line should always be a short, concise summary of the objectâs purpose. For brevity, it should not explicitly state the objectâs name or type, since these are available by other means (except if the name happens to be a verb describing a functionâs operation). This line should begin with a capital letter and end with a period.</p>
<p>If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.</p>
</blockquote>
<p>This sentence needs a bit more explanation:</p>
<blockquote>
<p>The following lines should be one or more paragraphs describing the objectâs calling conventions, its side effects, etc.</p>
</blockquote>
<p>Specifically, I am looking for examples of well-commented functions and classes.</p>
| 68 | 2009-01-01T22:30:39Z | 405,624 | <p>I think the best resource will be <a href="http://docs.python.org/documenting/index.html">Documenting Python</a></p>
<p>Quote:</p>
<p><code>This document describes the style guide for our documentation, the custom reStructuredText markup introduced to support Python documentation and how it should be used, as well as the Sphinx build system.</code></p>
<p><a href="http://sphinx.pocoo.org/">Sphinx</a>: The official Python documentation generator</p>
| 5 | 2009-01-01T22:56:09Z | [
"python",
"documentation",
"coding-style"
] |
Function and class documentation best practices for Python | 405,582 | <p>I am looking for best practices for function/class/module documentation, i.e. comments in the code itself. Ideally I would like a comment template which is both human readable and consumable by Python documentation utilities.</p>
<p>I have read the <a href="http://docs.python.org/tutorial/controlflow.html">Python documentation on docstrings</a>.</p>
<p>I understand this part:</p>
<blockquote>
<p>The first line should always be a short, concise summary of the objectâs purpose. For brevity, it should not explicitly state the objectâs name or type, since these are available by other means (except if the name happens to be a verb describing a functionâs operation). This line should begin with a capital letter and end with a period.</p>
<p>If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.</p>
</blockquote>
<p>This sentence needs a bit more explanation:</p>
<blockquote>
<p>The following lines should be one or more paragraphs describing the objectâs calling conventions, its side effects, etc.</p>
</blockquote>
<p>Specifically, I am looking for examples of well-commented functions and classes.</p>
| 68 | 2009-01-01T22:30:39Z | 405,663 | <p>The best way to learn documentation practices is probably to look at the source code of a well known project. Like the <a href="http://www.djangoproject.com/" rel="nofollow">Djangoproject</a>.</p>
| 2 | 2009-01-01T23:16:43Z | [
"python",
"documentation",
"coding-style"
] |
Function and class documentation best practices for Python | 405,582 | <p>I am looking for best practices for function/class/module documentation, i.e. comments in the code itself. Ideally I would like a comment template which is both human readable and consumable by Python documentation utilities.</p>
<p>I have read the <a href="http://docs.python.org/tutorial/controlflow.html">Python documentation on docstrings</a>.</p>
<p>I understand this part:</p>
<blockquote>
<p>The first line should always be a short, concise summary of the objectâs purpose. For brevity, it should not explicitly state the objectâs name or type, since these are available by other means (except if the name happens to be a verb describing a functionâs operation). This line should begin with a capital letter and end with a period.</p>
<p>If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.</p>
</blockquote>
<p>This sentence needs a bit more explanation:</p>
<blockquote>
<p>The following lines should be one or more paragraphs describing the objectâs calling conventions, its side effects, etc.</p>
</blockquote>
<p>Specifically, I am looking for examples of well-commented functions and classes.</p>
| 68 | 2009-01-01T22:30:39Z | 405,710 | <p>You should <a href="http://www.python.org/dev/peps/pep-0287/">use reStructuredText</a> and check out the <a href="http://sphinx.pocoo.org/markup/index.html">Sphinx markup constructs</a>. All the cool kids are doing it.</p>
<p>You should <a href="http://www.python.org/dev/peps/pep-0257/">follow docstring conventions</a>. i.e.</p>
<blockquote>
<p>It prescribes the function or method's
effect as a command ("Do this",
"Return that").</p>
</blockquote>
<p>You should avoid repeating yourself unnecessarily or explaining the eminently obvious. Example of what not to do:</p>
<pre><code>def do_things(verbose=False):
"""Do some things.
:param verbose: Be verbose (give additional messages).
"""
raise NotImplementedError
</code></pre>
<p>If you wanted to describe something non-obvious it would be a different story; for example, that verbose causes messages to occur on <code>stdout</code> or a <code>logging</code> stream. This is not specific to Python, but follows from more hand-wavy ideals such as <a href="http://en.wikipedia.org/wiki/Self-documenting">self-documenting code</a> and <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">code/documentation DRY</a>.</p>
<p>Try to avoid mentioning specific types if possible (abstract or interface-like types are generally okay). Mentioning <em>protocols</em> is typically more helpful from a duck typing perspective (i.e. "iterable" instead of <code>set</code>, or "mutable ordered sequence" instead of <code>list</code>). I've seen some code that is very literal and heavy WRT the <code>:rtype:</code> and the <code>:type param:</code> function-level documentation, which I've found to be at odds with the duck typing mentality.</p>
| 45 | 2009-01-01T23:54:52Z | [
"python",
"documentation",
"coding-style"
] |
Function and class documentation best practices for Python | 405,582 | <p>I am looking for best practices for function/class/module documentation, i.e. comments in the code itself. Ideally I would like a comment template which is both human readable and consumable by Python documentation utilities.</p>
<p>I have read the <a href="http://docs.python.org/tutorial/controlflow.html">Python documentation on docstrings</a>.</p>
<p>I understand this part:</p>
<blockquote>
<p>The first line should always be a short, concise summary of the objectâs purpose. For brevity, it should not explicitly state the objectâs name or type, since these are available by other means (except if the name happens to be a verb describing a functionâs operation). This line should begin with a capital letter and end with a period.</p>
<p>If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.</p>
</blockquote>
<p>This sentence needs a bit more explanation:</p>
<blockquote>
<p>The following lines should be one or more paragraphs describing the objectâs calling conventions, its side effects, etc.</p>
</blockquote>
<p>Specifically, I am looking for examples of well-commented functions and classes.</p>
| 68 | 2009-01-01T22:30:39Z | 406,346 | <p>As Emji said, Django is a good project to follow for clear, consistent style guides.</p>
<p>For example, their <a href="http://docs.djangoproject.com/en/dev/internals/contributing/?from=olddocs#coding-style">Contribute to Django style guide</a> even goes as far as describing how they'd like to see documentation. Specifically they mention:</p>
<p><em>In docstrings, use âaction wordsâ such as:</em></p>
<pre><code>def foo():
"""
Calculates something and returns the result.
"""
pass
</code></pre>
<p><em>Here's an example of what not to do:</em></p>
<pre><code>def foo():
"""
Calculate something and return the result.
"""
pass
</code></pre>
| 8 | 2009-01-02T09:05:02Z | [
"python",
"documentation",
"coding-style"
] |
Accepting File Argument in Python (from Send To context menu) | 405,612 | <p>I'm going to start of by noting that I have next to no python experience.</p>
<p><img src="http://www.aquate.us/u/9986423875612301299.jpg" alt="alt text" /></p>
<p>As you may know, by simply dropping a shortcut in the Send To folder on your Windows PC, you can allow a program to take a file as an argument.</p>
<p>How would I write a python program that takes this file as an argument? </p>
<p>And, as a bonus if anyone gets a chance --
How would I integrate that with a urllib2 to POST the file to a PHP script on my server?</p>
<p>Thanks in advance.</p>
<p>Edit-- also, how do I make something show up in the Sendto menu? I was under the impression that you just drop a shortcut into the SendTo folder and it automatically adds an option in the menu...
Never mind. I figured out what I was doing wrong :)</p>
| 3 | 2009-01-01T22:50:42Z | 405,625 | <pre><code>import sys
for arg in sys.argv:
print arg
</code></pre>
| 1 | 2009-01-01T22:56:55Z | [
"python",
"urllib2",
"contextmenu",
"sendto"
] |
Accepting File Argument in Python (from Send To context menu) | 405,612 | <p>I'm going to start of by noting that I have next to no python experience.</p>
<p><img src="http://www.aquate.us/u/9986423875612301299.jpg" alt="alt text" /></p>
<p>As you may know, by simply dropping a shortcut in the Send To folder on your Windows PC, you can allow a program to take a file as an argument.</p>
<p>How would I write a python program that takes this file as an argument? </p>
<p>And, as a bonus if anyone gets a chance --
How would I integrate that with a urllib2 to POST the file to a PHP script on my server?</p>
<p>Thanks in advance.</p>
<p>Edit-- also, how do I make something show up in the Sendto menu? I was under the impression that you just drop a shortcut into the SendTo folder and it automatically adds an option in the menu...
Never mind. I figured out what I was doing wrong :)</p>
| 3 | 2009-01-01T22:50:42Z | 405,629 | <ol>
<li>Find out what the dragged file was: <a href="http://docs.python.org/library/sys.html#sys.argv">http://docs.python.org/library/sys.html#sys.argv</a></li>
<li>Open it: <a href="http://docs.python.org/library/functions.html#open">http://docs.python.org/library/functions.html#open</a></li>
<li>Read it in: <a href="http://docs.python.org/library/stdtypes.html#file.read">http://docs.python.org/library/stdtypes.html#file.read</a></li>
<li>Post it: <a href="http://docs.python.org/library/urllib2.html#urllib2.urlopen">http://docs.python.org/library/urllib2.html#urllib2.urlopen</a></li>
</ol>
| 7 | 2009-01-01T22:57:47Z | [
"python",
"urllib2",
"contextmenu",
"sendto"
] |
insert two values from an mysql table into another table using a python program | 405,617 | <p>I'm having a small problem with a Python program (below) that I'm writing. </p>
<p>I want to insert two values from a MySQL table into another table from a Python program.</p>
<p>The two fields are priority and product and I have selected them from the shop table and I want to insert them into the products table. </p>
<p>Can anyone help? Thanks a lot. Marc.</p>
<pre><code>import MySQLdb
def checkOut():
db = MySQLdb.connect(host='localhost', user = 'root', passwd = '$$', db = 'fillmyfridge')
cursor = db.cursor(MySQLdb.cursors.DictCursor)
user_input = raw_input('please enter the product barcode that you are taking out of the fridge: \n')
cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1 where barcode = %s', (user_input))
db.commit()
cursor.execute('select product, priority from shop where barcode = %s', (user_input))
rows = cursor.fetchall()
cursor.execute('insert into products(product, barcode, priority) values (%s, %s)', (rows["product"], user_input, rows["priority"]))
db.commit()
print 'the following product has been removed from the fridge and needs to be ordered'
</code></pre>
| -2 | 2009-01-01T22:54:43Z | 405,668 | <p>Well, the same thing again:</p>
<pre><code>import MySQLdb
def checkOut():
db = MySQLdb.connect(host='localhost', user = 'root', passwd = '$$', db = 'fillmyfridge')
cursor = db.cursor(MySQLdb.cursors.DictCursor)
user_input = raw_input('please enter the product barcode that you are taking out of the fridge: \n')
cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1 where barcode = %s', (user_input))
db.commit()
cursor.execute('select product, priority from shop where barcode = %s', (user_input))
rows = cursor.fetchall()
</code></pre>
<ol>
<li><p>Do you need fetchall()?? Barcode's are unique I guess and one barcode is to one product I guess. So, fetchone() is enough....isn't it??</p></li>
<li><p>In any case if you do a fetchall() its a result set not a single result.
So <code>rows["product"]</code> is not valid.
It has to be</p>
<pre><code>for row in rows:
cursor.execute('insert into products(product, barcode, priority) values (%s, %s, %s)', (row["product"], user_input, row["priority"]))
db.commit()
print 'the following product has been removed from the fridge and needs to be ordered'
</code></pre></li>
</ol>
<p>or better</p>
<pre><code>import MySQLdb
def checkOut():
db = MySQLdb.connect(host='localhost', user = 'root', passwd = '$$', db = 'fillmyfridge')
cursor = db.cursor(MySQLdb.cursors.DictCursor)
user_input = raw_input('please enter the product barcode that you are taking out of the fridge: \n')
cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1 where barcode = %s', (user_input))
cursor.execute('insert into products(product, barcode, priority) select product, barcode, priority from shop where barcode = %s', (user_input))
db.commit()
</code></pre>
<p><strong>Edit:</strong> Also, you use <code>db.commit()</code> almost like <code>print</code> - anywhere, you need to read and understand the <a href="http://en.wikipedia.org/wiki/Atomicity_(database_systems)" rel="nofollow">atomicity</a> principle for databases</p>
| 1 | 2009-01-01T23:21:40Z | [
"python",
"mysql",
"database"
] |
insert two values from an mysql table into another table using a python program | 405,617 | <p>I'm having a small problem with a Python program (below) that I'm writing. </p>
<p>I want to insert two values from a MySQL table into another table from a Python program.</p>
<p>The two fields are priority and product and I have selected them from the shop table and I want to insert them into the products table. </p>
<p>Can anyone help? Thanks a lot. Marc.</p>
<pre><code>import MySQLdb
def checkOut():
db = MySQLdb.connect(host='localhost', user = 'root', passwd = '$$', db = 'fillmyfridge')
cursor = db.cursor(MySQLdb.cursors.DictCursor)
user_input = raw_input('please enter the product barcode that you are taking out of the fridge: \n')
cursor.execute('update shops set instock=0, howmanytoorder = howmanytoorder + 1 where barcode = %s', (user_input))
db.commit()
cursor.execute('select product, priority from shop where barcode = %s', (user_input))
rows = cursor.fetchall()
cursor.execute('insert into products(product, barcode, priority) values (%s, %s)', (rows["product"], user_input, rows["priority"]))
db.commit()
print 'the following product has been removed from the fridge and needs to be ordered'
</code></pre>
| -2 | 2009-01-01T22:54:43Z | 405,672 | <p>You don't mention what the problem is, but in the code you show this:</p>
<pre><code>cursor.execute('insert into products(product, barcode, priority) values (%s, %s)', (rows["product"], user_input, rows["priority"]))
</code></pre>
<p>where your values clause only has two %s's in it, where it should have three:</p>
<pre><code>cursor.execute('insert into products(product, barcode, priority) values (%s, %s, %s)', (rows["product"], user_input, rows["priority"]))
</code></pre>
| 1 | 2009-01-01T23:22:56Z | [
"python",
"mysql",
"database"
] |
Passing arguments with wildcards to a Python script | 405,652 | <p>I want to do something like this:</p>
<pre><code>c:\data\> python myscript.py *.csv
</code></pre>
<p>and pass all of the .csv files in the directory to my python script (such that <code>sys.argv</code> contains <code>["file1.csv", "file2.csv"]</code>, etc.) </p>
<p>But <code>sys.argv</code> just receives <code>["*.csv"]</code> indicating that the wildcard was not expanded, so this doesn't work.</p>
<p>I feel like there is a simple way to do this, but can't find it on Google. Any ideas?</p>
| 12 | 2009-01-01T23:08:01Z | 405,662 | <p>You can use the glob module, that way you won't depend on the behavior of a particular shell (well, you still depend on the shell not expanding the arguments, but at least you can get this to happen in Unix by escaping the wildcards :-) ).</p>
<pre><code>from glob import glob
filelist = glob('*.csv') #You can pass the sys.argv argument
</code></pre>
| 20 | 2009-01-01T23:15:46Z | [
"python",
"windows",
"command-line",
"arguments"
] |
Passing arguments with wildcards to a Python script | 405,652 | <p>I want to do something like this:</p>
<pre><code>c:\data\> python myscript.py *.csv
</code></pre>
<p>and pass all of the .csv files in the directory to my python script (such that <code>sys.argv</code> contains <code>["file1.csv", "file2.csv"]</code>, etc.) </p>
<p>But <code>sys.argv</code> just receives <code>["*.csv"]</code> indicating that the wildcard was not expanded, so this doesn't work.</p>
<p>I feel like there is a simple way to do this, but can't find it on Google. Any ideas?</p>
| 12 | 2009-01-01T23:08:01Z | 405,667 | <p>In Unix, the shell expands wildcards, so programs get the expanded list of filenames. Windows doesn't do this: the shell passes the wildcards directly to the program, which has to expand them itself.</p>
<p>Vinko is right: the glob module does the job:</p>
<pre><code>import glob, sys
for arg in glob.glob(sys.argv[1]):
print "Arg:", arg
</code></pre>
| 11 | 2009-01-01T23:19:50Z | [
"python",
"windows",
"command-line",
"arguments"
] |
Modifying Microsoft Outlook contacts from Python | 405,724 | <p>I have written a few Python tools in the past to extract data from my Outlook contacts. Now, I am trying to <em>modify</em> my Outlook Contacts. I am finding that my changes are being noted by Outlook, but they aren't sticking. I seem to be updating some cache, but not the real record.</p>
<p>The code is straightforward.</p>
<pre><code>import win32com.client
import pywintypes
o = win32com.client.Dispatch("Outlook.Application")
ns = o.GetNamespace("MAPI")
profile = ns.Folders.Item("My Profile Name")
contacts = profile.Folders.Item("Contacts")
contact = contacts.Items[43] # Grab a random contact, for this example.
print "About to overwrite ",contact.FirstName, contact.LastName
contact.categories = 'Supplier' # Override the categories
# Edit: I don't always do these last steps.
ns = None
o = None
</code></pre>
<p>At this point, I change over to Outlook, which is opened to the Detailed Address Cards view. </p>
<p>I look at the contact summary (without opening it) and the category is unchanged (not refreshed?). </p>
<p>I open the contact and its category HAS changed, <em>sometimes</em>. (Not sure of when, but it feels like it is cache related.) If it has changed, it prompts me to Save Changes when I close it which is odd, because I haven't changed anything in the Outlook UI.</p>
<p>If I quit and restart Outlook, the changes are gone.</p>
<p>I <em>suspect</em> I am failing to call <a href="http://msdn.microsoft.com/en-us/library/cc842181.aspx">SaveChanges</a>, but I can't see which object supports it.</p>
<p>So my question is:</p>
<ul>
<li>Should I be calling SaveChanges? If so, where is it?</li>
<li>Am I making some other silly mistake, which is causing my data to be discarded?</li>
</ul>
| 9 | 2009-01-02T00:11:57Z | 405,758 | <p>I believe there is a .Save() method on the contact, so you need to add:</p>
<p>contact.Save()</p>
| 6 | 2009-01-02T00:44:33Z | [
"python",
"winapi",
"outlook",
"mapi"
] |
Floating Point Limitations | 406,361 | <p>My code:</p>
<pre><code>a = '2.3'
</code></pre>
<p>I wanted to display <code>a</code> as a floating point value.</p>
<p>Since <code>a</code> is a string, I tried:</p>
<pre><code>float(a)
</code></pre>
<p>The result I got was :</p>
<pre><code>2.2999999999999998
</code></pre>
<p>I want a solution for this problem. Please, kindly help me.</p>
<p>I was following <a href="http://docs.python.org/tutorial/floatingpoint.html">this tutorial</a>.</p>
| 4 | 2009-01-02T09:17:26Z | 406,367 | <p>I think it reflects more on your understanding of floating point types than on Python. See <a href="http://csharpindepth.com/Articles/General/FloatingPoint.aspx" rel="nofollow">my article about floating point numbers</a> (.NET-based, but still relevant) for the reasons behind this "inaccuracy". If you need to keep the exact decimal representation, you should use the <a href="http://docs.python.org/library/decimal.html" rel="nofollow">decimal module</a>.</p>
| 18 | 2009-01-02T09:22:15Z | [
"python",
"floating-point",
"precision",
"floating-accuracy"
] |
Floating Point Limitations | 406,361 | <p>My code:</p>
<pre><code>a = '2.3'
</code></pre>
<p>I wanted to display <code>a</code> as a floating point value.</p>
<p>Since <code>a</code> is a string, I tried:</p>
<pre><code>float(a)
</code></pre>
<p>The result I got was :</p>
<pre><code>2.2999999999999998
</code></pre>
<p>I want a solution for this problem. Please, kindly help me.</p>
<p>I was following <a href="http://docs.python.org/tutorial/floatingpoint.html">this tutorial</a>.</p>
| 4 | 2009-01-02T09:17:26Z | 406,373 | <p>This is not a drawback of python, rather, it is a drawback of the way floating point numbers are stored on a computer. Regardless of implementation language, you will find similar problems.</p>
<p>You say that you want to 'display' A as a floating point, why not just display the string? Visually it will be identical to what you expect.</p>
<p>As Jon mentioned, if your needs are more than just 'displaying' the floating point number, you should use the decimal module to store the exact representation.</p>
| 6 | 2009-01-02T09:27:15Z | [
"python",
"floating-point",
"precision",
"floating-accuracy"
] |
Floating Point Limitations | 406,361 | <p>My code:</p>
<pre><code>a = '2.3'
</code></pre>
<p>I wanted to display <code>a</code> as a floating point value.</p>
<p>Since <code>a</code> is a string, I tried:</p>
<pre><code>float(a)
</code></pre>
<p>The result I got was :</p>
<pre><code>2.2999999999999998
</code></pre>
<p>I want a solution for this problem. Please, kindly help me.</p>
<p>I was following <a href="http://docs.python.org/tutorial/floatingpoint.html">this tutorial</a>.</p>
| 4 | 2009-01-02T09:17:26Z | 407,366 | <p>Excellent answers explaining reasons. I just wish to add a possible practical solution from the standard library:</p>
<pre><code>>>> from decimal import Decimal
>>> a = Decimal('2.3')
>>> print a
2.3
</code></pre>
<p>This is actually a (very) F.A.Q. for Python and you can <a href="http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate" rel="nofollow">read the answer here</a>.</p>
<p><hr />
Edit: I just noticed that John Skeet already mentioned this. Oh well...</p>
| 4 | 2009-01-02T16:43:44Z | [
"python",
"floating-point",
"precision",
"floating-accuracy"
] |
Why does Ruby have Rails while Python has no central framework? | 406,907 | <p>This is a(n) historical question, not a comparison-between-languages question:</p>
<p><a href="http://tomayko.com/writings/no-rails-for-python">This article from 2005</a> talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. <strong>Why, historically speaking, did this happen for Ruby but not for Python?</strong> (or did it happen, and that framework is Django?)</p>
<p>Also, the hypothetical questions: <strong>would Python be more popular if it had one, good framework? Would Ruby be less popular if it had no central framework?</strong></p>
<p><strong>[Please avoid discussions of whether Ruby or Python is better, which is just too open-ended to answer.]</strong></p>
<p><strong>Edit:</strong> Though I thought this is obvious, I'm not saying that other frameworks do not exist for Ruby, but rather that the big one <strong>in terms of popularity</strong> is Rails. Also, I should mention that I'm not saying that frameworks for Python are not as good (or better than) Rails. Every framework has its pros and cons, but Rails seems to, as Ben Blank says in the one of the comments below, have surpassed Ruby in terms of popularity. There are no examples of that on the Python side. WHY? That's the question.</p>
| 8 | 2009-01-02T14:26:57Z | 406,925 | <p>I don't think it's right to characterise Rails as 'the' 'single' 'central' Ruby framework.</p>
<p>Other frameworks for Ruby include Merb, Camping and Ramaze.</p>
<p>... which sort of invalidates the question.</p>
| 7 | 2009-01-02T14:33:24Z | [
"python",
"ruby-on-rails",
"ruby",
"frameworks",
"history"
] |
Why does Ruby have Rails while Python has no central framework? | 406,907 | <p>This is a(n) historical question, not a comparison-between-languages question:</p>
<p><a href="http://tomayko.com/writings/no-rails-for-python">This article from 2005</a> talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. <strong>Why, historically speaking, did this happen for Ruby but not for Python?</strong> (or did it happen, and that framework is Django?)</p>
<p>Also, the hypothetical questions: <strong>would Python be more popular if it had one, good framework? Would Ruby be less popular if it had no central framework?</strong></p>
<p><strong>[Please avoid discussions of whether Ruby or Python is better, which is just too open-ended to answer.]</strong></p>
<p><strong>Edit:</strong> Though I thought this is obvious, I'm not saying that other frameworks do not exist for Ruby, but rather that the big one <strong>in terms of popularity</strong> is Rails. Also, I should mention that I'm not saying that frameworks for Python are not as good (or better than) Rails. Every framework has its pros and cons, but Rails seems to, as Ben Blank says in the one of the comments below, have surpassed Ruby in terms of popularity. There are no examples of that on the Python side. WHY? That's the question.</p>
| 8 | 2009-01-02T14:26:57Z | 406,940 | <p>Rails was somewhat revolutionary in its extreme "convention over configuration" approach which set it apart from pretty much anything else and made it the "killer app" of Ruby, causing a lot of people to notice Ruby in the first place. </p>
<p>So the question is really "Why did David Hansson decide to write Rails in Ruby rather than Python?"</p>
| 5 | 2009-01-02T14:39:57Z | [
"python",
"ruby-on-rails",
"ruby",
"frameworks",
"history"
] |
Why does Ruby have Rails while Python has no central framework? | 406,907 | <p>This is a(n) historical question, not a comparison-between-languages question:</p>
<p><a href="http://tomayko.com/writings/no-rails-for-python">This article from 2005</a> talks about the lack of a single, central framework for Python. For Ruby, this framework is clearly Rails. <strong>Why, historically speaking, did this happen for Ruby but not for Python?</strong> (or did it happen, and that framework is Django?)</p>
<p>Also, the hypothetical questions: <strong>would Python be more popular if it had one, good framework? Would Ruby be less popular if it had no central framework?</strong></p>
<p><strong>[Please avoid discussions of whether Ruby or Python is better, which is just too open-ended to answer.]</strong></p>
<p><strong>Edit:</strong> Though I thought this is obvious, I'm not saying that other frameworks do not exist for Ruby, but rather that the big one <strong>in terms of popularity</strong> is Rails. Also, I should mention that I'm not saying that frameworks for Python are not as good (or better than) Rails. Every framework has its pros and cons, but Rails seems to, as Ben Blank says in the one of the comments below, have surpassed Ruby in terms of popularity. There are no examples of that on the Python side. WHY? That's the question.</p>
| 8 | 2009-01-02T14:26:57Z | 406,949 | <p>Remember that Ruby had existed for a long time before Rails was created. According to Wikipedia, Ruby was created in the mid-90's; Rails didn't come around until 2004. Ruby is simply the language that David Hansson chose to use for Rails.</p>
<p>And yes, I would say <b>Ruby is to Rails as Python is to Django</b>.</p>
| 5 | 2009-01-02T14:43:19Z | [
"python",
"ruby-on-rails",
"ruby",
"frameworks",
"history"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.