title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Why doesn't os.system('set foo=bar') work?
1,506,579
<p>Possibly a stupid question: Why can't I set an environment variable with this?</p> <pre><code>os.system('set foo=bar') # on windows </code></pre> <p>I'm aware of <code>os.environ</code>, and that works for me. I'm just confused about why the former doesn't work. </p>
0
2009-10-01T21:21:19Z
1,506,594
<p>See the discussion <a href="http://stackoverflow.com/questions/1506010/how-to-use-export-with-python-on-linux">here</a> -- <code>export</code> and <code>set</code> are both shell commands, and whether on Windows or Unix, they're still inevitably being addressed to a <strong>child process</strong> running the shell (be it bash, cmd.exe, whatever) and so bereft of any further action when that child process terminates (i.e., when <code>os.system</code> returns to the caller).</p>
11
2009-10-01T21:24:44Z
[ "python", "environment-variables", "environment" ]
Matplotlib square boxplot
1,506,647
<p>I have a plot of two boxplots in the same figure. Due to style reasons, the axis should have the same length, so that the graphic box is squared. I tried to use the set_aspect method, but the axis are too different by means of range and the result is terrific.</p> <p>Is it possible to have 1:1 axis even if they have not the same number of points ?</p> <p>Thanks</p> <p>F.</p>
4
2009-10-01T21:37:37Z
1,506,741
<p>Try <code>axis('equal')</code>. It's been a while since I worked with matplotlib, but I seem to remember typing that command a lot.</p>
4
2009-10-01T21:58:00Z
[ "python", "matplotlib", "square" ]
Matplotlib square boxplot
1,506,647
<p>I have a plot of two boxplots in the same figure. Due to style reasons, the axis should have the same length, so that the graphic box is squared. I tried to use the set_aspect method, but the axis are too different by means of range and the result is terrific.</p> <p>Is it possible to have 1:1 axis even if they have not the same number of points ?</p> <p>Thanks</p> <p>F.</p>
4
2009-10-01T21:37:37Z
1,506,925
<p>You can use <a href="http://matplotlib.sourceforge.net/api/axes%5Fapi.html?highlight=set%5Faspect#matplotlib.axes.Axes.set%5Faspect" rel="nofollow">Axes.set_aspect</a> to do this if you set the aspect to the ratio of axes limits. Here's an example: <img src="http://i37.tinypic.com/b6u9zs.png" alt="alt text" /></p> <pre><code>from matplotlib.pyplot import figure, show fig = figure() ax0 = fig.add_subplot(1,2,1) ax0.set_xlim(10., 10.5) ax0.set_ylim(0, 100.) ax0.set_aspect(.5/100) ax1 = fig.add_subplot(1,2,2) ax1.set_xlim(0., 1007) ax1.set_ylim(0, 12.) x0, x1 = ax1.get_xlim() y0, y1 = ax1.get_ylim() ax1.set_aspect((x1-x0)/(y1-y0)) show() </code></pre> <p>There may be an easier way, but I don't know it.</p>
3
2009-10-01T22:53:40Z
[ "python", "matplotlib", "square" ]
Matplotlib square boxplot
1,506,647
<p>I have a plot of two boxplots in the same figure. Due to style reasons, the axis should have the same length, so that the graphic box is squared. I tried to use the set_aspect method, but the axis are too different by means of range and the result is terrific.</p> <p>Is it possible to have 1:1 axis even if they have not the same number of points ?</p> <p>Thanks</p> <p>F.</p>
4
2009-10-01T21:37:37Z
8,930,451
<p>For loglog plots ( <code>loglog()</code> ) don't forget to use</p> <pre><code>ax1.set_aspect(log10(xmax/xmin)/log10(ymax/ymin)) </code></pre>
1
2012-01-19T17:23:32Z
[ "python", "matplotlib", "square" ]
How to use Sphinx auto-documentation when Python file won't compile
1,506,673
<p>This question is even harder today because I haven't had any luck using the search function on the Sphinx homepage today.</p> <p>I have a group of modules that I want to be documented from the docstrings. However, these are not pure Python scripts. They won't compile as is, because they are run from a C# application that creates a new variable in the executing scope.</p> <p>To the Python compiler, it looks like I have an undefined method (which, technically I do, until C# creates the IronPython script engine and creates the method).</p> <p>When I run:</p> <pre><code>sphinx-build -b html output/html </code></pre> <p>I get:</p> <pre><code>NameError: name 'injected_method' is not defined </code></pre> <p>How do I get Sphinx to ignore compilation errors and just generate my documentation?</p> <p>EDIT:</p> <p>If anybody knows if an alternative to Sphinx (like Epydoc) does not have to compile the Python script to get the function signatures and docstrings, that would be helpful as well. Sphinx is the best looking documentation generator, but I'll abandon it if I have to.</p>
1
2009-10-01T21:41:14Z
1,506,824
<p>Perhaps you could define injected_method as a empty function so that the documentation will work. You'll need to make sure that the definition of injected_method that you're injecting happens after the new injected_method stub.</p> <pre><code>#By empty function I mean a function that looks like this def injected_method(): pass </code></pre>
0
2009-10-01T22:20:24Z
[ "python", "ironpython", "python-sphinx" ]
How to use Sphinx auto-documentation when Python file won't compile
1,506,673
<p>This question is even harder today because I haven't had any luck using the search function on the Sphinx homepage today.</p> <p>I have a group of modules that I want to be documented from the docstrings. However, these are not pure Python scripts. They won't compile as is, because they are run from a C# application that creates a new variable in the executing scope.</p> <p>To the Python compiler, it looks like I have an undefined method (which, technically I do, until C# creates the IronPython script engine and creates the method).</p> <p>When I run:</p> <pre><code>sphinx-build -b html output/html </code></pre> <p>I get:</p> <pre><code>NameError: name 'injected_method' is not defined </code></pre> <p>How do I get Sphinx to ignore compilation errors and just generate my documentation?</p> <p>EDIT:</p> <p>If anybody knows if an alternative to Sphinx (like Epydoc) does not have to compile the Python script to get the function signatures and docstrings, that would be helpful as well. Sphinx is the best looking documentation generator, but I'll abandon it if I have to.</p>
1
2009-10-01T21:41:14Z
1,506,908
<p>Well, you could try:</p> <ul> <li>Wrapping the usage of injected_method in a try/except.</li> <li>Writing a script that filters out all python-code that is run on import time, and feeds the result into Sphinx.</li> <li>You could....ok, I have no more ideas. :)</li> </ul>
3
2009-10-01T22:47:24Z
[ "python", "ironpython", "python-sphinx" ]
How to use Sphinx auto-documentation when Python file won't compile
1,506,673
<p>This question is even harder today because I haven't had any luck using the search function on the Sphinx homepage today.</p> <p>I have a group of modules that I want to be documented from the docstrings. However, these are not pure Python scripts. They won't compile as is, because they are run from a C# application that creates a new variable in the executing scope.</p> <p>To the Python compiler, it looks like I have an undefined method (which, technically I do, until C# creates the IronPython script engine and creates the method).</p> <p>When I run:</p> <pre><code>sphinx-build -b html output/html </code></pre> <p>I get:</p> <pre><code>NameError: name 'injected_method' is not defined </code></pre> <p>How do I get Sphinx to ignore compilation errors and just generate my documentation?</p> <p>EDIT:</p> <p>If anybody knows if an alternative to Sphinx (like Epydoc) does not have to compile the Python script to get the function signatures and docstrings, that would be helpful as well. Sphinx is the best looking documentation generator, but I'll abandon it if I have to.</p>
1
2009-10-01T21:41:14Z
1,510,499
<p>Okay, I found a way to get around the Errors.</p> <p>When setting up the embedded scripting environment, instead of using:</p> <pre><code>ScriptScope.SetVariable("injected_method", myMethod); </code></pre> <p>I am now using:</p> <pre><code>ScriptRuntime.Globals.SetVariable("injected_method", myMethod); </code></pre> <p>And then, in the script:</p> <pre><code>import injected_method </code></pre> <p>Then I created a dummy injected_method.py file in my search path, which is blank. I delete the dummy file during the build of my C# project to avoid any conflicts.</p>
0
2009-10-02T16:10:21Z
[ "python", "ironpython", "python-sphinx" ]
How to arrange the source code of an application made with SQLAlchemy and a graphic interface?
1,506,887
<p>I'm developing an application using SQLAlchemy and wxPython that I'm trying to keep distributed in separated modules consisting of Business logic, ORM and GUI.</p> <p>I'm not completely sure how to do this in a pythonic way.</p> <p>Given that <code>mapping()</code> has to be called in orther for the objects to be used, I thought of putting it on the <code>__init__.py</code> of the bussiness logic, but keeping all the table definitions within a separate <code>orm.py</code> module.</p> <p>Should I keep something like:</p> <pre><code>/Business /__init__.py | mapping (module1.Class1, orm.table1) | /module1.py Class1 /orm.py import table1 = Table() /GUI /main.py | import business /crud.py </code></pre> <p>or something like</p> <pre><code>/Business /__init__.py | import | /module1.py Class1 table1 = Table() mapping (module1.Class1, orm.table1) /GUI /main.py | import business /crud.py </code></pre> <p>Is the first approach recommended? Is there any other option? I've seen the second way, but I don't like putting the database handling code and the bussiness logic code within the same module. Am I overthinking it? Is really not that big a problem?</p>
6
2009-10-01T22:39:03Z
1,509,612
<p>I find <a href="http://jcalderone.livejournal.com/39794.html">this document</a> by Jp Calderone to be a great tip on how to (not) structure your python project. Following it you won't have issues. I'll reproduce the entire text here:</p> <blockquote> <h1>Filesystem structure of a Python project</h1> <p><strong>Do</strong>:</p> <ul> <li>name the directory something related to your project. For example, if your project is named "<em>Twisted</em>", name the top-level directory for its source files <code>Twisted</code>. When you do releases, you should include a version number suffix: <code>Twisted-2.5</code>. </li> <li>create a directory <code>Twisted/bin</code> and put your executables there, if you have any. Don't give them a <code>.py</code> extension, even if they are Python source files. Don't put any code in them except an import of and call to a main function defined somewhere else in your projects. </li> <li>If your project is expressable as a single Python source file, then put it into the directory and name it something related to your project. For example, <code>Twisted/twisted.py</code>. If you need multiple source files, create a package instead (<code>Twisted/twisted/</code>, with an empty <code>Twisted/twisted/__init__.py</code>) and place your source files in it. For example, <code>Twisted/twisted/internet.py</code>. </li> <li>put your unit tests in a sub-package of your package (note - this means that the single Python source file option above was a trick - you always need at least one other file for your unit tests). For example, <code>Twisted/twisted/test/</code>. Of course, make it a package with <code>Twisted/twisted/test/__init__.py</code>. Place tests in files like <code>Twisted/twisted/test/test_internet.py</code>.</li> <li>add <code>Twisted/README</code> and T<code>wisted/setup.py</code> to explain and install your software, respectively, if you're feeling nice.</li> </ul> <p><strong>Don't</strong>:</p> <ul> <li>put your source in a directory called <code>src</code> or <code>lib</code>. This makes it hard to run without installing. </li> <li>put your tests outside of your Python package. This makes it hard to run the tests against an installed version. </li> <li>create a package that only has a <code>__init__.py</code> and then put all your code into <code>__init__.py</code>. Just make a module instead of a package, it's simpler. </li> <li>try to come up with magical hacks to make Python able to import your module or package without having the user add the directory containing it to their import path (either via <code>PYTHONPATH</code> or some other mechanism). You will not correctly handle all cases and users will get angry at you when your software doesn't work in their environment.</li> </ul> </blockquote>
5
2009-10-02T13:48:36Z
[ "python", "sqlalchemy", "directory-structure", "version-control" ]
Cleanest and most Pythonic way to get tomorrow's date?
1,506,901
<p>What is the cleanest and most Pythonic way to get tomorrow's date? There must be a better way than to add one to the day, handle days at the end of the month, etc.</p>
43
2009-10-01T22:45:11Z
1,506,916
<p><code>datetime.date.today() + datetime.timedelta(days=1)</code> should do the trick</p>
90
2009-10-01T22:49:11Z
[ "python", "datetime", "date", "time" ]
Cleanest and most Pythonic way to get tomorrow's date?
1,506,901
<p>What is the cleanest and most Pythonic way to get tomorrow's date? There must be a better way than to add one to the day, handle days at the end of the month, etc.</p>
43
2009-10-01T22:45:11Z
1,506,917
<p><a href="http://docs.python.org/library/datetime.html#timedelta-objects"><code>timedelta</code></a> can handle adding days, seconds, microseconds, milliseconds, minutes, hours, or weeks.</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; today = datetime.date.today() &gt;&gt;&gt; today datetime.date(2009, 10, 1) &gt;&gt;&gt; today + datetime.timedelta(days=1) datetime.date(2009, 10, 2) &gt;&gt;&gt; datetime.date(2009,10,31) + datetime.timedelta(hours=24) datetime.date(2009, 11, 1) </code></pre> <p>As asked in a comment, leap days pose no problem:</p> <pre><code>&gt;&gt;&gt; datetime.date(2004, 2, 28) + datetime.timedelta(days=1) datetime.date(2004, 2, 29) &gt;&gt;&gt; datetime.date(2004, 2, 28) + datetime.timedelta(days=2) datetime.date(2004, 3, 1) &gt;&gt;&gt; datetime.date(2005, 2, 28) + datetime.timedelta(days=1) datetime.date(2005, 3, 1) </code></pre>
23
2009-10-01T22:49:24Z
[ "python", "datetime", "date", "time" ]
Cleanest and most Pythonic way to get tomorrow's date?
1,506,901
<p>What is the cleanest and most Pythonic way to get tomorrow's date? There must be a better way than to add one to the day, handle days at the end of the month, etc.</p>
43
2009-10-01T22:45:11Z
1,507,077
<p>No handling of <a href="http://en.wikipedia.org/wiki/Leap%5Fsecond">leap seconds</a> tho:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime, timedelta &gt;&gt;&gt; dt = datetime(2008,12,31,23,59,59) &gt;&gt;&gt; str(dt) '2008-12-31 23:59:59' &gt;&gt;&gt; # leap second was added at the end of 2008, &gt;&gt;&gt; # adding one second should create a datetime &gt;&gt;&gt; # of '2008-12-31 23:59:60' &gt;&gt;&gt; str(dt+timedelta(0,1)) '2009-01-01 00:00:00' &gt;&gt;&gt; str(dt+timedelta(0,2)) '2009-01-01 00:00:01' </code></pre> <p>darn.</p> <p>EDIT - @Mark: The docs say "yes", but the code says "not so much":</p> <pre><code>&gt;&gt;&gt; time.strptime("2008-12-31 23:59:60","%Y-%m-%d %H:%M:%S") (2008, 12, 31, 23, 59, 60, 2, 366, -1) &gt;&gt;&gt; time.mktime(time.strptime("2008-12-31 23:59:60","%Y-%m-%d %H:%M:%S")) 1230789600.0 &gt;&gt;&gt; time.gmtime(time.mktime(time.strptime("2008-12-31 23:59:60","%Y-%m-%d %H:%M:%S"))) (2009, 1, 1, 6, 0, 0, 3, 1, 0) &gt;&gt;&gt; time.localtime(time.mktime(time.strptime("2008-12-31 23:59:60","%Y-%m-%d %H:%M:%S"))) (2009, 1, 1, 0, 0, 0, 3, 1, 0) </code></pre> <p>I would think that gmtime or localtime would take the value returned by mktime and given me back the original tuple, with 60 as the number of seconds. And this test shows that these leap seconds can just fade away...</p> <pre><code>&gt;&gt;&gt; a = time.mktime(time.strptime("2008-12-31 23:59:60","%Y-%m-%d %H:%M:%S")) &gt;&gt;&gt; b = time.mktime(time.strptime("2009-01-01 00:00:00","%Y-%m-%d %H:%M:%S")) &gt;&gt;&gt; a,b (1230789600.0, 1230789600.0) &gt;&gt;&gt; b-a 0.0 </code></pre>
5
2009-10-01T23:45:34Z
[ "python", "datetime", "date", "time" ]
Cleanest and most Pythonic way to get tomorrow's date?
1,506,901
<p>What is the cleanest and most Pythonic way to get tomorrow's date? There must be a better way than to add one to the day, handle days at the end of the month, etc.</p>
43
2009-10-01T22:45:11Z
1,507,121
<p>Even the basic <code>time</code> module can handle this:</p> <pre><code>import time time.localtime(time.time() + 24*3600) </code></pre>
4
2009-10-01T23:58:15Z
[ "python", "datetime", "date", "time" ]
How do I get fluent in Python?
1,507,041
<p>Once you have learned the basic commands in Python, you are often able to solve most programming problem you face. But the way in which this is done is not really <em>Python-ic</em>. What is common is to use the classical c++ or Java mentality to solve problems. But Python is more than that. It has functional programming incorporated; many libraries available; object oriented, and its own ways. <strong>In short there are often better, shorter, faster, more elegant ways to the same thing.</strong></p> <p>It is a little bit like learning a new language. First you learn the words and the grammar, but then you need to get fluent. </p> <p>Once you have learned the language, how do you get fluent in Python? How have <em>you</em> done it? What books mostly helped?</p>
10
2009-10-01T23:32:12Z
1,507,045
<p>Have you read the <a href="http://rads.stackoverflow.com/amzn/click/0596007973" rel="nofollow">Python Cookbook</a>? It's a pretty good source for Pythonic.</p> <p>Plus you'll find <a href="http://stackoverflow.com/search?q=user%3a95810%20%5Bpython%5D&amp;tab=votes">much more from Alex Martelli on Stack Overflow</a>.</p>
8
2009-10-01T23:33:25Z
[ "python" ]
How do I get fluent in Python?
1,507,041
<p>Once you have learned the basic commands in Python, you are often able to solve most programming problem you face. But the way in which this is done is not really <em>Python-ic</em>. What is common is to use the classical c++ or Java mentality to solve problems. But Python is more than that. It has functional programming incorporated; many libraries available; object oriented, and its own ways. <strong>In short there are often better, shorter, faster, more elegant ways to the same thing.</strong></p> <p>It is a little bit like learning a new language. First you learn the words and the grammar, but then you need to get fluent. </p> <p>Once you have learned the language, how do you get fluent in Python? How have <em>you</em> done it? What books mostly helped?</p>
10
2009-10-01T23:32:12Z
1,507,054
<p>Read other people's code. Write some of your own code. Repeat for a year or two.</p> <p>Study the Python documentation and learn the built-in modules.</p> <p>Read Python in a Nutshell.</p> <p>Subscribe your RSS reader to the Python tag on Stack Overflow.</p>
10
2009-10-01T23:35:48Z
[ "python" ]
How do I get fluent in Python?
1,507,041
<p>Once you have learned the basic commands in Python, you are often able to solve most programming problem you face. But the way in which this is done is not really <em>Python-ic</em>. What is common is to use the classical c++ or Java mentality to solve problems. But Python is more than that. It has functional programming incorporated; many libraries available; object oriented, and its own ways. <strong>In short there are often better, shorter, faster, more elegant ways to the same thing.</strong></p> <p>It is a little bit like learning a new language. First you learn the words and the grammar, but then you need to get fluent. </p> <p>Once you have learned the language, how do you get fluent in Python? How have <em>you</em> done it? What books mostly helped?</p>
10
2009-10-01T23:32:12Z
1,507,058
<p>I guess becoming fluent in any programming language is the same as becoming fluent in a spoken/written language. You do that by speaking and listening to the language, a lot.</p> <p>So my advice is to do some projects using python, and you will soon become fluent in it. You can complement this by reading other people's code who are more experienced in the language to see how they solve certain problems. </p>
2
2009-10-01T23:36:15Z
[ "python" ]
How do I get fluent in Python?
1,507,041
<p>Once you have learned the basic commands in Python, you are often able to solve most programming problem you face. But the way in which this is done is not really <em>Python-ic</em>. What is common is to use the classical c++ or Java mentality to solve problems. But Python is more than that. It has functional programming incorporated; many libraries available; object oriented, and its own ways. <strong>In short there are often better, shorter, faster, more elegant ways to the same thing.</strong></p> <p>It is a little bit like learning a new language. First you learn the words and the grammar, but then you need to get fluent. </p> <p>Once you have learned the language, how do you get fluent in Python? How have <em>you</em> done it? What books mostly helped?</p>
10
2009-10-01T23:32:12Z
1,507,068
<p>The same way you get fluent in any language - program a lot.</p> <p>I'd recommend working on a project (hopefully something you'll actually use later). While working on the project, every time you need some basic piece of functionality, try writing it yourself, and <strong>then</strong> checking online how other people did it.</p> <p>This both lets you learn how to actually get stuff done in Python, but will also allow you to see what are the "Pythonic" counterparts to common coding cases.</p>
3
2009-10-01T23:41:36Z
[ "python" ]
How do I get fluent in Python?
1,507,041
<p>Once you have learned the basic commands in Python, you are often able to solve most programming problem you face. But the way in which this is done is not really <em>Python-ic</em>. What is common is to use the classical c++ or Java mentality to solve problems. But Python is more than that. It has functional programming incorporated; many libraries available; object oriented, and its own ways. <strong>In short there are often better, shorter, faster, more elegant ways to the same thing.</strong></p> <p>It is a little bit like learning a new language. First you learn the words and the grammar, but then you need to get fluent. </p> <p>Once you have learned the language, how do you get fluent in Python? How have <em>you</em> done it? What books mostly helped?</p>
10
2009-10-01T23:32:12Z
1,507,101
<p>There are some Python textbooks that not only teach you the language, they teach you the philosophy of the language (why it is the way it is) and teach you common idioms. I learned from the book <a href="http://www.rmi.net/~lutz/about-lp4e.html" rel="nofollow">Learning Python</a> by <a href="http://www.rmi.net/~lutz/" rel="nofollow">Mark Lutz</a> and I recommend it.</p> <p>If you already know the basics of the language, you can Google search for "Python idioms" and you will find some gems. Here are a few:</p> <p><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html" rel="nofollow">http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html</a></p> <p><a href="http://docs.python.org/dev/howto/doanddont.html" rel="nofollow">http://docs.python.org/dev/howto/doanddont.html</a></p> <p><a href="http://jaynes.colorado.edu/PythonIdioms.html" rel="nofollow">http://jaynes.colorado.edu/PythonIdioms.html</a></p> <p>If you read some good Python code and get a feel for why it was written the way it was, you can learn some cool things. Here is a recent <a href="http://stackoverflow.com/questions/1490190/python-modules-most-worthwhile-reading">discussion of modules worth reading</a> to improve your Pythonic coding skills.</p> <p>Good luck!</p> <p>EDIT: Oh, I should add: +1 for <a href="http://oreilly.com/catalog/9780596007973" rel="nofollow">Python Cookbook</a> and Alex Martelli. I didn't mention these because Jon-Eric already did.</p>
3
2009-10-01T23:52:38Z
[ "python" ]
How do I get fluent in Python?
1,507,041
<p>Once you have learned the basic commands in Python, you are often able to solve most programming problem you face. But the way in which this is done is not really <em>Python-ic</em>. What is common is to use the classical c++ or Java mentality to solve problems. But Python is more than that. It has functional programming incorporated; many libraries available; object oriented, and its own ways. <strong>In short there are often better, shorter, faster, more elegant ways to the same thing.</strong></p> <p>It is a little bit like learning a new language. First you learn the words and the grammar, but then you need to get fluent. </p> <p>Once you have learned the language, how do you get fluent in Python? How have <em>you</em> done it? What books mostly helped?</p>
10
2009-10-01T23:32:12Z
1,507,169
<p>More Pythonic? Start with a simple import.</p> <pre><code>import this </code></pre> <p>And add practice.</p>
5
2009-10-02T00:16:09Z
[ "python" ]
How do I get fluent in Python?
1,507,041
<p>Once you have learned the basic commands in Python, you are often able to solve most programming problem you face. But the way in which this is done is not really <em>Python-ic</em>. What is common is to use the classical c++ or Java mentality to solve problems. But Python is more than that. It has functional programming incorporated; many libraries available; object oriented, and its own ways. <strong>In short there are often better, shorter, faster, more elegant ways to the same thing.</strong></p> <p>It is a little bit like learning a new language. First you learn the words and the grammar, but then you need to get fluent. </p> <p>Once you have learned the language, how do you get fluent in Python? How have <em>you</em> done it? What books mostly helped?</p>
10
2009-10-01T23:32:12Z
1,507,504
<p>I can tell you what I've done.</p> <ol> <li><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html">Idiomatic Python</a></li> <li>Bookmark SO with the python keyword.</li> <li>Read other's <em>good</em> python code.</li> <li><a href="http://www.pythonchallenge.com/">The Python Challenge</a></li> </ol> <p>That order is probably good, too. This is where things get fun.</p>
7
2009-10-02T02:31:13Z
[ "python" ]
How do I get fluent in Python?
1,507,041
<p>Once you have learned the basic commands in Python, you are often able to solve most programming problem you face. But the way in which this is done is not really <em>Python-ic</em>. What is common is to use the classical c++ or Java mentality to solve problems. But Python is more than that. It has functional programming incorporated; many libraries available; object oriented, and its own ways. <strong>In short there are often better, shorter, faster, more elegant ways to the same thing.</strong></p> <p>It is a little bit like learning a new language. First you learn the words and the grammar, but then you need to get fluent. </p> <p>Once you have learned the language, how do you get fluent in Python? How have <em>you</em> done it? What books mostly helped?</p>
10
2009-10-01T23:32:12Z
1,509,575
<p>Read existing projects known for technical excelence.</p> <p>Some of the ones I'd recommend are:</p> <ul> <li><a href="http://code.djangoproject.com/browser/django" rel="nofollow">Django</a></li> <li><a href="http://svn.sqlalchemy.org/sqlalchemy/" rel="nofollow">SQLAlchemy</a></li> <li>Python's <a href="http://docs.python.org/library/json.html" rel="nofollow"><code>/lib/json</code></a></li> <li>Python's <code>/lib/test</code></li> <li>Visit <a href="http://pythonsource.com/" rel="nofollow">http://pythonsource.com/</a> for many other modules written in Python.</li> </ul>
2
2009-10-02T13:41:41Z
[ "python" ]
wx.TextCtrl.LoadFile()
1,507,075
<p>I am trying to display search result data quickly. I have all absolute file paths for files on my network drive(s) in a single, ~50MB text file. The python script makes a single pass over every line in this file [kept on the local drive] in a second or less, and that is acceptable. That is the time it takes to gather results.</p> <p>However, the results are given in a wx.TextCtrl widget. Appending them line by line to a wx TextCtrl would be ridiculous. The best method I have come up with is to write the results to a text file, and call wx.TextCtrl's LoadFile native, which, depending on the number of results, loads the lines of text into the pane in between 0.1 to 5 seconds or so. However there must be a faster way for 10+MB of text inbound. The results are immediately calculated and available in the same process as the GUI... so please, tell me is there any way I can pipe/proxy/hack that data directly into the TextCtrl? Would mmap help this transfer?</p>
0
2009-10-01T23:44:31Z
1,507,087
<p>Are people really going to read (or need) all 10MB in a text control? Probably not.</p> <p>Suggest that, you load on demand by paging in portions of the data.</p> <p>Or better still, provide some user search functionality that narrows down the results to the information of interest.</p>
0
2009-10-01T23:49:32Z
[ "python", "file-io", "wxpython", "wxwidgets", "mmap" ]
wx.TextCtrl.LoadFile()
1,507,075
<p>I am trying to display search result data quickly. I have all absolute file paths for files on my network drive(s) in a single, ~50MB text file. The python script makes a single pass over every line in this file [kept on the local drive] in a second or less, and that is acceptable. That is the time it takes to gather results.</p> <p>However, the results are given in a wx.TextCtrl widget. Appending them line by line to a wx TextCtrl would be ridiculous. The best method I have come up with is to write the results to a text file, and call wx.TextCtrl's LoadFile native, which, depending on the number of results, loads the lines of text into the pane in between 0.1 to 5 seconds or so. However there must be a faster way for 10+MB of text inbound. The results are immediately calculated and available in the same process as the GUI... so please, tell me is there any way I can pipe/proxy/hack that data directly into the TextCtrl? Would mmap help this transfer?</p>
0
2009-10-01T23:44:31Z
1,512,903
<p>You can load all the data at once with AppendText, why you need to do it line by line, but still it will take seconds as 10MB is huge. If you use wx.RichTextCtrl it is bit faster in my test it loaded 10 MB in 6 secs instead of 9 sec for TextCtrl.</p> <p>I do not see the reason why you need to set all the data at once? and who is going to read 10MB?</p> <p>So depending on the purpose there can be better ways.</p> <p>If you need to display all data in super fast way, write a custom control which keeps a list of lines and only renders the lines visible in the view.</p> <p>here is a test app where you can try various things</p> <pre><code>import wx import wx.richtext import string import time # create a big text line = string.ascii_letters+"\n" bigText = line*200000 app = wx.PySimpleApp() myframe = wx.Frame(None) #tc = wx.TextCtrl(myframe, style=wx.TE_MULTILINE) tc = wx.richtext.RichTextCtrl(myframe) def loadData(): s = time.time() tc.SetMaxLength(len(bigText)) tc.AppendText(bigText) print time.time()-s # load big text after 5 secs wx.CallLater(5000, loadData) app.SetTopWindow(myframe) myframe.Show() app.MainLoop() </code></pre> <p>If you do not want to paint everything youself in a custom control, you can just use a textctrl with separate scrollbar and update text of textcntrl on scrolling, so at a time you will be loading few lines only.</p> <p><strong>Edit:</strong> as you said in your comment that data may be 1-2 MB, 1MB data with AppendText takes only .5 sec I think that is ok</p>
0
2009-10-03T05:32:18Z
[ "python", "file-io", "wxpython", "wxwidgets", "mmap" ]
Python: is it bad form to raise exceptions within __init__?
1,507,082
<p>Is it considered bad form to raise exceptions within __init_? If so, then what is the accepted method of throwing an error when certain class variables are initialized as None or of an incorrect type?</p>
59
2009-10-01T23:47:38Z
1,507,112
<p>I should think it is the perfect case for the built-in <code>ValueError</code> exception.</p>
3
2009-10-01T23:55:38Z
[ "python", "exception" ]
Python: is it bad form to raise exceptions within __init__?
1,507,082
<p>Is it considered bad form to raise exceptions within __init_? If so, then what is the accepted method of throwing an error when certain class variables are initialized as None or of an incorrect type?</p>
59
2009-10-01T23:47:38Z
1,507,120
<p>The standard library says:</p> <pre><code>&gt;&gt;&gt; f = file("notexisting.txt") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IOError: [Errno 2] No such file or directory: 'notexisting.txt' </code></pre> <p>Also I don't really see any reason why it should be considered bad form.</p>
3
2009-10-01T23:58:13Z
[ "python", "exception" ]
Python: is it bad form to raise exceptions within __init__?
1,507,082
<p>Is it considered bad form to raise exceptions within __init_? If so, then what is the accepted method of throwing an error when certain class variables are initialized as None or of an incorrect type?</p>
59
2009-10-01T23:47:38Z
1,507,127
<p>Raising exceptions within <code>__init__()</code> is absolutely fine. There's no other good way to indicate an error condition within a constructor, and there are many hundreds of examples in the standard library where building an object can raise an exception.</p> <p>The error class to raise, of course, is up to you. <code>ValueError</code> is best if the constructor was passed an invalid parameter.</p>
82
2009-10-01T23:59:26Z
[ "python", "exception" ]
Python: is it bad form to raise exceptions within __init__?
1,507,082
<p>Is it considered bad form to raise exceptions within __init_? If so, then what is the accepted method of throwing an error when certain class variables are initialized as None or of an incorrect type?</p>
59
2009-10-01T23:47:38Z
1,507,130
<p>I don't see any reason that it should be bad form.</p> <p>On the contrary, one of the things exceptions are known for doing well, as opposed to returning error codes, is that error codes usually <strong>can't</strong> be returned by constructors. So at least in languages like C++, raising exceptions is the only way to signal errors.</p>
8
2009-10-02T00:01:01Z
[ "python", "exception" ]
Python: is it bad form to raise exceptions within __init__?
1,507,082
<p>Is it considered bad form to raise exceptions within __init_? If so, then what is the accepted method of throwing an error when certain class variables are initialized as None or of an incorrect type?</p>
59
2009-10-01T23:47:38Z
1,507,245
<p>I concur with all of the above.</p> <p>There's really no other way to signal that something went wrong in the initialisation of an object other than raising an exception. </p> <p>In most programs classes where the state of a class is wholly dependant on the inputs to that class we might expect some kind of ValueError or TypeError to be raised. </p> <p>Classes with side-effects (e.g. one which does networking or graphics) might raise an error in init if (for example) the network device is unavailable or the canvas object cannot be written to. This sounds sensible to me because often you want to know about failure conditions as soon as possible. </p>
2
2009-10-02T00:46:58Z
[ "python", "exception" ]
Python: is it bad form to raise exceptions within __init__?
1,507,082
<p>Is it considered bad form to raise exceptions within __init_? If so, then what is the accepted method of throwing an error when certain class variables are initialized as None or of an incorrect type?</p>
59
2009-10-01T23:47:38Z
7,501,167
<p>It's true that the only proper way to indicate an error in a constructor is raising an exception. That is why in C++ and in other object-oriented languages that have been designed with exception safety in mind, the destructor is not called if an exception is thrown in the constructor of an object (meaning that the initialization of the object is incomplete). This is often not the case in scripting languages, such as Python. For example, the following code throws an AttributeError if socket.connect() fails:</p> <pre><code>class NetworkInterface: def __init__(self, address) self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect(address) self.stream = self.socket.makefile() def __del__(self) self.stream.close() self.socket.close() </code></pre> <p>The reason is that the destructor of the incomplete object is called after the connection attempt has failed, before the stream attribute has been initialized. You shouldn't avoid throwing exceptions from constructors, I'm just saying that it's difficult to write fully exception safe code in Python. Some Python developers avoid using destructors altogether, but that's a matter of another debate.</p>
8
2011-09-21T14:04:02Z
[ "python", "exception" ]
Python: is it bad form to raise exceptions within __init__?
1,507,082
<p>Is it considered bad form to raise exceptions within __init_? If so, then what is the accepted method of throwing an error when certain class variables are initialized as None or of an incorrect type?</p>
59
2009-10-01T23:47:38Z
18,825,585
<p>Raising errors from init is unavoidable in some cases, but doing too much work in init is a bad style. You should consider making a factory or a pseudo-factory - a simple classmethod that returns setted up object.</p>
1
2013-09-16T10:18:01Z
[ "python", "exception" ]
How to check dimensions of all images in a directory using python?
1,507,084
<p>I need to check the dimensions of images in a directory. Currently it has ~700 images. I just need to check the sizes, and if the size does not match a given dimension, it will be moved to a different folder. How do I get started? </p>
10
2009-10-01T23:47:48Z
1,507,110
<p>You can use the <a href="http://www.pythonware.com/products/pil/" rel="nofollow">Python Imaging Library</a> (aka PIL) to read the image headers and query the dimensions.</p> <p>One way to approach it would be to write yourself a function that takes a filename and returns the dimensions (using PIL). Then use the <code>os.path.walk</code> function to traverse all the files in the directory, applying this function. Collecting the results, you can build a dictionary of mappings <code>filename -&gt; dimensions</code>, then use a list comprehension (see <code>itertools</code>) to filter out those that do not match the required size.</p>
4
2009-10-01T23:55:11Z
[ "python", "image", "directory" ]
How to check dimensions of all images in a directory using python?
1,507,084
<p>I need to check the dimensions of images in a directory. Currently it has ~700 images. I just need to check the sizes, and if the size does not match a given dimension, it will be moved to a different folder. How do I get started? </p>
10
2009-10-01T23:47:48Z
1,507,142
<p>One common way is to use <a href="http://www.pythonware.com/products/pil/">PIL</a>, the python imaging library to get the dimensions:</p> <pre><code>from PIL import Image import os.path filename = os.path.join('path', 'to', 'image', 'file') img = Image.open(filename) print img.size </code></pre> <p>Then you need to loop over the files in your directory, check the dimensions against your required dimensions, and move those files that do not match.</p>
5
2009-10-02T00:06:21Z
[ "python", "image", "directory" ]
How to check dimensions of all images in a directory using python?
1,507,084
<p>I need to check the dimensions of images in a directory. Currently it has ~700 images. I just need to check the sizes, and if the size does not match a given dimension, it will be moved to a different folder. How do I get started? </p>
10
2009-10-01T23:47:48Z
3,175,473
<p>If you don't need the rest of PIL and just want image dimensions of PNG, JPEG and GIF then this small function (BSD license) does the job nicely:</p> <p><a href="http://code.google.com/p/bfg-pages/source/browse/trunk/pages/getimageinfo.py" rel="nofollow">http://code.google.com/p/bfg-pages/source/browse/trunk/pages/getimageinfo.py</a></p> <pre><code>import StringIO import struct def getImageInfo(data): data = str(data) size = len(data) height = -1 width = -1 content_type = '' # handle GIFs if (size &gt;= 10) and data[:6] in ('GIF87a', 'GIF89a'): # Check to see if content_type is correct content_type = 'image/gif' w, h = struct.unpack("&lt;HH", data[6:10]) width = int(w) height = int(h) # See PNG 2. Edition spec (http://www.w3.org/TR/PNG/) # Bytes 0-7 are below, 4-byte chunk length, then 'IHDR' # and finally the 4-byte width, height elif ((size &gt;= 24) and data.startswith('\211PNG\r\n\032\n') and (data[12:16] == 'IHDR')): content_type = 'image/png' w, h = struct.unpack("&gt;LL", data[16:24]) width = int(w) height = int(h) # Maybe this is for an older PNG version. elif (size &gt;= 16) and data.startswith('\211PNG\r\n\032\n'): # Check to see if we have the right content type content_type = 'image/png' w, h = struct.unpack("&gt;LL", data[8:16]) width = int(w) height = int(h) # handle JPEGs elif (size &gt;= 2) and data.startswith('\377\330'): content_type = 'image/jpeg' jpeg = StringIO.StringIO(data) jpeg.read(2) b = jpeg.read(1) try: while (b and ord(b) != 0xDA): while (ord(b) != 0xFF): b = jpeg.read(1) while (ord(b) == 0xFF): b = jpeg.read(1) if (ord(b) &gt;= 0xC0 and ord(b) &lt;= 0xC3): jpeg.read(3) h, w = struct.unpack("&gt;HH", jpeg.read(4)) break else: jpeg.read(int(struct.unpack("&gt;H", jpeg.read(2))[0])-2) b = jpeg.read(1) width = int(w) height = int(h) except struct.error: pass except ValueError: pass return content_type, width, height </code></pre>
13
2010-07-04T17:01:48Z
[ "python", "image", "directory" ]
How to check dimensions of all images in a directory using python?
1,507,084
<p>I need to check the dimensions of images in a directory. Currently it has ~700 images. I just need to check the sizes, and if the size does not match a given dimension, it will be moved to a different folder. How do I get started? </p>
10
2009-10-01T23:47:48Z
34,704,634
<pre><code>#!/usr/bin/env python """ Get information about images in a folder. """ from os import listdir from os.path import isfile, join from PIL import Image def print_data(data): """ Parameters ---------- data : dict """ for k, v in data.items(): print("%s:\t%s" % (k, v)) print("Min width: %i" % data['min_width']) print("Max width: %i" % data['max_width']) print("Min height: %i" % data['min_height']) print("Min height: %i" % data['max_height']) def main(path): """ Parameters ---------- path : str Path where to look for image files. """ onlyfiles = [f for f in listdir(path) if isfile(join(path, f))] # Filter files by extension onlyfiles = [f for f in onlyfiles if f.endswith('.jpg')] data = {} data['images_count'] = len(onlyfiles) data['min_width'] = 10**100 # No image will be bigger than that data['max_width'] = 0 data['min_height'] = 10**100 # No image will be bigger than that data['max_height'] = 0 for filename in onlyfiles: im = Image.open(filename) width, height = im.size data['min_width'] = min(width, data['min_width']) data['max_width'] = max(width, data['max_height']) data['min_height'] = min(height, data['min_height']) data['max_height'] = max(height, data['max_height']) print_data(data) if __name__ == '__main__': main(path='.') </code></pre>
1
2016-01-10T11:02:30Z
[ "python", "image", "directory" ]
python MySQLDB query timeout
1,507,091
<p>I'm trying to enforce a time limit on queries in python MySQLDB. I have a situation where I have no control over the queries, but need to ensure that they do not run over a set time limit. I've tried using signal.SIGALRM to interrupt the call to execute, but this does not seem to work. The signal gets sent, but does not get caught until after the call to execute finishes.</p> <p>I wrote a test case to prove this behavior:</p> <pre><code>#!/usr/local/bin/python2.6 import time import signal from somewhere import get_dbc class Timeout(Exception): """ Time Exceded """ def _alarm_handler(*args): raise Timeout dbc = get_dbc() signal.signal(signal.SIGALRM, _alarm_handler) signal.alarm(1) try: print "START: ", time.time() dbc.execute("SELECT SLEEP(10)") except Timeout: print "TIMEOUT!", time.time()' </code></pre> <p>The "SELECT SLEEP(10)" is simulating a slow query, but I do see the same behavior with an actual slow query.</p> <p>The Result:</p> <pre><code>START: 1254440686.69 TIMEOUT! 1254440696.69 </code></pre> <p>As you can see, it's sleeping for 10 seconds then I get the Timeout Exception. </p> <p>Questions: </p> <ol> <li>Why do I not get the signal until after execute finishes?</li> <li>Is there another reliable way to limit query execution time?</li> </ol>
7
2009-10-01T23:51:06Z
1,507,116
<blockquote> <p>Why do I not get the signal until after execute finishes?</p> </blockquote> <p>The query is executed through a C function, which blocks the Python VM from executing until it returns.</p> <blockquote> <p>Is there another reliable way to limit query execution time?</p> </blockquote> <p>This is (IMO) a really ugly solution, but it <em>does</em> work. You could run the query in a separate process (either via <code>fork()</code> or the <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow"><code>multiprocessing</code> module</a>). Run the alarm timer in your main process, and when you receive it, send a <code>SIGINT</code> or <code>SIGKILL</code> to the child process. If you use <code>multiprocessing</code>, you can use the <code>Process.terminate()</code> method.</p>
1
2009-10-01T23:56:40Z
[ "python", "timeout", "mysql" ]
python MySQLDB query timeout
1,507,091
<p>I'm trying to enforce a time limit on queries in python MySQLDB. I have a situation where I have no control over the queries, but need to ensure that they do not run over a set time limit. I've tried using signal.SIGALRM to interrupt the call to execute, but this does not seem to work. The signal gets sent, but does not get caught until after the call to execute finishes.</p> <p>I wrote a test case to prove this behavior:</p> <pre><code>#!/usr/local/bin/python2.6 import time import signal from somewhere import get_dbc class Timeout(Exception): """ Time Exceded """ def _alarm_handler(*args): raise Timeout dbc = get_dbc() signal.signal(signal.SIGALRM, _alarm_handler) signal.alarm(1) try: print "START: ", time.time() dbc.execute("SELECT SLEEP(10)") except Timeout: print "TIMEOUT!", time.time()' </code></pre> <p>The "SELECT SLEEP(10)" is simulating a slow query, but I do see the same behavior with an actual slow query.</p> <p>The Result:</p> <pre><code>START: 1254440686.69 TIMEOUT! 1254440696.69 </code></pre> <p>As you can see, it's sleeping for 10 seconds then I get the Timeout Exception. </p> <p>Questions: </p> <ol> <li>Why do I not get the signal until after execute finishes?</li> <li>Is there another reliable way to limit query execution time?</li> </ol>
7
2009-10-01T23:51:06Z
1,507,370
<p>Use <a href="http://twistedmatrix.com/documents/current/api/twisted.enterprise.adbapi.html" rel="nofollow">adbapi</a>. It allows you to do a db call asynchronously.</p> <pre><code>from twisted.internet import reactor from twisted.enterprise import adbapi def bogusQuery(): return dbpool.runQuery("SELECT SLEEP(10)") def printResult(l): # function that would be called if it didn't time out for item in l: print item def handle_timeout(): # function that will be called when it timeout reactor.stop() dbpool = adbapi.ConnectionPool("MySQLdb", user="me", password="myself", host="localhost", database="async") bogusQuery().addCallback(printResult) reactor.callLater(4, handle_timeout) reactor.run() </code></pre>
1
2009-10-02T01:29:34Z
[ "python", "timeout", "mysql" ]
python MySQLDB query timeout
1,507,091
<p>I'm trying to enforce a time limit on queries in python MySQLDB. I have a situation where I have no control over the queries, but need to ensure that they do not run over a set time limit. I've tried using signal.SIGALRM to interrupt the call to execute, but this does not seem to work. The signal gets sent, but does not get caught until after the call to execute finishes.</p> <p>I wrote a test case to prove this behavior:</p> <pre><code>#!/usr/local/bin/python2.6 import time import signal from somewhere import get_dbc class Timeout(Exception): """ Time Exceded """ def _alarm_handler(*args): raise Timeout dbc = get_dbc() signal.signal(signal.SIGALRM, _alarm_handler) signal.alarm(1) try: print "START: ", time.time() dbc.execute("SELECT SLEEP(10)") except Timeout: print "TIMEOUT!", time.time()' </code></pre> <p>The "SELECT SLEEP(10)" is simulating a slow query, but I do see the same behavior with an actual slow query.</p> <p>The Result:</p> <pre><code>START: 1254440686.69 TIMEOUT! 1254440696.69 </code></pre> <p>As you can see, it's sleeping for 10 seconds then I get the Timeout Exception. </p> <p>Questions: </p> <ol> <li>Why do I not get the signal until after execute finishes?</li> <li>Is there another reliable way to limit query execution time?</li> </ol>
7
2009-10-01T23:51:06Z
1,508,287
<blockquote> <p>Why do I not get the signal until after execute finishes?</p> </blockquote> <p>The process waiting for network I/O is in an uninterruptible state (UNIX thing, not related to Python or MySQL). It gets the signal after the system call finishes (probably as <code>EINTR</code> error code, although I am not sure).</p> <blockquote> <p>Is there another reliable way to limit query execution time?</p> </blockquote> <p>I think that it is usually done by an external tool like <code>mkill</code> that monitors MySQL for long running queries and kills them. </p>
-1
2009-10-02T08:17:49Z
[ "python", "timeout", "mysql" ]
python MySQLDB query timeout
1,507,091
<p>I'm trying to enforce a time limit on queries in python MySQLDB. I have a situation where I have no control over the queries, but need to ensure that they do not run over a set time limit. I've tried using signal.SIGALRM to interrupt the call to execute, but this does not seem to work. The signal gets sent, but does not get caught until after the call to execute finishes.</p> <p>I wrote a test case to prove this behavior:</p> <pre><code>#!/usr/local/bin/python2.6 import time import signal from somewhere import get_dbc class Timeout(Exception): """ Time Exceded """ def _alarm_handler(*args): raise Timeout dbc = get_dbc() signal.signal(signal.SIGALRM, _alarm_handler) signal.alarm(1) try: print "START: ", time.time() dbc.execute("SELECT SLEEP(10)") except Timeout: print "TIMEOUT!", time.time()' </code></pre> <p>The "SELECT SLEEP(10)" is simulating a slow query, but I do see the same behavior with an actual slow query.</p> <p>The Result:</p> <pre><code>START: 1254440686.69 TIMEOUT! 1254440696.69 </code></pre> <p>As you can see, it's sleeping for 10 seconds then I get the Timeout Exception. </p> <p>Questions: </p> <ol> <li>Why do I not get the signal until after execute finishes?</li> <li>Is there another reliable way to limit query execution time?</li> </ol>
7
2009-10-01T23:51:06Z
1,510,167
<p>@nosklo's twisted-based solution is elegant and workable, but if you want to avoid the dependency on twisted, the task is still doable, e.g....:</p> <pre><code>import multiprocessing def query_with_timeout(dbc, timeout, query, *a, **k): conn1, conn2 = multiprocessing.Pipe(False) subproc = multiprocessing.Process(target=do_query, args=(dbc, query, conn2)+a, kwargs=k) subproc.start() subproc.join(timeout) if conn1.poll(): return conn1.recv() subproc.terminate() raise TimeoutError("Query %r ran for &gt;%r" % (query, timeout)) def do_query(dbc, query, conn, *a, **k): cu = dbc.cursor() cu.execute(query, *a, **k) return cu.fetchall() </code></pre>
7
2009-10-02T15:14:05Z
[ "python", "timeout", "mysql" ]
python MySQLDB query timeout
1,507,091
<p>I'm trying to enforce a time limit on queries in python MySQLDB. I have a situation where I have no control over the queries, but need to ensure that they do not run over a set time limit. I've tried using signal.SIGALRM to interrupt the call to execute, but this does not seem to work. The signal gets sent, but does not get caught until after the call to execute finishes.</p> <p>I wrote a test case to prove this behavior:</p> <pre><code>#!/usr/local/bin/python2.6 import time import signal from somewhere import get_dbc class Timeout(Exception): """ Time Exceded """ def _alarm_handler(*args): raise Timeout dbc = get_dbc() signal.signal(signal.SIGALRM, _alarm_handler) signal.alarm(1) try: print "START: ", time.time() dbc.execute("SELECT SLEEP(10)") except Timeout: print "TIMEOUT!", time.time()' </code></pre> <p>The "SELECT SLEEP(10)" is simulating a slow query, but I do see the same behavior with an actual slow query.</p> <p>The Result:</p> <pre><code>START: 1254440686.69 TIMEOUT! 1254440696.69 </code></pre> <p>As you can see, it's sleeping for 10 seconds then I get the Timeout Exception. </p> <p>Questions: </p> <ol> <li>Why do I not get the signal until after execute finishes?</li> <li>Is there another reliable way to limit query execution time?</li> </ol>
7
2009-10-01T23:51:06Z
1,609,603
<blockquote> <p>I've tried using signal.SIGALRM to interrupt the call to execute, but this does not seem to work. The signal gets sent, but does not get caught until after the call to execute finishes.</p> </blockquote> <p>mysql library handles interrupted systems calls internally so you won't see side effects of SIGALRM until after API call completes (short of killing the current thread or process)</p> <p>You can try patching MySQL-Python and use MYSQL_OPT_READ_TIMEOUT option (added in mysql 5.0.25)</p>
2
2009-10-22T19:58:56Z
[ "python", "timeout", "mysql" ]
python MySQLDB query timeout
1,507,091
<p>I'm trying to enforce a time limit on queries in python MySQLDB. I have a situation where I have no control over the queries, but need to ensure that they do not run over a set time limit. I've tried using signal.SIGALRM to interrupt the call to execute, but this does not seem to work. The signal gets sent, but does not get caught until after the call to execute finishes.</p> <p>I wrote a test case to prove this behavior:</p> <pre><code>#!/usr/local/bin/python2.6 import time import signal from somewhere import get_dbc class Timeout(Exception): """ Time Exceded """ def _alarm_handler(*args): raise Timeout dbc = get_dbc() signal.signal(signal.SIGALRM, _alarm_handler) signal.alarm(1) try: print "START: ", time.time() dbc.execute("SELECT SLEEP(10)") except Timeout: print "TIMEOUT!", time.time()' </code></pre> <p>The "SELECT SLEEP(10)" is simulating a slow query, but I do see the same behavior with an actual slow query.</p> <p>The Result:</p> <pre><code>START: 1254440686.69 TIMEOUT! 1254440696.69 </code></pre> <p>As you can see, it's sleeping for 10 seconds then I get the Timeout Exception. </p> <p>Questions: </p> <ol> <li>Why do I not get the signal until after execute finishes?</li> <li>Is there another reliable way to limit query execution time?</li> </ol>
7
2009-10-01T23:51:06Z
18,083,281
<h3>Generic notes</h3> <p>I've experienced the same issue lately with several conditions I had to met:</p> <ul> <li>solution must be thread safe</li> <li>multiple connections to database from the same machine may be active at the same time, kill the exact one connection/query</li> <li>application contains connections to many different databases - portable handler for each DB host</li> </ul> <p>We had following class layout (<em>unfortunately I cannot post real sources</em>):</p> <pre class="lang-python prettyprint-override"><code>class AbstractModel: pass class FirstDatabaseModel(AbstractModel): pass # Connection to one DB host class SecondDatabaseModel(AbstractModel): pass # Connection to one DB host </code></pre> <p>And created several threads for each model.</p> <hr/> <h3>Solution <sub>Python 3.2</sub></h3> <p>In our application <em>one model = one database</em>. So I've created "<em>service connection</em>" for each model (so we could execute <code>KILL</code> in parallel connection). Therefore if one instance of <code>FirstDatabaseModel</code> was created, 2 database connection were created; if 5 instances were created only 6 connections were used:</p> <pre class="lang-python prettyprint-override"><code>class AbstractModel: _service_connection = None # Formal declaration def __init__(self): ''' Somehow load config and create connection ''' self.config = # ... self.connection = MySQLFromConfig(self.config) self._init_service_connection() # Get connection ID (pseudocode) self.connection_id = self.connection.FetchOneCol('SELECT CONNECTION_ID()') def _init_service_connection(self): ''' Initialize one singleton connection for model ''' cls = type(self) if cls._service_connection is not None: return cls._service_connection = MySQLFromConfig(self.config) </code></pre> <p>Now we need a killer:</p> <pre class="lang-python prettyprint-override"><code>def _kill_connection(self): # Add your own mysql data escaping sql = 'KILL CONNECTION {}'.format(self.connection_id) # Do your own connection check and renewal type(self)._service_connection.execute(sql) </code></pre> <p><em>Note: <code>connection.execute</code> = create cursor, execute, close cursor.</em></p> <p>And make killer thread safe using <code>threading.Lock</code>:</p> <pre class="lang-python prettyprint-override"><code>def _init_service_connection(self): ''' Initialize one singleton connection for model ''' cls = type(self) if cls._service_connection is not None: return cls._service_connection = MySQLFromConfig(self.config) cls._service_connection_lock = threading.Lock() def _kill_connection(self): # Add your own mysql data escaping sql = 'KILL CONNECTION {}'.format(self.connection_id) cls = type(self) # Do your own connection check and renewal try: cls._service_connection_lock.acquire() cls._service_connection.execute(sql) finally: cls._service_connection_lock.release() </code></pre> <p>And finally add timed execution method using <code>threading.Timer</code>:</p> <pre class="lang-python prettyprint-override"><code>def timed_query(self, sql, timeout=5): kill_query_timer = threading.Timer(timeout, self._kill_connection) kill_query_timer.start() try: self.connection.long_query() finally: kill_query_timer.cancel() </code></pre>
1
2013-08-06T14:41:09Z
[ "python", "timeout", "mysql" ]
urllib2: submitting a form and then redirecting
1,507,170
<p>My goal is to come up with a portable urllib2 solution that would POST a form and then redirect the user to what comes out. The POSTing part is simple:</p> <pre><code>request = urllib2.Request('https://some.site/page', data=urllib.urlencode({'key':'value'})) response = urllib2.urlopen(request) </code></pre> <p>Providing <code>data</code> sets request type to POST. Now, what I suspect all the data I should care about comes from <code>response.info()</code> &amp; <code>response.geturl()</code>. I should do a <code>self.redirect(response.geturl())</code> inside a <code>get(self)</code> method of <code>webapp.RequestHandler</code>.</p> <p>But what should I do with headers? Anything else I've overlooked? Code snippets are highly appreciated. :)</p> <p>TIA.</p> <p>EDIT: Here's a naive solution I came up with. Redirects but the remote server shows an error indicating that there's no match to the previously POSTed form:</p> <pre><code>info = response.info() for key in info: self.response.headers[key] = info[key] self.response.headers['Location'] = response.geturl() self.response.set_status(302) self.response.clear() </code></pre>
1
2009-10-02T00:16:10Z
1,507,415
<p>I suspect this will almost always fail. When you POST a form, the URL you end up at is just the URL you posted to. Sending someone else to this URL, or even visiting it again with the same browser that just POSTed, is going to do a GET and the page won't have the form data that was POSTed. The only way this would work is if the site redirected after the POST to a URL containing some sort of session info.</p>
2
2009-10-02T01:51:37Z
[ "python", "google-app-engine", "urllib2" ]
urllib2: submitting a form and then redirecting
1,507,170
<p>My goal is to come up with a portable urllib2 solution that would POST a form and then redirect the user to what comes out. The POSTing part is simple:</p> <pre><code>request = urllib2.Request('https://some.site/page', data=urllib.urlencode({'key':'value'})) response = urllib2.urlopen(request) </code></pre> <p>Providing <code>data</code> sets request type to POST. Now, what I suspect all the data I should care about comes from <code>response.info()</code> &amp; <code>response.geturl()</code>. I should do a <code>self.redirect(response.geturl())</code> inside a <code>get(self)</code> method of <code>webapp.RequestHandler</code>.</p> <p>But what should I do with headers? Anything else I've overlooked? Code snippets are highly appreciated. :)</p> <p>TIA.</p> <p>EDIT: Here's a naive solution I came up with. Redirects but the remote server shows an error indicating that there's no match to the previously POSTed form:</p> <pre><code>info = response.info() for key in info: self.response.headers[key] = info[key] self.response.headers['Location'] = response.geturl() self.response.set_status(302) self.response.clear() </code></pre>
1
2009-10-02T00:16:10Z
1,507,434
<p>The standard way to follow redirects with urllib2 is to use the <a href="http://docs.python.org/library/urllib2.html#httpredirecthandler-objects" rel="nofollow">HTTPRedirectHandler</a>. (Not sure what you mean by 'what comes out' but I'm assuming a standard http redirect here, javascript redirect is a different beast)</p> <pre><code># Created handler redirectionHandler = urllib2.HTTPRedirectHandler() # 2 apply the handler to an opener opener = urllib2.build_opener(redirectionHandler) # 3. Install the openers urllib2.install_opener(opener) request = urllib2.Request('https://some.site/page', data=urllib.urlencode({'key':'value'})) response = urllib2.urlopen(request) </code></pre> <p>See <a href="http://docs.python.org/library/urllib2.html#httpredirecthandler-objects" rel="nofollow">urllib2.HTTPRedirectHandler</a> for details on the handler.</p>
2
2009-10-02T01:57:40Z
[ "python", "google-app-engine", "urllib2" ]
urllib2: submitting a form and then redirecting
1,507,170
<p>My goal is to come up with a portable urllib2 solution that would POST a form and then redirect the user to what comes out. The POSTing part is simple:</p> <pre><code>request = urllib2.Request('https://some.site/page', data=urllib.urlencode({'key':'value'})) response = urllib2.urlopen(request) </code></pre> <p>Providing <code>data</code> sets request type to POST. Now, what I suspect all the data I should care about comes from <code>response.info()</code> &amp; <code>response.geturl()</code>. I should do a <code>self.redirect(response.geturl())</code> inside a <code>get(self)</code> method of <code>webapp.RequestHandler</code>.</p> <p>But what should I do with headers? Anything else I've overlooked? Code snippets are highly appreciated. :)</p> <p>TIA.</p> <p>EDIT: Here's a naive solution I came up with. Redirects but the remote server shows an error indicating that there's no match to the previously POSTed form:</p> <pre><code>info = response.info() for key in info: self.response.headers[key] = info[key] self.response.headers['Location'] = response.geturl() self.response.set_status(302) self.response.clear() </code></pre>
1
2009-10-02T00:16:10Z
1,507,721
<p>You will find using mechanize much easier than using urllib2 directly</p> <p><a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">http://wwwsearch.sourceforge.net/mechanize/</a></p>
0
2009-10-02T04:22:42Z
[ "python", "google-app-engine", "urllib2" ]
What are the advantages of faster server side scripting languages?
1,507,175
<p>Typical performance of Python scripts are about <a href="http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy/" rel="nofollow">5 times faster</a> than PHP. What are the advantages of using faster server side scripting languages? Will the speed ever be felt by website visitors? Can PHP's performance be compensated by faster server processors?</p>
1
2009-10-02T00:17:15Z
1,507,183
<p>How about <a href="http://code.google.com/appengine/docs/quotas.html#Resources" rel="nofollow">when you get charged for CPU time</a>? </p> <blockquote> <p>I just saved a ton of money by switching to Python!</p> </blockquote>
9
2009-10-02T00:21:51Z
[ "php", "python", "performance", "scripting", "webserver" ]
What are the advantages of faster server side scripting languages?
1,507,175
<p>Typical performance of Python scripts are about <a href="http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy/" rel="nofollow">5 times faster</a> than PHP. What are the advantages of using faster server side scripting languages? Will the speed ever be felt by website visitors? Can PHP's performance be compensated by faster server processors?</p>
1
2009-10-02T00:17:15Z
1,507,186
<p>According to Andy B. King, in <em>Website Optimization</em>:</p> <blockquote> <p>For Google an increase in page load time from 0.4 second to 0.9 seconds decreased traffic and ad revenues by 20%. For Amazon every 100 ms increase in load times decreased sales with 1%.</p> </blockquote> <p><a href="http://www.svennerberg.com/2008/12/page-load-times-vs-conversion-rates/">http://www.svennerberg.com/2008/12/page-load-times-vs-conversion-rates/</a></p> <p>But even though Python is ~4 times faster, by and large it's the architecture of the software that makes the biggest difference. If your queries and disk access are unoptimized, then you have a massive bottleneck&mdash;even when you're just including some 20 different files (5ms seek time equals 100ms). I'm certain that even Python can be slowed by inefficiencies and database queries, just as badly as PHP can.</p> <p>That said, unfriendly interfaces will cost you more, in the long run, than the decrease in speed will. Just make a registration form with no explanation and fifteen required fields, with strict validation, and you'll scare tons of people away. (In my own opinion.)</p>
12
2009-10-02T00:23:48Z
[ "php", "python", "performance", "scripting", "webserver" ]
What are the advantages of faster server side scripting languages?
1,507,175
<p>Typical performance of Python scripts are about <a href="http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy/" rel="nofollow">5 times faster</a> than PHP. What are the advantages of using faster server side scripting languages? Will the speed ever be felt by website visitors? Can PHP's performance be compensated by faster server processors?</p>
1
2009-10-02T00:17:15Z
1,507,192
<p>Increasing the execution speed of web request handlers usually translates to handling more requests/second with the same hardware. This is valuable in a number of cases; maintaining one server is much easier than maintaining two.</p> <p>BTW, why Python and not Haskell? Haskell is 100x faster than PHP in some benchmarks.</p>
1
2009-10-02T00:26:02Z
[ "php", "python", "performance", "scripting", "webserver" ]
What are the advantages of faster server side scripting languages?
1,507,175
<p>Typical performance of Python scripts are about <a href="http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy/" rel="nofollow">5 times faster</a> than PHP. What are the advantages of using faster server side scripting languages? Will the speed ever be felt by website visitors? Can PHP's performance be compensated by faster server processors?</p>
1
2009-10-02T00:17:15Z
1,507,200
<p>For typical web apps, the difference in speed won't usually be felt within the request itself (the network latency dwarfs your compute time for a typical script that runs inside an HTTP request).</p> <p>There are plenty of <em>other</em> things that affect scalability, but the processing needs to handle an average request does factor in. So, a lonely user will not feel the difference. A user who is one of many might feel the difference, as the server infrastructure struggles with load.</p> <p>Of course, throwing more processor will mitigate the issue, but as jrockway says, maintaining two servers is significantly more than twice as hard as maintaining one.</p> <p>All of that said, in the vast majority of cases, your bottlenecks will not be processor. You'll be running out of memory, or you'll find that your database interaction is the real bottleneck.</p>
4
2009-10-02T00:31:06Z
[ "php", "python", "performance", "scripting", "webserver" ]
How and when to appropriately use weakref in Python
1,507,566
<p>I have some code where instances of classes have parent&lt;->child references to each other, e.g.:</p> <pre><code>class Node(object): def __init__(self): self.parent = None self.children = {} def AddChild(self, name, child): child.parent = self self.children[name] = child def Run(): root, c1, c2 = Node(), Node(), Node() root.AddChild("first", c1) root.AddChild("second", c2) Run() </code></pre> <p>I <em>think</em> this creates circular references such that <code>root</code>, <code>c1</code> and <code>c2</code> won't be freed after Run() is completed, right?. So, how do get them to be freed? I think I can do something like <code>root.children.clear()</code>, or <code>self.parent = None</code> - but what if I don't know when to do that?</p> <p>Is this an appropriate time to use the weakref module? What, exactly, do I weakref'ify? the <code>parent</code> attribute? The <code>children</code> attribute? The whole object? All of the above? I see talk about the WeakKeyDictionary and weakref.proxy, but its not clear to me how they should be used, if at all, in this case.</p> <p>This is also on python2.4 (can't upgrade).</p> <p><strong>Update: Example and Summary</strong></p> <p>What objects to weakref-ify depends on which object can live without the other, and what objects depend on each other. The object that lives the longest should contain weakrefs to the shorter-lived objects. Similarly, weakrefs should not be made to dependencies - if they are, the dependency could silently disappear even though it is still needed.</p> <p>If, for example, you have a tree structure, <code>root</code>, that has children, <code>kids</code>, but can exist <em>without</em> children, then the <code>root</code> object should use weakrefs for its <code>kids</code>. This is also the case if the child object depends on the existence of the parent object. Below, the child object <em>requires</em> a parent in order to compute its depth, hence the strong-ref for <code>parent</code>. The members of the <code>kids</code> attribute are optional, though, so weakrefs are used to prevent a circular reference.</p> <pre><code>class Node: def __init__(self) self.parent = None self.kids = weakref.WeakValueDictionary() def GetDepth(self): root, depth = self, 0 while root: depth += 1 root = root.parent return count root = Node() root.kids["one"] = Node() root.kids["two"] = Node() # do what you will with root or sub-trees of it. </code></pre> <p>To flip the relationship around, we have something like the below. Here, the <code>Facade</code> classes require a <code>Subsystem</code> instance to work, so they use a strong-ref to the subsystem they need. <code>Subsystem</code>s, however, don't require a <code>Facade</code> to work. <code>Subsystem</code>s just provide a way to notify <code>Facade</code>s about each other's actions.</p> <pre><code>class Facade: def __init__(self, subsystem) self.subsystem = subsystem subsystem.Register(self) class Subsystem: def __init__(self): self.notify = [] def Register(self, who): self.notify.append(weakref.proxy(who)) sub = Subsystem() f1 = CliFacade(sub) f2 = WebFacade(sub) # Go on to reading from POST, stdin, etc </code></pre>
38
2009-10-02T03:03:40Z
1,507,578
<p>Yep, weakref's excellent here. Specifically, instead of:</p> <pre><code>self.children = {} </code></pre> <p>use:</p> <pre><code>self.children = weakref.WeakValueDictionary() </code></pre> <p>Nothing else needs change in your code. This way, when a child has no other differences, it just goes away -- and so does the entry in the parent's <code>children</code> map that has that child as the value.</p> <p>Avoiding reference loops is up high on a par with implementing caches as a motivation for using the <code>weakref</code> module. Ref loops won't kill you, but they may end up clogging your memory, esp. if some of the classes whose instances are involved in them define <code>__del__</code>, since that interferes with the <code>gc</code>'s module ability to dissolve those loops.</p>
23
2009-10-02T03:10:11Z
[ "python", "circular-reference" ]
How and when to appropriately use weakref in Python
1,507,566
<p>I have some code where instances of classes have parent&lt;->child references to each other, e.g.:</p> <pre><code>class Node(object): def __init__(self): self.parent = None self.children = {} def AddChild(self, name, child): child.parent = self self.children[name] = child def Run(): root, c1, c2 = Node(), Node(), Node() root.AddChild("first", c1) root.AddChild("second", c2) Run() </code></pre> <p>I <em>think</em> this creates circular references such that <code>root</code>, <code>c1</code> and <code>c2</code> won't be freed after Run() is completed, right?. So, how do get them to be freed? I think I can do something like <code>root.children.clear()</code>, or <code>self.parent = None</code> - but what if I don't know when to do that?</p> <p>Is this an appropriate time to use the weakref module? What, exactly, do I weakref'ify? the <code>parent</code> attribute? The <code>children</code> attribute? The whole object? All of the above? I see talk about the WeakKeyDictionary and weakref.proxy, but its not clear to me how they should be used, if at all, in this case.</p> <p>This is also on python2.4 (can't upgrade).</p> <p><strong>Update: Example and Summary</strong></p> <p>What objects to weakref-ify depends on which object can live without the other, and what objects depend on each other. The object that lives the longest should contain weakrefs to the shorter-lived objects. Similarly, weakrefs should not be made to dependencies - if they are, the dependency could silently disappear even though it is still needed.</p> <p>If, for example, you have a tree structure, <code>root</code>, that has children, <code>kids</code>, but can exist <em>without</em> children, then the <code>root</code> object should use weakrefs for its <code>kids</code>. This is also the case if the child object depends on the existence of the parent object. Below, the child object <em>requires</em> a parent in order to compute its depth, hence the strong-ref for <code>parent</code>. The members of the <code>kids</code> attribute are optional, though, so weakrefs are used to prevent a circular reference.</p> <pre><code>class Node: def __init__(self) self.parent = None self.kids = weakref.WeakValueDictionary() def GetDepth(self): root, depth = self, 0 while root: depth += 1 root = root.parent return count root = Node() root.kids["one"] = Node() root.kids["two"] = Node() # do what you will with root or sub-trees of it. </code></pre> <p>To flip the relationship around, we have something like the below. Here, the <code>Facade</code> classes require a <code>Subsystem</code> instance to work, so they use a strong-ref to the subsystem they need. <code>Subsystem</code>s, however, don't require a <code>Facade</code> to work. <code>Subsystem</code>s just provide a way to notify <code>Facade</code>s about each other's actions.</p> <pre><code>class Facade: def __init__(self, subsystem) self.subsystem = subsystem subsystem.Register(self) class Subsystem: def __init__(self): self.notify = [] def Register(self, who): self.notify.append(weakref.proxy(who)) sub = Subsystem() f1 = CliFacade(sub) f2 = WebFacade(sub) # Go on to reading from POST, stdin, etc </code></pre>
38
2009-10-02T03:03:40Z
1,508,284
<p>I suggest using <code>child.parent = weakref.proxy(self)</code>. This is good solution to avoid circular references in case when lifetime of (external references to) <code>parent</code> covers lifetime of <code>child</code>. Contrary, use <code>weakref</code> for <code>child</code> (as Alex suggested) when lifetime of <code>child</code> covers lifetime of <code>parent</code>. But never use <code>weakref</code> when both <code>parent</code> and <code>child</code> can be alive without other.</p> <p>Here these rules are illustrated with examples. Use weakref-ed parent if you store root in some variable and pass it around, while children are accessed from it:</p> <pre><code>def Run(): root, c1, c2 = Node(), Node(), Node() root.AddChild("first", c1) root.AddChild("second", c2) return root # Note that only root refers to c1 and c2 after return, # so this references should be strong </code></pre> <p>Use weakref-ed children if you bind all them to variables, while root is accessed through them:</p> <pre><code>def Run(): root, c1, c2 = Node(), Node(), Node() root.AddChild("first", c1) root.AddChild("second", c2) return c1, c2 </code></pre> <p>But neither will work for the following:</p> <pre><code>def Run(): root, c1, c2 = Node(), Node(), Node() root.AddChild("first", c1) root.AddChild("second", c2) return c1 </code></pre>
11
2009-10-02T08:17:00Z
[ "python", "circular-reference" ]
How and when to appropriately use weakref in Python
1,507,566
<p>I have some code where instances of classes have parent&lt;->child references to each other, e.g.:</p> <pre><code>class Node(object): def __init__(self): self.parent = None self.children = {} def AddChild(self, name, child): child.parent = self self.children[name] = child def Run(): root, c1, c2 = Node(), Node(), Node() root.AddChild("first", c1) root.AddChild("second", c2) Run() </code></pre> <p>I <em>think</em> this creates circular references such that <code>root</code>, <code>c1</code> and <code>c2</code> won't be freed after Run() is completed, right?. So, how do get them to be freed? I think I can do something like <code>root.children.clear()</code>, or <code>self.parent = None</code> - but what if I don't know when to do that?</p> <p>Is this an appropriate time to use the weakref module? What, exactly, do I weakref'ify? the <code>parent</code> attribute? The <code>children</code> attribute? The whole object? All of the above? I see talk about the WeakKeyDictionary and weakref.proxy, but its not clear to me how they should be used, if at all, in this case.</p> <p>This is also on python2.4 (can't upgrade).</p> <p><strong>Update: Example and Summary</strong></p> <p>What objects to weakref-ify depends on which object can live without the other, and what objects depend on each other. The object that lives the longest should contain weakrefs to the shorter-lived objects. Similarly, weakrefs should not be made to dependencies - if they are, the dependency could silently disappear even though it is still needed.</p> <p>If, for example, you have a tree structure, <code>root</code>, that has children, <code>kids</code>, but can exist <em>without</em> children, then the <code>root</code> object should use weakrefs for its <code>kids</code>. This is also the case if the child object depends on the existence of the parent object. Below, the child object <em>requires</em> a parent in order to compute its depth, hence the strong-ref for <code>parent</code>. The members of the <code>kids</code> attribute are optional, though, so weakrefs are used to prevent a circular reference.</p> <pre><code>class Node: def __init__(self) self.parent = None self.kids = weakref.WeakValueDictionary() def GetDepth(self): root, depth = self, 0 while root: depth += 1 root = root.parent return count root = Node() root.kids["one"] = Node() root.kids["two"] = Node() # do what you will with root or sub-trees of it. </code></pre> <p>To flip the relationship around, we have something like the below. Here, the <code>Facade</code> classes require a <code>Subsystem</code> instance to work, so they use a strong-ref to the subsystem they need. <code>Subsystem</code>s, however, don't require a <code>Facade</code> to work. <code>Subsystem</code>s just provide a way to notify <code>Facade</code>s about each other's actions.</p> <pre><code>class Facade: def __init__(self, subsystem) self.subsystem = subsystem subsystem.Register(self) class Subsystem: def __init__(self): self.notify = [] def Register(self, who): self.notify.append(weakref.proxy(who)) sub = Subsystem() f1 = CliFacade(sub) f2 = WebFacade(sub) # Go on to reading from POST, stdin, etc </code></pre>
38
2009-10-02T03:03:40Z
9,834,694
<p>I wanted to clarify which references can be weak. The following approach is general, but I use the doubly-linked tree in all examples. </p> <p>Logical Step 1.</p> <p>You need to ensure that there are strong references to keep all the objects alive as long as you need them. It could be done in many ways, for example by:</p> <ul> <li>[direct names]: a named reference to each node in the tree</li> <li>[container]: a reference to a container that stores all the nodes</li> <li>[root + children]: a reference to the root node, and references from each node to its children</li> <li>[leaves + parent]: references to all the leaf nodes, and references from each node to its parent</li> </ul> <p>Logical Step 2.</p> <p>Now you add references to represent information, if required.</p> <p>For instance, if you used [container] approach in Step 1, you still have to represent the edges. An edge between nodes A and B can be represented with a single reference; it can go in either direction. Again, there are many options, for example:</p> <ul> <li>[children]: references from each node to its children</li> <li>[parent]: a reference from each node to its parent</li> <li>[set of sets]: a set containing 2-element sets; each 2-element contains references to nodes of one edge</li> </ul> <p>Of course, if you used [root + children] approach in Step 1, all your information is already fully represented, so you skip this step.</p> <p>Logical Step 3.</p> <p>Now you add references to improve performance, if desired.</p> <p>For instance, if you used [container] approach in Step 1, and [children] approach in Step 2, you might desire to improve the speed of certain algorithms, and add references between each each node and its parent. Such information is logically redundant, since you could (at a cost in performance) derive it from existing data.</p> <hr> <p><em>All the references in Step 1 must be strong</em>.</p> <p><em>All the references in Steps 2 and 3 may be weak or strong</em>. There is no advantage to using strong references. There is an advantage to using weak references until you know that cycles are no longer possible. Strictly speaking, once you know that cycles are impossible, it makes no difference whether to use weak or strong references. But to avoid thinking about it, you might as well use exclusively weak references in the Steps 2 and 3.</p>
0
2012-03-23T05:48:28Z
[ "python", "circular-reference" ]
How does Smalltalk (Pharo for example) compare to Python?
1,508,256
<p>I've seen some comparisons between <strong>Smalltalk and Ruby</strong> on the one hand and <strong>Ruby and Python</strong> on the other, but <strong>not between Python and Smalltalk</strong>. I'd especially like to know what the fundamental differences in Implementation, Syntax, Extensiabillity and Philosophy are. </p> <p><em>For example Python does not seem to have Metaclasses. Smalltalk has no concept of generators. And although both are said to be dynamicly typed, I believe that Python does not do dynamic method dispatch. Is this correct?</em></p>
6
2009-10-02T08:09:36Z
1,508,306
<p>According to <a href="http://en.wikipedia.org/wiki/Dynamic%5Fdispatch" rel="nofollow">Wikipedia</a>'s page on dynamic method dispatch:</p> <blockquote> <p><strong>Smalltalk Implementation</strong></p> <p>Smalltalk uses a type based message dispatcher. Each instance has a single type whose definition contains the methods. When an instance receives a message, the dispatcher looks up the corresponding method in the message-to-method map for the type and then invokes the method. [...]</p> <p>Many other dynamically typed languages, including <strong>Python</strong>, Ruby, Objective-C and Groovy use similar approaches.</p> </blockquote> <p>Emphasis added, and one paragraph snipped. So, at least that part seems to be similar between the two languages.</p>
1
2009-10-02T08:25:04Z
[ "python", "comparison", "language-features", "smalltalk", "language-comparisons" ]
How does Smalltalk (Pharo for example) compare to Python?
1,508,256
<p>I've seen some comparisons between <strong>Smalltalk and Ruby</strong> on the one hand and <strong>Ruby and Python</strong> on the other, but <strong>not between Python and Smalltalk</strong>. I'd especially like to know what the fundamental differences in Implementation, Syntax, Extensiabillity and Philosophy are. </p> <p><em>For example Python does not seem to have Metaclasses. Smalltalk has no concept of generators. And although both are said to be dynamicly typed, I believe that Python does not do dynamic method dispatch. Is this correct?</em></p>
6
2009-10-02T08:09:36Z
1,508,309
<p>I've been reading <a href="http://rads.stackoverflow.com/amzn/click/1430219483" rel="nofollow">coders at work</a> which is a really nice book full of interviews with top programmers. Anyhow, one of them is the inventor of smalltalk and he talks in length on his language and how it relates to python (he likes python quite a bit as well). The only problem he had with python was it's slow code... he really wanted to have the smalltalk jit compiler as a backend for python, but unfortunately due to the software belonging to the company he worked for, this was not possible.</p> <p>anyhow... maybe not a point by point comparison, but really a good read anyway this book.</p>
2
2009-10-02T08:26:31Z
[ "python", "comparison", "language-features", "smalltalk", "language-comparisons" ]
How does Smalltalk (Pharo for example) compare to Python?
1,508,256
<p>I've seen some comparisons between <strong>Smalltalk and Ruby</strong> on the one hand and <strong>Ruby and Python</strong> on the other, but <strong>not between Python and Smalltalk</strong>. I'd especially like to know what the fundamental differences in Implementation, Syntax, Extensiabillity and Philosophy are. </p> <p><em>For example Python does not seem to have Metaclasses. Smalltalk has no concept of generators. And although both are said to be dynamicly typed, I believe that Python does not do dynamic method dispatch. Is this correct?</em></p>
6
2009-10-02T08:09:36Z
1,508,312
<p>Python certainly does have metaclasses.</p> <p>Smalltalk has some unusual features:</p> <ul> <li>Has a rather simple syntax and only about 6 (!) keywords. Everything else (including defining new classes) is accomplished by calling methods (sending messages in Smalltalk). This allows you to create some DSL within the language.</li> <li>In Smalltalk, you don't store source files, but instead have one big memory image and you modify it on the fly. You can also modify most of the Smalltalk itself (and possibly break it ;)</li> </ul>
7
2009-10-02T08:26:55Z
[ "python", "comparison", "language-features", "smalltalk", "language-comparisons" ]
How does Smalltalk (Pharo for example) compare to Python?
1,508,256
<p>I've seen some comparisons between <strong>Smalltalk and Ruby</strong> on the one hand and <strong>Ruby and Python</strong> on the other, but <strong>not between Python and Smalltalk</strong>. I'd especially like to know what the fundamental differences in Implementation, Syntax, Extensiabillity and Philosophy are. </p> <p><em>For example Python does not seem to have Metaclasses. Smalltalk has no concept of generators. And although both are said to be dynamicly typed, I believe that Python does not do dynamic method dispatch. Is this correct?</em></p>
6
2009-10-02T08:09:36Z
1,510,402
<blockquote> <p>For example Python does not seem to have Metaclasses.</p> </blockquote> <p>It sure does -- it just doesn't implicitly generate a new metaclass for every class: it uses the same metaclass as the parent class, or <code>type</code> by default. Python's design philosophy, aka "The Zen of Python", can be perused by doing <code>import this</code> at an interactive interpreter's prompt; the applicable point here is the second one, "Explicit is better than implicit."</p> <p>In Python 2.X, you specify a custom metaclass with the following syntax:</p> <pre><code>class sic: __metaclass__ = mymeta ... </code></pre> <p>In Python 3.X, more elegantly, you use named-argument syntax:</p> <pre><code>class sify(metaclass=mymeta): ... </code></pre> <blockquote> <p>Smalltalk has no concept of generators.</p> </blockquote> <p>Python's generators are first-class (typically standalone) functions, and Smalltalk doesn't have the concept of "standalone" functions -- it has methods inside classes. But it certainly does have iterators -- as classes, of course:</p> <pre><code>iterator := aCollection iterator. [iterator hasNext] whileTrue: [iterator next doSomething]. </code></pre> <p>Since Smalltalk has first-class "code blocks" (Ruby took them from it), you accomplish iteration, just like other "control structures", by sending a code block to a suitable method, and if you wish you can do that directly with the collection (think <code>select:</code>):</p> <pre><code>aCollection select: [:item | item doSomething]. </code></pre> <p>So in Smalltalk (and Ruby) you send the code block to the iteration; Python does things the other way round, the iteration sends values out to the surrounding "calling" code. Looks very different, but not "deeply" different in the end.</p> <p>First-class code blocks mean that Smalltalk doesn't need nor have "control structure" statements and keywords such as <code>if</code> or <code>while</code>: they can be accomplished by sending code blocks as arguments of appropriate methods (e.g. <code>ifTrue:</code> method of booleans). (Ruby chooses to have the keywords/statements <em>in addition</em> to the first-class code blocks; I would say that Python [[explicitly]] and Smalltalk [[implicitly]] both try, like C, to "offer a single way to perform an operation", while Ruby's more in the Perl-ish school of "there are many ways to do it").</p> <blockquote> <p>And although both are said to be dynamicly typed, I believe that Python does not do dynamic method dispatch. Is this correct?</p> </blockquote> <p>No, absolutely incorrect -- Python <em>intensely</em> does dynamic method dispatch, <strong>to extremes</strong>. Consider for example:</p> <pre><code>for i in range(10): myobject.bah() </code></pre> <p>By Python semantics, this performs <strong>10 lookups</strong> for method <code>bah</code> in <code>myobject</code> -- just in case the previous execution of the method had caused <code>myobject</code> to entirely restructure itself internally so that its <em>current</em> <code>bah</code> method is completely different from the <em>previous</em> one (might be a pretty insane thing for the programmer to rely on such furious dynamism, but Python supports it). This is the reason that makes:</p> <pre><code>themethod = myobject.bah for i in range(10): themethod() </code></pre> <p>a common hand-optimization in Python code -- does one dynamic lookup before the loop instead of 10 inside the loop, one per leg (it's a case of "constant hoisting", since the compiler is forbidden from doing the "constant folding" itself by Python's extreme rules for dynamic lookups -- unless it can prove that it's guaranteed to be innocuous, and in practice such proof is too hard so Python implementations typically don't bother).</p> <p>Python uses unified namespaces: methods are attributes of an object just like any other, except that they're callable. This is why extracting the method without calling it (known as a "bound method"), setting a reference to it in a variable (or stashing it into a list or other container, returning it from a function, whatever) is a plain and simple operation like in the above constant-hoisting example.</p> <p>Smalltalk and Ruby have separate namespaces for methods and other attributes (in Smalltalk, non-methods attributes are not visible outside the object's own methods), so "extracting a method" and "calling the resulting object" require more introspective ceremony (but the common case of dispatching may be thereby made marginally simpler in certain cases -- in particular, "just mentioning" an argument-less method implicitly calls it, while in Python, like in C, calling is explicitly performed by appending parentheses, while "just mentioning", well... "just mentions" it, making it available for any sort of explicit operation <em>including</em> calling;-).</p>
9
2009-10-02T15:54:15Z
[ "python", "comparison", "language-features", "smalltalk", "language-comparisons" ]
How does Smalltalk (Pharo for example) compare to Python?
1,508,256
<p>I've seen some comparisons between <strong>Smalltalk and Ruby</strong> on the one hand and <strong>Ruby and Python</strong> on the other, but <strong>not between Python and Smalltalk</strong>. I'd especially like to know what the fundamental differences in Implementation, Syntax, Extensiabillity and Philosophy are. </p> <p><em>For example Python does not seem to have Metaclasses. Smalltalk has no concept of generators. And although both are said to be dynamicly typed, I believe that Python does not do dynamic method dispatch. Is this correct?</em></p>
6
2009-10-02T08:09:36Z
1,883,218
<blockquote> <p>Smalltalk has no concept of generators.</p> </blockquote> <p>True, but they can be implemented in most Smalltalk dialects from within the language. GNU Smalltalk comes with Generators as part of its <a href="http://smalltalk.gnu.org/faq/47" rel="nofollow">stream library</a>.</p>
2
2009-12-10T19:01:12Z
[ "python", "comparison", "language-features", "smalltalk", "language-comparisons" ]
Why is it that my thumbnail PIL function won't work the 2nd time?
1,508,355
<blockquote> <pre><code>def create_thumbnail(f, width=200, height=100): im = Image.open(f) im.thumbnail((width, height), Image.ANTIALIAS) thumbnail_file = StringIO() im.save(thumbnail_file, 'JPEG') thumbnail_file.seek(0) return thumbnail_file </code></pre> </blockquote> <p>It seems that my error is "IOError: cannot identify image file"...based on my traceback log.</p>
0
2009-10-02T08:42:22Z
1,508,826
<p>The only thing I can think of is that you are running on Windows, in which case <code>Image.open()</code> will open a file handler but does not close it. (That behaviour does not occur on Linux/Unix - the file is closed by the end of your code, and it doesn't matter if it isn't anyway).</p>
2
2009-10-02T10:43:59Z
[ "python", "python-imaging-library" ]
Mod_python produces no output
1,508,406
<p>Just installed and configured mod_python 3.2.8 on a CentOS 5 (Apache 2.2.3) server with Python 2.4.3. It is loaded fine by Apache.</p> <p>I activated the mpinfo test page and it works. So I wrote a simple "Hello World" with the following code:</p> <pre><code>from mod_python import apache def handler(req): req.content_type = 'text/plain' req.write("Hello World!") req.flush() return apache.OK </code></pre> <p>It outputs a blank page, with no text and no source. If I consciously create a syntax error I get the error output on the URL, for example (when I put a space before "def"):</p> <pre><code>Mod_python error: "PythonHandler mod_python.cgihandler" Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 299, in HandlerDispatch result = object(req) File "/usr/lib/python2.4/site-packages/mod_python/cgihandler.py", line 96, in handler imp.load_module(module_name, fd, path, desc) File "/var/www/vhosts/localhost/httpdocs/mptest.py", line 3 def handler(req): ^ SyntaxError: invalid syntax </code></pre> <p>I have spent about five hours browsing different tutorials, faqs and trouble shooting guides but can't find a description of this exakt issue.</p> <p>What do you think could be the issue/cause?</p> <p><b>EDIT:</b> Here is the Apache configuration for the site...</p> <pre><code>&lt;Directory /&gt; Options FollowSymLinks AllowOverride None AddHandler mod_python .py PythonHandler mptest PythonDebug On &lt;/Directory&gt; </code></pre> <p><b>EDIT 2:</b> Ah, another thing I forgot to mention is that I intend to use mod_python to write Apache extensions. The application itself is written in PHP but I need to make some security tweeks on the server :)</p>
1
2009-10-02T08:51:43Z
1,508,747
<p>Don't use <code>mod_python</code>. </p> <p>A common mistake is to take <code>mod_python</code> as "<em><code>mod_php</code>, but for python</em>" and that is <strong>not true</strong>. <code>mod_python</code> is more suited to writing apache extensions, not web applications. </p> <p>The <a href="http://www.python.org/dev/peps/pep-0333/" rel="nofollow">standartized</a> protocol to use between python web applications and web servers (not only apache) is <a href="http://wsgi.org" rel="nofollow">WSGI</a>. Using it ensures that you can publish your application to any wsgi-compliant webserver (almost all modern web servers are wsgi-compliant)</p> <p>On apache, use <a href="http://code.google.com/p/modwsgi/" rel="nofollow"><code>mod_wsgi</code></a> instead.</p> <p>Your example rewritten using the wsgi standard and <code>mod_wsgi</code> on apache:</p> <p><code>mywebapp.py</code>:</p> <pre><code>def application(environ, start_response): start_response('200 OK', [('content-type', 'text/plain')]) return ['Hello World'] </code></pre> <p>Apache configuration:</p> <pre><code>WSGIScriptAlias /myapp /usr/local/www/wsgi-scripts/mywebapp.py &lt;Directory /usr/local/www/wsgi-scripts&gt; Order allow,deny Allow from all &lt;/Directory&gt; </code></pre> <p>Now just go to <code>http://localhost/myapp</code> and the script will run. Additionally, any access under this root (i.e. <code>http://localhost/myapp/stuff/here</code>) will be handled by this script.</p> <p>It's a good idea to choose a web framework. <a href="http://cherrypy.org/" rel="nofollow">CherryPy</a>. <a href="http://pylonshq.com" rel="nofollow">Pylons</a>. <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>. They make things even easier.</p> <p>A good website to look at is <a href="http://wsgi.org" rel="nofollow">wsgi.org</a></p>
2
2009-10-02T10:18:17Z
[ "python", "apache", "mod-python" ]
Mod_python produces no output
1,508,406
<p>Just installed and configured mod_python 3.2.8 on a CentOS 5 (Apache 2.2.3) server with Python 2.4.3. It is loaded fine by Apache.</p> <p>I activated the mpinfo test page and it works. So I wrote a simple "Hello World" with the following code:</p> <pre><code>from mod_python import apache def handler(req): req.content_type = 'text/plain' req.write("Hello World!") req.flush() return apache.OK </code></pre> <p>It outputs a blank page, with no text and no source. If I consciously create a syntax error I get the error output on the URL, for example (when I put a space before "def"):</p> <pre><code>Mod_python error: "PythonHandler mod_python.cgihandler" Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 299, in HandlerDispatch result = object(req) File "/usr/lib/python2.4/site-packages/mod_python/cgihandler.py", line 96, in handler imp.load_module(module_name, fd, path, desc) File "/var/www/vhosts/localhost/httpdocs/mptest.py", line 3 def handler(req): ^ SyntaxError: invalid syntax </code></pre> <p>I have spent about five hours browsing different tutorials, faqs and trouble shooting guides but can't find a description of this exakt issue.</p> <p>What do you think could be the issue/cause?</p> <p><b>EDIT:</b> Here is the Apache configuration for the site...</p> <pre><code>&lt;Directory /&gt; Options FollowSymLinks AllowOverride None AddHandler mod_python .py PythonHandler mptest PythonDebug On &lt;/Directory&gt; </code></pre> <p><b>EDIT 2:</b> Ah, another thing I forgot to mention is that I intend to use mod_python to write Apache extensions. The application itself is written in PHP but I need to make some security tweeks on the server :)</p>
1
2009-10-02T08:51:43Z
1,509,008
<p>I make a complete new answer for clarity...</p> <p>I decided to install mod_wsgi instead. So I've set it up and when I go to my testfile I just see the page source. I haven't been spending any time on finding the issue yet, so I'll get back to you when I either solve the problem or decide that I need more help :)</p> <p>Thank you :)</p>
0
2009-10-02T11:35:19Z
[ "python", "apache", "mod-python" ]
Mod_python produces no output
1,508,406
<p>Just installed and configured mod_python 3.2.8 on a CentOS 5 (Apache 2.2.3) server with Python 2.4.3. It is loaded fine by Apache.</p> <p>I activated the mpinfo test page and it works. So I wrote a simple "Hello World" with the following code:</p> <pre><code>from mod_python import apache def handler(req): req.content_type = 'text/plain' req.write("Hello World!") req.flush() return apache.OK </code></pre> <p>It outputs a blank page, with no text and no source. If I consciously create a syntax error I get the error output on the URL, for example (when I put a space before "def"):</p> <pre><code>Mod_python error: "PythonHandler mod_python.cgihandler" Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 299, in HandlerDispatch result = object(req) File "/usr/lib/python2.4/site-packages/mod_python/cgihandler.py", line 96, in handler imp.load_module(module_name, fd, path, desc) File "/var/www/vhosts/localhost/httpdocs/mptest.py", line 3 def handler(req): ^ SyntaxError: invalid syntax </code></pre> <p>I have spent about five hours browsing different tutorials, faqs and trouble shooting guides but can't find a description of this exakt issue.</p> <p>What do you think could be the issue/cause?</p> <p><b>EDIT:</b> Here is the Apache configuration for the site...</p> <pre><code>&lt;Directory /&gt; Options FollowSymLinks AllowOverride None AddHandler mod_python .py PythonHandler mptest PythonDebug On &lt;/Directory&gt; </code></pre> <p><b>EDIT 2:</b> Ah, another thing I forgot to mention is that I intend to use mod_python to write Apache extensions. The application itself is written in PHP but I need to make some security tweeks on the server :)</p>
1
2009-10-02T08:51:43Z
1,512,233
<p>Your original problem is that mod_python.cgihandler is being called to handle the request. This means your Python script file is being interpreted as a CGI script. Thus, no wonder it doesn't return anything.</p> <p>You likely have conflicting definition in your Apache configuration which is enabling the mod_python.cgihandler.</p>
1
2009-10-02T23:08:41Z
[ "python", "apache", "mod-python" ]
fast string modification in python
1,508,464
<p>This is partially a theoretical question:</p> <p>I have a string (say UTF-8), and I need to modify it so that each character (not byte) becomes 2 characters, for instance:</p> <pre><code>"Nissim" becomes "N-i-s-s-i-m-" "01234" becomes "0a1b2c3d4e" </code></pre> <p>and so on. I would suspect that naive concatenation in a loop would be too expensive (it IS the bottleneck, this is supposed to happen all the time).</p> <p>I would either use an array (pre-allocated) or try to make my own C module to handle this.</p> <p>Anyone has better ideas for this kind of thing?</p> <p>(Note that the problem is always about multibyte encodings, and must be solved for UTF-8 as well),</p> <p>Oh and its Python 2.5, so no shiny Python 3 thingies are available here.</p> <p>Thanks</p>
4
2009-10-02T09:06:17Z
1,508,508
<p>have you tested how slow it is or how fast you need, i think something like this will be fast enough</p> <pre><code>s = u"\u0960\u0961" ss = ''.join(sum(map(list,zip(s,"anurag")),[])) </code></pre> <p>So try with simplest and if it doesn't suffice then try to improve upon it, C module should be last option</p> <p><strong>Edit:</strong> This is also the fastest</p> <pre><code>import timeit s1="Nissim" s2="------" timeit.f1=lambda s1,s2:''.join(sum(map(list,zip(s1,s2)),[])) timeit.f2=lambda s1,s2:''.join([''.join(list(x)) for x in zip(s1,s2)]) timeit.f3=lambda s1,s2:''.join(i+j for i, j in zip(s1, s2)) N=100000 print "anurag",timeit.Timer("timeit.f1('Nissim', '------')","import timeit").timeit(N) print "dweeves",timeit.Timer("timeit.f2('Nissim', '------')","import timeit").timeit(N) print "SilentGhost",timeit.Timer("timeit.f3('Nissim', '------')","import timeit").timeit(N) </code></pre> <p>output is</p> <pre><code>anurag 1.95547590546 dweeves 2.36131184271 SilentGhost 3.10855625505 </code></pre>
1
2009-10-02T09:15:59Z
[ "python", "string" ]
fast string modification in python
1,508,464
<p>This is partially a theoretical question:</p> <p>I have a string (say UTF-8), and I need to modify it so that each character (not byte) becomes 2 characters, for instance:</p> <pre><code>"Nissim" becomes "N-i-s-s-i-m-" "01234" becomes "0a1b2c3d4e" </code></pre> <p>and so on. I would suspect that naive concatenation in a loop would be too expensive (it IS the bottleneck, this is supposed to happen all the time).</p> <p>I would either use an array (pre-allocated) or try to make my own C module to handle this.</p> <p>Anyone has better ideas for this kind of thing?</p> <p>(Note that the problem is always about multibyte encodings, and must be solved for UTF-8 as well),</p> <p>Oh and its Python 2.5, so no shiny Python 3 thingies are available here.</p> <p>Thanks</p>
4
2009-10-02T09:06:17Z
1,508,550
<p>Try to build the result with the <a href="http://docs.python.org/library/re.html" rel="nofollow"><code>re</code> module</a>. It will do the nasty concatenation under the hood, so performance should be OK. Example:</p> <pre><code> import re re.sub(r'(.)', r'\1-', u'Nissim') count = 1 def repl(m): global count s = m.group(1) + unicode(count) count += 1 return s re.sub(r'(.)', repl, u'Nissim') </code></pre>
2
2009-10-02T09:23:34Z
[ "python", "string" ]
fast string modification in python
1,508,464
<p>This is partially a theoretical question:</p> <p>I have a string (say UTF-8), and I need to modify it so that each character (not byte) becomes 2 characters, for instance:</p> <pre><code>"Nissim" becomes "N-i-s-s-i-m-" "01234" becomes "0a1b2c3d4e" </code></pre> <p>and so on. I would suspect that naive concatenation in a loop would be too expensive (it IS the bottleneck, this is supposed to happen all the time).</p> <p>I would either use an array (pre-allocated) or try to make my own C module to handle this.</p> <p>Anyone has better ideas for this kind of thing?</p> <p>(Note that the problem is always about multibyte encodings, and must be solved for UTF-8 as well),</p> <p>Oh and its Python 2.5, so no shiny Python 3 thingies are available here.</p> <p>Thanks</p>
4
2009-10-02T09:06:17Z
1,508,551
<p>this might be a python effective solution:</p> <pre><code>s1="Nissim" s2="------" s3=''.join([''.join(list(x)) for x in zip(s1,s2)]) </code></pre>
2
2009-10-02T09:24:39Z
[ "python", "string" ]
fast string modification in python
1,508,464
<p>This is partially a theoretical question:</p> <p>I have a string (say UTF-8), and I need to modify it so that each character (not byte) becomes 2 characters, for instance:</p> <pre><code>"Nissim" becomes "N-i-s-s-i-m-" "01234" becomes "0a1b2c3d4e" </code></pre> <p>and so on. I would suspect that naive concatenation in a loop would be too expensive (it IS the bottleneck, this is supposed to happen all the time).</p> <p>I would either use an array (pre-allocated) or try to make my own C module to handle this.</p> <p>Anyone has better ideas for this kind of thing?</p> <p>(Note that the problem is always about multibyte encodings, and must be solved for UTF-8 as well),</p> <p>Oh and its Python 2.5, so no shiny Python 3 thingies are available here.</p> <p>Thanks</p>
4
2009-10-02T09:06:17Z
1,508,858
<p>Use Reduce.</p> <pre><code>&gt;&gt;&gt; str = "Nissim" &gt;&gt;&gt; reduce(lambda x, y : x+y+'-', str, '') 'N-i-s-s-i-m-' </code></pre> <p>The same with numbers too as long as you know which char maps to which. [dict can be handy]</p> <pre><code>&gt;&gt;&gt; mapper = dict([(repr(i), chr(i+ord('a'))) for i in range(9)]) &gt;&gt;&gt; str1 = '0123' &gt;&gt;&gt; reduce(lambda x, y : x+y+mapper[y], str1, '') '0a1b2c3d' </code></pre>
0
2009-10-02T10:50:55Z
[ "python", "string" ]
fast string modification in python
1,508,464
<p>This is partially a theoretical question:</p> <p>I have a string (say UTF-8), and I need to modify it so that each character (not byte) becomes 2 characters, for instance:</p> <pre><code>"Nissim" becomes "N-i-s-s-i-m-" "01234" becomes "0a1b2c3d4e" </code></pre> <p>and so on. I would suspect that naive concatenation in a loop would be too expensive (it IS the bottleneck, this is supposed to happen all the time).</p> <p>I would either use an array (pre-allocated) or try to make my own C module to handle this.</p> <p>Anyone has better ideas for this kind of thing?</p> <p>(Note that the problem is always about multibyte encodings, and must be solved for UTF-8 as well),</p> <p>Oh and its Python 2.5, so no shiny Python 3 thingies are available here.</p> <p>Thanks</p>
4
2009-10-02T09:06:17Z
1,509,659
<p>here are my timings. Note, it's py3.1</p> <pre><code>&gt;&gt;&gt; s1 'Nissim' &gt;&gt;&gt; s2 = '-' * len(s1) &gt;&gt;&gt; timeit.timeit("''.join(i+j for i, j in zip(s1, s2))", "from __main__ import s1, s2") 3.5249209707199043 &gt;&gt;&gt; timeit.timeit("''.join(sum(map(list,zip(s1,s2)),[]))", "from __main__ import s1, s2") 5.903614027402 &gt;&gt;&gt; timeit.timeit("''.join([''.join(list(x)) for x in zip(s1,s2)])", "from __main__ import s1, s2") 6.04072124013328 &gt;&gt;&gt; timeit.timeit("''.join(i+'-' for i in s1)", "from __main__ import s1, s2") 2.484378367653335 &gt;&gt;&gt; timeit.timeit("reduce(lambda x, y : x+y+'-', s1, '')", "from __main__ import s1; from functools import reduce") 2.290644129319844 </code></pre>
1
2009-10-02T13:55:54Z
[ "python", "string" ]
fast string modification in python
1,508,464
<p>This is partially a theoretical question:</p> <p>I have a string (say UTF-8), and I need to modify it so that each character (not byte) becomes 2 characters, for instance:</p> <pre><code>"Nissim" becomes "N-i-s-s-i-m-" "01234" becomes "0a1b2c3d4e" </code></pre> <p>and so on. I would suspect that naive concatenation in a loop would be too expensive (it IS the bottleneck, this is supposed to happen all the time).</p> <p>I would either use an array (pre-allocated) or try to make my own C module to handle this.</p> <p>Anyone has better ideas for this kind of thing?</p> <p>(Note that the problem is always about multibyte encodings, and must be solved for UTF-8 as well),</p> <p>Oh and its Python 2.5, so no shiny Python 3 thingies are available here.</p> <p>Thanks</p>
4
2009-10-02T09:06:17Z
1,510,030
<pre><code>string="™¡™©€" unicode(string,"utf-8") s2='-'*len(s1) ''.join(sum(map(list,zip(s1,s2)),[])).encode("utf-8") </code></pre>
0
2009-10-02T14:54:20Z
[ "python", "string" ]
fast string modification in python
1,508,464
<p>This is partially a theoretical question:</p> <p>I have a string (say UTF-8), and I need to modify it so that each character (not byte) becomes 2 characters, for instance:</p> <pre><code>"Nissim" becomes "N-i-s-s-i-m-" "01234" becomes "0a1b2c3d4e" </code></pre> <p>and so on. I would suspect that naive concatenation in a loop would be too expensive (it IS the bottleneck, this is supposed to happen all the time).</p> <p>I would either use an array (pre-allocated) or try to make my own C module to handle this.</p> <p>Anyone has better ideas for this kind of thing?</p> <p>(Note that the problem is always about multibyte encodings, and must be solved for UTF-8 as well),</p> <p>Oh and its Python 2.5, so no shiny Python 3 thingies are available here.</p> <p>Thanks</p>
4
2009-10-02T09:06:17Z
1,510,511
<p>@gnosis, beware of all the well-intentioned responders saying you should measure the times: yes, you should (because programmers' instincts are often off-base about performance), <strong>but</strong> measuring a single case, as in all the <code>timeit</code> examples proffered so far, misses a crucial consideration -- <strong>big-O</strong>.</p> <p>Your instincts are correct: <em>in general</em> (with a very few special cases where recent Python releases can optimize things a bit, but they don't stretch very far), building a string by a loop of <code>+=</code> over the pieces (or a <code>reduce</code> and so on) must be <code>O(N**2)</code> due to the many intermediate object allocations and the inevitable repeated copying of those object's content; joining, regular expressions, and the third option that was not mentioned in the above answers (<code>write</code> method of <code>cStringIO.StringIO</code> instances) are the <code>O(N)</code> solutions and therefore the only ones worth considering unless you happen to <strong>know</strong> for sure that the strings you'll be operating on have modest upper bounds on their length.</p> <p>So what, if any, are the upper bounds in length on the strings you're processing? If you can give us an idea, benchmarks can be run on <em>representative</em> ranges of lengths of interest (for example, say, "most often less than 100 characters but some % of the time maybe a couple thousand characters" would be an excellent spec for this performance evaluation: IOW, it doesn't need to be extremely precise, just indicative of your problem space).</p> <p>I also notice that nobody seems to follow one crucial and difficult point in your specs: that the strings are Python 2.5 multibyte, UTF-8 encoded, <code>str</code>s, and the insertions must happen only after each "complete character", <em>not</em> after each <em>byte</em>. Everybody seems to be "looping on the str", which give each byte, not each <em>character</em> as you so clearly specify.</p> <p>There's really no good, fast way to "loop over characters" in a multibyte-encoded byte <code>str</code>; the best one can do is to <code>.decode('utf-8')</code>, giving a unicode object -- process the unicode object (where loops <em>do</em> correctly go over characters!), then <code>.encode</code> it back at the end. By far the best approach in general is to only, exclusively use unicode objects, <strong>not</strong> encoded <code>str</code>s, throughout the heart of your code; encode and decode to/from byte strings only upon I/O (if and when you must because you need to communicate with subsystems that only support byte strings and not proper Unicode).</p> <p>So I would strongly suggest that you consider this "best approach" and restructure your code accordingly: unicode everywhere, except at the boundaries where it may be encoded/decoded if and when necessary only. For the "processing" part, you'll be MUCH happier with unicode objects than you would be lugging around balky multibyte-encoded strings!-)</p> <p><strong>Edit</strong>: forgot to comment on a possible approach you mention -- <code>array.array</code>. That's indeed O(N) <em>if</em> you are only <em>appending</em> to the end of the new array you're constructing (some appends will make the array grow beyond previously allocated capacity and therefore require a reallocation and copying of data, <strong>but</strong>, just like for list, a midly exponential overallocation strategy allows <code>append</code> to be <em>amortized</em> O(1), and therefore N appends to be O(N)).</p> <p>However, to build an array (again, just like a list) by repeated <code>insert</code> operations in the middle of it is <code>O(N**2)</code>, because each of the O(N) insertions must shift all the O(N) following items (assuming the number of previously existing items and the number of newly inserted ones are proportional to each other, as seems to be the case for your specific requirements).</p> <p>So, an <code>array.array('u')</code>, with repeated <code>append</code>s to it (<strong>not</strong> <code>insert</code>s!-), is a fourth O(N) approach that can solve your problem (in addition to the three I already mentioned: <code>join</code>, <code>re</code>, and <code>cStringIO</code>) -- <em>those</em> are the ones worth benchmarking once you clarify the ranges of lengths that are of interest, as I mentioned above.</p>
9
2009-10-02T16:12:59Z
[ "python", "string" ]
Log exception with traceback
1,508,467
<p>How can I log my Python errors?</p> <pre><code>try: do_something() except: # How can I log my exception here, complete with its traceback? </code></pre>
56
2009-10-02T09:07:15Z
1,508,485
<p>Heres a simple example taken from the <a href="http://docs.python.org/library/logging.html" rel="nofollow">python 2.6 documentation</a>:</p> <pre><code>import logging LOG_FILENAME = '/tmp/logging_example.out' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,) logging.debug('This message should go to the log file') </code></pre>
-1
2009-10-02T09:10:58Z
[ "python", "exception", "logging", "error-handling" ]
Log exception with traceback
1,508,467
<p>How can I log my Python errors?</p> <pre><code>try: do_something() except: # How can I log my exception here, complete with its traceback? </code></pre>
56
2009-10-02T09:07:15Z
1,508,761
<p>Use <a href="https://docs.python.org/library/logging.html#logging.exception"><code>logging.exception</code></a> from with an <code>except:</code> handler to log the current exception, prepended with a message.</p> <pre><code>import logging LOG_FILENAME = '/tmp/logging_example.out' logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG) logging.debug('This message should go to the log file') try: run_my_stuff() except: logging.exception('Got exception on main handler') raise </code></pre> <p>Now looking at the log file, <code>/tmp/logging_example.out</code>:</p> <pre><code>DEBUG:root:This message should go to the log file ERROR:root:Got exception on main handler Traceback (most recent call last): File "/tmp/teste.py", line 9, in &lt;module&gt; run_my_stuff() NameError: name 'run_my_stuff' is not defined </code></pre>
84
2009-10-02T10:24:09Z
[ "python", "exception", "logging", "error-handling" ]
Log exception with traceback
1,508,467
<p>How can I log my Python errors?</p> <pre><code>try: do_something() except: # How can I log my exception here, complete with its traceback? </code></pre>
56
2009-10-02T09:07:15Z
9,929,970
<p>My job recently tasked me with logging all the tracebacks/exceptions from our application. I tried numerous techniques that others had posted online such as the one above but settled on a different approach. Overriding <code>traceback.print_exception</code>. </p> <p>I have a write up at <a href="http://www.bbarrows.com/blog/2012/09/24/implementing-exception-logging-in-python/">http://www.bbarrows.com/</a> That would be much easier to read but Ill paste it in here as well.</p> <p>When tasked with logging all the exceptions that our software might encounter in the wild I tried a number of different techniques to log our python exception tracebacks. At first I thought that the python system exception hook, sys.excepthook would be the perfect place to insert the logging code. I was trying something similar to:</p> <pre><code>import traceback import StringIO import logging import os, sys def my_excepthook(excType, excValue, traceback, logger=logger): logger.error("Logging an uncaught exception", exc_info=(excType, excValue, traceback)) sys.excepthook = my_excepthook </code></pre> <p>This worked for the main thread but I soon found that the my sys.excepthook would not exist across any new threads my process started. This is a huge issue because most everything happens in threads in this project.</p> <p>After googling and reading plenty of documentation the most helpful information I found was from the Python Issue tracker.</p> <p>The first post on the thread shows a working example of the <code>sys.excepthook</code> NOT persisting across threads (as shown below). Apparently this is expected behavior.</p> <pre><code>import sys, threading def log_exception(*args): print 'got exception %s' % (args,) sys.excepthook = log_exception def foo(): a = 1 / 0 threading.Thread(target=foo).start() </code></pre> <p>The messages on this Python Issue thread really result in 2 suggested hacks. Either subclass <code>Thread</code> and wrap the run method in our own try except block in order to catch and log exceptions or monkey patch <code>threading.Thread.run</code> to run in your own try except block and log the exceptions.</p> <p>The first method of subclassing <code>Thread</code> seems to me to be less elegant in your code as you would have to import and use your custom <code>Thread</code> class EVERYWHERE you wanted to have a logging thread. This ended up being a hassle because I had to search our entire code base and replace all normal <code>Threads</code> with this custom <code>Thread</code>. However, it was clear as to what this <code>Thread</code> was doing and would be easier for someone to diagnose and debug if something went wrong with the custom logging code. A custome logging thread might look like this:</p> <pre><code>class TracebackLoggingThread(threading.Thread): def run(self): try: super(TracebackLoggingThread, self).run() except (KeyboardInterrupt, SystemExit): raise except Exception, e: logger = logging.getLogger('') logger.exception("Logging an uncaught exception") </code></pre> <p>The second method of monkey patching <code>threading.Thread.run</code> is nice because I could just run it once right after <code>__main__</code> and instrument my logging code in all exceptions. Monkey patching can be annoying to debug though as it changes the expected functionality of something. The suggested patch from the Python Issue tracker was:</p> <pre><code>def installThreadExcepthook(): """ Workaround for sys.excepthook thread bug From http://spyced.blogspot.com/2007/06/workaround-for-sysexcepthook-bug.html (https://sourceforge.net/tracker/?func=detail&amp;atid=105470&amp;aid=1230540&amp;group_id=5470). Call once from __main__ before creating any threads. If using psyco, call psyco.cannotcompile(threading.Thread.run) since this replaces a new-style class method. """ init_old = threading.Thread.__init__ def init(self, *args, **kwargs): init_old(self, *args, **kwargs) run_old = self.run def run_with_except_hook(*args, **kw): try: run_old(*args, **kw) except (KeyboardInterrupt, SystemExit): raise except: sys.excepthook(*sys.exc_info()) self.run = run_with_except_hook threading.Thread.__init__ = init </code></pre> <p>It was not until I started testing my exception logging I realized that I was going about it all wrong.</p> <p>To test I had placed a</p> <pre><code>raise Exception("Test") </code></pre> <p>somewhere in my code. However, wrapping a a method that called this method was a try except block that printed out the traceback and swallowed the exception. This was very frustrating because I saw the traceback bring printed to STDOUT but not being logged. It was I then decided that a much easier method of logging the tracebacks was just to monkey patch the method that all python code uses to print the tracebacks themselves, traceback.print_exception. I ended up with something similar to the following:</p> <pre><code>def add_custom_print_exception(): old_print_exception = traceback.print_exception def custom_print_exception(etype, value, tb, limit=None, file=None): tb_output = StringIO.StringIO() traceback.print_tb(tb, limit, tb_output) logger = logging.getLogger('customLogger') logger.error(tb_output.getvalue()) tb_output.close() old_print_exception(etype, value, tb, limit=None, file=None) traceback.print_exception = custom_print_exception </code></pre> <p>This code writes the traceback to a String Buffer and logs it to logging ERROR. I have a custom logging handler set up the 'customLogger' logger which takes the ERROR level logs and send them home for analysis.</p>
31
2012-03-29T16:58:57Z
[ "python", "exception", "logging", "error-handling" ]
Log exception with traceback
1,508,467
<p>How can I log my Python errors?</p> <pre><code>try: do_something() except: # How can I log my exception here, complete with its traceback? </code></pre>
56
2009-10-02T09:07:15Z
11,844,359
<p>maybe not as stylish, but easier:</p> <pre><code>#!/bin/bash log="/var/log/yourlog" /path/to/your/script.py 2&gt;&amp;1 | (while read; do echo "$REPLY" &gt;&gt; $log; done) </code></pre>
-1
2012-08-07T10:52:20Z
[ "python", "exception", "logging", "error-handling" ]
Log exception with traceback
1,508,467
<p>How can I log my Python errors?</p> <pre><code>try: do_something() except: # How can I log my exception here, complete with its traceback? </code></pre>
56
2009-10-02T09:07:15Z
29,556,246
<p>Use exc_info options may be better, remains warning or error title: </p> <pre><code>try: # coode in here except Exception, e: logging.error(e, exc_info=True) </code></pre>
16
2015-04-10T08:00:52Z
[ "python", "exception", "logging", "error-handling" ]
Log exception with traceback
1,508,467
<p>How can I log my Python errors?</p> <pre><code>try: do_something() except: # How can I log my exception here, complete with its traceback? </code></pre>
56
2009-10-02T09:07:15Z
36,633,733
<p>Uncaught exception messages go to STDERR, so instead of implementing your logging in Python itself you could send STDERR to a file using whatever shell you're using to run your Python script. In a Bash script, you can do this with output redirection, as <a href="http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html" rel="nofollow">described in the BASH guide</a>.</p> <h3>Examples</h3> <p>Append errors to file, other output to the terminal:</p> <pre><code>./test.py 2&gt;&gt; mylog.log </code></pre> <p>Overwrite file with interleaved STDOUT and STDERR output:</p> <pre><code>./test.py &amp;&gt; mylog.log </code></pre>
0
2016-04-14T20:50:28Z
[ "python", "exception", "logging", "error-handling" ]
Log exception with traceback
1,508,467
<p>How can I log my Python errors?</p> <pre><code>try: do_something() except: # How can I log my exception here, complete with its traceback? </code></pre>
56
2009-10-02T09:07:15Z
36,635,362
<p>You can log all uncaught exceptions on the main thread by assigning a handler to <a href="https://docs.python.org/library/sys.html#sys.excepthook" rel="nofollow"><code>sys.excepthook</code></a>, perhaps using the <a href="https://docs.python.org/3/library/logging.html#logging.debug" rel="nofollow"><code>exc_info</code> parameter of Python's logging functions</a>:</p> <pre><code>import sys import logging logging.basicConfig(filename='/tmp/foobar.log') def exception_hook(exc_type, exc_value, exc_traceback): logging.error( "Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback) ) sys.excepthook = exception_hook raise Exception('Boom') </code></pre> <p>If your program uses threads, however, then note that threads created using <a href="https://docs.python.org/2/library/threading.html#thread-objects" rel="nofollow"><code>threading.Thread</code></a> will <em>not</em> trigger <code>sys.excepthook</code> when an uncaught exception occurs inside them, as noted in <a href="http://bugs.python.org/issue1230540" rel="nofollow">Issue 1230540</a> on Python's issue tracker. Some hacks have been suggested there to work around this limitation, like monkey-patching <code>Thread.__init__</code> to overwrite <code>self.run</code> with an alternative <code>run</code> method that wraps the original in a <code>try</code> block and calls <code>sys.excepthook</code> from inside the <code>except</code> block. Alternatively, you could just manually wrap the entry point for each of your threads in <code>try</code>/<code>except</code> yourself.</p>
0
2016-04-14T22:51:04Z
[ "python", "exception", "logging", "error-handling" ]
Is there anything like Project Sprouts but implemented in Python?
1,508,743
<p>Since our entire build system is written in Python, I'm wondering if there is anything like <a href="http://projectsprouts.org/" rel="nofollow">Sprouts</a> that I could leverage to integrate Flex builds / development into our codebase? </p> <p>Sprouts looks nice and all, but I don't want to introduce another build-time dependency to our projects (namely Ruby).</p> <p>Thanks</p>
1
2009-10-02T10:17:56Z
1,509,678
<p>No, I don't believe there is anything similar for Python.</p> <p>It looks like Sprouts is made up of a lot of <a href="http://rake.rubyforge.org/" rel="nofollow">Rake</a> build files, so you could try to roll your own build system in Python using tools like <a href="http://www.blueskyonmars.com/projects/paver/" rel="nofollow">Paver</a>, <a href="http://docs.fabfile.org/0.9/" rel="nofollow">fabric</a>, <a href="http://www.buildout.org/docs/index.html" rel="nofollow">Buildout</a> recipes, <a href="http://pythonpaste.org/script/developer.html#templates" rel="nofollow">paster templates</a>, etc. That would give you the ability to generate new projects like Sprouts does.</p> <p>Overall I wouldn't worry too much about adding Ruby as a dependency. If it does what you need then you'll save a lot of time by using it instead of hunting for something written in Python (or worse yet rewriting its functionality).</p>
3
2009-10-02T13:58:17Z
[ "python", "ruby", "flex" ]
python 2.6 or python 3.1?
1,508,906
<p>I am about to learn Python and was wondering what is recommended, learning python 2.6 or 3.1? (any tips on learning python is welcomed as well =)</p> <p><hr /></p> <p>edit: Is the difference really big between the two? If I learn python 2 will i have trouble learning python 3?</p>
6
2009-10-02T11:03:38Z
1,508,919
<p>You really want to stick with the later version. Python 2.6 and the rest of the 2.x versions that come out are really for compatibility. However, this is not true if you want to use a framework like Django right away because it is incompatible with the 3.x series at the moment.</p> <p>A tip for learning Python? Just start using it and find online documentation for it. I feel it's an easy (and awesome) language to pick up.</p>
5
2009-10-02T11:08:53Z
[ "python" ]
python 2.6 or python 3.1?
1,508,906
<p>I am about to learn Python and was wondering what is recommended, learning python 2.6 or 3.1? (any tips on learning python is welcomed as well =)</p> <p><hr /></p> <p>edit: Is the difference really big between the two? If I learn python 2 will i have trouble learning python 3?</p>
6
2009-10-02T11:03:38Z
1,508,921
<p>If you're looking to learn python: <a href="http://diveintopython3.org/" rel="nofollow">http://diveintopython3.org/</a> was recently finished and can be read completely free online or you can buy the hardcopy. It's a great tutorial and introduction to the language.</p>
4
2009-10-02T11:10:34Z
[ "python" ]
python 2.6 or python 3.1?
1,508,906
<p>I am about to learn Python and was wondering what is recommended, learning python 2.6 or 3.1? (any tips on learning python is welcomed as well =)</p> <p><hr /></p> <p>edit: Is the difference really big between the two? If I learn python 2 will i have trouble learning python 3?</p>
6
2009-10-02T11:03:38Z
1,508,929
<p>I would go with 2.6 for a couple of reasons.</p> <ol> <li><p>There's so much more material (books, examples, etc) based on 2.6. Some things might not work under 3.x, and you'll be able to get some good second-hand deals on 2.4-6 books.</p></li> <li><p>The majority of libraries you'll want to pull in are still aimed at 2.6. This will change in time, but 2.6 support won't vanish overnight. Far from it. Linux distributions (that have a lot tied into python) aren't planning to move on for at least another year, so you're safe!</p></li> </ol>
10
2009-10-02T11:12:05Z
[ "python" ]
python 2.6 or python 3.1?
1,508,906
<p>I am about to learn Python and was wondering what is recommended, learning python 2.6 or 3.1? (any tips on learning python is welcomed as well =)</p> <p><hr /></p> <p>edit: Is the difference really big between the two? If I learn python 2 will i have trouble learning python 3?</p>
6
2009-10-02T11:03:38Z
1,508,931
<p>If you want to use existing libraries and modules written in C/C++ or use SWIG, you'll have to use python2, otherwise I don't really see a reason to stick with python2.</p>
-1
2009-10-02T11:12:56Z
[ "python" ]
python 2.6 or python 3.1?
1,508,906
<p>I am about to learn Python and was wondering what is recommended, learning python 2.6 or 3.1? (any tips on learning python is welcomed as well =)</p> <p><hr /></p> <p>edit: Is the difference really big between the two? If I learn python 2 will i have trouble learning python 3?</p>
6
2009-10-02T11:03:38Z
1,509,018
<ul> <li>If you're looking to <strong>develop software right now</strong> stick with Python 2.6. </li> <li>If you're looking to <strong>learn the language and experiment</strong> go with Python 3.1.</li> </ul> <p>Python 3.1 doesn't have the same library support (yet!) as Python 2.6, so you'll encounter difficulties working with existing software projects. If you're not pressed to produce a working product at this very moment, I'd suggest trying out Python 3.1. And there is no better place to start than <a href="http://diveintopython3.org" rel="nofollow">Dive Into Python 3</a>, as has been mentioned by Clint. Good luck!</p> <p>UPDATE 2011-2-27: I'd say that support for Python 3 is improving constantly and you might want to check and see if your project can't be done with Python 3. There's a website devoted to tracking support for Python 3: <a href="http://getpython3.com/" rel="nofollow">http://getpython3.net/</a></p>
15
2009-10-02T11:37:37Z
[ "python" ]
python 2.6 or python 3.1?
1,508,906
<p>I am about to learn Python and was wondering what is recommended, learning python 2.6 or 3.1? (any tips on learning python is welcomed as well =)</p> <p><hr /></p> <p>edit: Is the difference really big between the two? If I learn python 2 will i have trouble learning python 3?</p>
6
2009-10-02T11:03:38Z
1,509,308
<p>You would want to go with 2.6 today.</p> <p>Why? Because there is no library support for 3.1. We've just finished porting setuptools (under the name Distribute) to Python 3, so hopefully library support for Python 3 will increase dramatically during the next year, but it's not there yet.</p> <p>And it's not so hard to switch. It's not like it's a whole new language, like some Python critics make it sound like. So if you start with Python 3, it's no disaster either. It's just that it's going to be hard to actually be productive in Python 3 at the moment. So go with 2.6.</p>
5
2009-10-02T12:47:33Z
[ "python" ]
python 2.6 or python 3.1?
1,508,906
<p>I am about to learn Python and was wondering what is recommended, learning python 2.6 or 3.1? (any tips on learning python is welcomed as well =)</p> <p><hr /></p> <p>edit: Is the difference really big between the two? If I learn python 2 will i have trouble learning python 3?</p>
6
2009-10-02T11:03:38Z
1,509,378
<p>As for tips on learning Python, I would work through the main tutorial (<a href="http://docs.python.org/3.1/tutorial/" rel="nofollow">http://docs.python.org/3.1/tutorial/</a>) and then explore the Beginner's Guide. O'Reilly's Learning Python is pretty handy if you prefer using a book.</p>
0
2009-10-02T13:06:25Z
[ "python" ]
Parsing large pseudo-xml files in python
1,508,938
<p>I'm trying to parse* a large file (> 5GB) of structured markup data. The data format is essentially XML but there is no explicit root element. What's the most efficient way to do that?</p> <p>The problem with SAX parsers is that they require a root element, so either I've to add a pseudo element to the data stream (is there an equivalent to Java's SequenceInputStream in Python?) or I've to switch to a non-SAX conform event-based parser (is there a successor of sgmllib?)</p> <p>The structure of the data is quite simple. Basically a listing of elements: </p> <pre><code>&lt;Document&gt; &lt;docid&gt;1&lt;/docid&gt; &lt;text&gt;foo&lt;/text&gt; &lt;/Document&gt; &lt;Document&gt; &lt;docid&gt;2&lt;/docid&gt; &lt;text&gt;bar&lt;/text&gt; &lt;/Document&gt; </code></pre> <p>*actually to iterate</p>
4
2009-10-02T11:15:49Z
1,508,976
<p><a href="http://docs.python.org/library/xml.sax.html" rel="nofollow">http://docs.python.org/library/xml.sax.html</a></p> <p>Note, that you can pass a 'stream' object to <code>xml.sax.parse</code>. This means you can probably pass any object that has file-like methods (like <code>read</code>) to the <code>parse</code> call... Make your own object, which will firstly put your virtual root start-tag, then the contents of file, then virtual root end-tag. I guess that you only need to implement <code>read</code> method... but this might depend on the sax parser you'll use.</p> <p>Example that works for me:</p> <pre><code>import xml.sax import xml.sax.handler class PseudoStream(object): def read_iterator(self): yield '&lt;foo&gt;' yield '&lt;bar&gt;' for line in open('test.xml'): yield line yield '&lt;/bar&gt;' yield '&lt;/foo&gt;' def __init__(self): self.ri = self.read_iterator() def read(self, *foo): try: return self.ri.next() except StopIteration: return '' class SAXHandler(xml.sax.handler.ContentHandler): def startElement(self, name, attrs): print name, attrs d = xml.sax.parse(PseudoStream(), SAXHandler()) </code></pre>
10
2009-10-02T11:26:55Z
[ "python", "xml" ]
Parsing large pseudo-xml files in python
1,508,938
<p>I'm trying to parse* a large file (> 5GB) of structured markup data. The data format is essentially XML but there is no explicit root element. What's the most efficient way to do that?</p> <p>The problem with SAX parsers is that they require a root element, so either I've to add a pseudo element to the data stream (is there an equivalent to Java's SequenceInputStream in Python?) or I've to switch to a non-SAX conform event-based parser (is there a successor of sgmllib?)</p> <p>The structure of the data is quite simple. Basically a listing of elements: </p> <pre><code>&lt;Document&gt; &lt;docid&gt;1&lt;/docid&gt; &lt;text&gt;foo&lt;/text&gt; &lt;/Document&gt; &lt;Document&gt; &lt;docid&gt;2&lt;/docid&gt; &lt;text&gt;bar&lt;/text&gt; &lt;/Document&gt; </code></pre> <p>*actually to iterate</p>
4
2009-10-02T11:15:49Z
1,509,024
<p>The quick and dirty answer would be adding a root element (as String) so it would be a valid XML.</p> <p>Regards.</p>
1
2009-10-02T11:39:00Z
[ "python", "xml" ]
Parsing large pseudo-xml files in python
1,508,938
<p>I'm trying to parse* a large file (> 5GB) of structured markup data. The data format is essentially XML but there is no explicit root element. What's the most efficient way to do that?</p> <p>The problem with SAX parsers is that they require a root element, so either I've to add a pseudo element to the data stream (is there an equivalent to Java's SequenceInputStream in Python?) or I've to switch to a non-SAX conform event-based parser (is there a successor of sgmllib?)</p> <p>The structure of the data is quite simple. Basically a listing of elements: </p> <pre><code>&lt;Document&gt; &lt;docid&gt;1&lt;/docid&gt; &lt;text&gt;foo&lt;/text&gt; &lt;/Document&gt; &lt;Document&gt; &lt;docid&gt;2&lt;/docid&gt; &lt;text&gt;bar&lt;/text&gt; &lt;/Document&gt; </code></pre> <p>*actually to iterate</p>
4
2009-10-02T11:15:49Z
1,510,957
<p>Add root element and use SAX, STax or VTD-XML ..</p>
1
2009-10-02T17:49:17Z
[ "python", "xml" ]
Parsing large pseudo-xml files in python
1,508,938
<p>I'm trying to parse* a large file (> 5GB) of structured markup data. The data format is essentially XML but there is no explicit root element. What's the most efficient way to do that?</p> <p>The problem with SAX parsers is that they require a root element, so either I've to add a pseudo element to the data stream (is there an equivalent to Java's SequenceInputStream in Python?) or I've to switch to a non-SAX conform event-based parser (is there a successor of sgmllib?)</p> <p>The structure of the data is quite simple. Basically a listing of elements: </p> <pre><code>&lt;Document&gt; &lt;docid&gt;1&lt;/docid&gt; &lt;text&gt;foo&lt;/text&gt; &lt;/Document&gt; &lt;Document&gt; &lt;docid&gt;2&lt;/docid&gt; &lt;text&gt;bar&lt;/text&gt; &lt;/Document&gt; </code></pre> <p>*actually to iterate</p>
4
2009-10-02T11:15:49Z
1,511,070
<p>xml.parsers.expat -- Fast XML parsing using Expat The xml.parsers.expat module is a Python interface to the Expat non-validating XML parser. The module provides a single extension type, xmlparser, that represents the current state of an XML parser. After an xmlparser object has been created, various attributes of the object can be set to handler functions. When an XML document is then fed to the parser, the handler functions are called for the character data and markup in the XML document.</p> <p>More info : <a href="http://www.python.org/doc/2.5/lib/module-xml.parsers.expat.html" rel="nofollow">http://www.python.org/doc/2.5/lib/module-xml.parsers.expat.html</a></p>
0
2009-10-02T18:17:01Z
[ "python", "xml" ]
KeyError with dict.fromkeys() and dict-like object
1,509,153
<p>In Python, you can use a dictionary as the first argument to <code>dict.fromkeys()</code>, e.g.:</p> <pre><code>In [1]: d = {'a': 1, 'b': 2} In [2]: dict.fromkeys(d) Out[2]: {'a': None, 'b': None} </code></pre> <p>I tried to do the same with a dict-like object, but that always raises a <code>KeyError</code>, e.g.:</p> <pre><code>In [1]: class SemiDict: ...: def __init__(self): ...: self.d = {} ...: ...: def __getitem__(self, key): ...: return self.d[key] ...: ...: def __setitem__(self, key, value): ...: self.d[key] = value ...: ...: In [2]: sd = SemiDict() In [3]: sd['a'] = 1 In [4]: dict.fromkeys(sd) --------------------------------------------------------------------------- KeyError Traceback (most recent call last) C:\bin\Console2\&lt;ipython console&gt; in &lt;module&gt;() C:\bin\Console2\&lt;ipython console&gt; in __getitem__(self, key) KeyError: 0 </code></pre> <p>What exactly is happening here? And can it be resolved, other than using something like <code>dict.fromkeys(sd.d)</code>?</p>
3
2009-10-02T12:09:48Z
1,509,183
<p>instance of <code>SemiDict</code> is not a sequence. I'd imagine the most obvious solution would be to inherit from <code>dict</code>, why don't you do it?</p>
1
2009-10-02T12:14:51Z
[ "python", "dictionary" ]
KeyError with dict.fromkeys() and dict-like object
1,509,153
<p>In Python, you can use a dictionary as the first argument to <code>dict.fromkeys()</code>, e.g.:</p> <pre><code>In [1]: d = {'a': 1, 'b': 2} In [2]: dict.fromkeys(d) Out[2]: {'a': None, 'b': None} </code></pre> <p>I tried to do the same with a dict-like object, but that always raises a <code>KeyError</code>, e.g.:</p> <pre><code>In [1]: class SemiDict: ...: def __init__(self): ...: self.d = {} ...: ...: def __getitem__(self, key): ...: return self.d[key] ...: ...: def __setitem__(self, key, value): ...: self.d[key] = value ...: ...: In [2]: sd = SemiDict() In [3]: sd['a'] = 1 In [4]: dict.fromkeys(sd) --------------------------------------------------------------------------- KeyError Traceback (most recent call last) C:\bin\Console2\&lt;ipython console&gt; in &lt;module&gt;() C:\bin\Console2\&lt;ipython console&gt; in __getitem__(self, key) KeyError: 0 </code></pre> <p>What exactly is happening here? And can it be resolved, other than using something like <code>dict.fromkeys(sd.d)</code>?</p>
3
2009-10-02T12:09:48Z
1,509,208
<p>To create the dict, <code>fromkeys</code> iterates over its argument. So it must be an iterator. One way to make it work is to add an <code>__iter__</code> method to your <code>dict</code>-like:</p> <pre><code>def __iter__(self): return iter(self.d) </code></pre>
6
2009-10-02T12:23:33Z
[ "python", "dictionary" ]
How to search XPath inside Python ClientForm object?
1,509,404
<p>I've got a form, returned by Python mechanize Browser and got via forms() method. How can I perform XPath search inside form node, that is, among descendant nodes of the HTML form node? TIA</p> <p>Upd: How to save html code of the form?</p>
0
2009-10-02T13:10:26Z
1,509,434
<p>By parsing the browser contents with lxml, which has xpath support.</p>
1
2009-10-02T13:15:43Z
[ "python", "mechanize" ]
Zero results in Query/GqlQuery
1,509,407
<p>How do I know if the results of my query either using the Query interface or the GqlQuery interface returned zero results? Would using <code>.get()</code> on zero results produce an error? If yes, what's the best way to handle it?</p>
2
2009-10-02T13:11:01Z
1,509,421
<p>when doing a get() if there are no results you will have an object containing None</p> <p>I normally do </p> <pre><code>result = query.get() if result is None: #do the following </code></pre> <p>or if you want to check that its not none then</p> <pre><code>if result is not None: #do the following </code></pre>
5
2009-10-02T13:14:09Z
[ "python", "google-app-engine", "gql", "gqlquery", "queryinterface" ]
Zero results in Query/GqlQuery
1,509,407
<p>How do I know if the results of my query either using the Query interface or the GqlQuery interface returned zero results? Would using <code>.get()</code> on zero results produce an error? If yes, what's the best way to handle it?</p>
2
2009-10-02T13:11:01Z
1,543,842
<p>if a query returns no results, <code>fetch()</code> returns an empty list <code>[]</code> and <code>get()</code> returns <code>None</code></p> <p>in either case you can use the following:</p> <pre><code>if result: #handle the result else: #no results were returned </code></pre>
2
2009-10-09T13:41:57Z
[ "python", "google-app-engine", "gql", "gqlquery", "queryinterface" ]
RESTful APIs in Django for GETTING information from a server
1,509,621
<p>Any idea of a RESTful APIs in Django for GETTING information from a server?</p> <p>What I want to do is fetch the errors from the server into a database. </p> <p>For example:</p> <p>The Live server has examplewebsite.com, any thing goes wrong with that website should POST the error, where the Django app GET the errors and insert them into the database.</p>
1
2009-10-02T13:50:19Z
1,509,650
<p>Are you just trying to fetch data over HTTP? If so, what about <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a>?</p>
0
2009-10-02T13:54:35Z
[ "python", "django", "rest", "api" ]
RESTful APIs in Django for GETTING information from a server
1,509,621
<p>Any idea of a RESTful APIs in Django for GETTING information from a server?</p> <p>What I want to do is fetch the errors from the server into a database. </p> <p>For example:</p> <p>The Live server has examplewebsite.com, any thing goes wrong with that website should POST the error, where the Django app GET the errors and insert them into the database.</p>
1
2009-10-02T13:50:19Z
1,510,582
<p>Take a look at <a href="http://bitbucket.org/jespern/django-piston/wiki/Home" rel="nofollow">Piston</a>, which calls itself a 'mini-framework for Django for creating RESTful APIs.'</p>
2
2009-10-02T16:24:06Z
[ "python", "django", "rest", "api" ]
Catch contents of PHP session under Apache with Python (mod_wsgi)?
1,509,641
<p>Is there a way to catch the contents of the PHP session variable <code>$_SESSION['user_id']</code> with a <code>mod_wsgi</code> Python script? I'm running a script in the background that will decide whether or not the user may proceed to view the document.</p> <p>I would like to do something like this:</p> <pre><code>def allow_access(environ, host): allow_access = False if environ['SCRIPT_NAME'] == 'forbidden_dir': if session['user_id'] == '1': allow_access = True if allow_access: return True else: return False </code></pre> <p>Is it possible?</p>
0
2009-10-02T13:53:44Z
1,509,778
<p>If it's possible, it's not easy; apache stores session variables in files in a special format.</p> <p>Your best option might be to write a php page that prints all session variables. (Hard-code it to only serve to localhost.) Open the url to that page from within your python script. Add a header to the url request with the session info. Then, once the php page is loaded in Python, parse the input.</p>
3
2009-10-02T14:14:07Z
[ "python", "apache", "mod-wsgi" ]
Catch contents of PHP session under Apache with Python (mod_wsgi)?
1,509,641
<p>Is there a way to catch the contents of the PHP session variable <code>$_SESSION['user_id']</code> with a <code>mod_wsgi</code> Python script? I'm running a script in the background that will decide whether or not the user may proceed to view the document.</p> <p>I would like to do something like this:</p> <pre><code>def allow_access(environ, host): allow_access = False if environ['SCRIPT_NAME'] == 'forbidden_dir': if session['user_id'] == '1': allow_access = True if allow_access: return True else: return False </code></pre> <p>Is it possible?</p>
0
2009-10-02T13:53:44Z
1,509,807
<p>please don't do this:</p> <pre><code>if allow_access: return True else: return False </code></pre> <p>when you can do: <code>return allow_access</code>.</p>
2
2009-10-02T14:19:11Z
[ "python", "apache", "mod-wsgi" ]
Compound UniqueConstraint with a function
1,510,018
<p><br /> A quick SQLAlchemy question... </p> <p>I have a class "Document" with attributes "Number" and "Date". I need to ensure that there's no duplicated number <em>for the same year</em>, is there a way to have a UniqueConstraint on "Number + year(Date)"? Should I use a unique Index instead? How would I declare the functional part?</p> <p>(SQLAlchemy 0.5.5, PostgreSQL 8.3.4)</p> <p>Thanks in advance!</p>
3
2009-10-02T14:52:57Z
1,510,137
<p>I'm pretty sure that unique constraints can only be applied on columns that already have data in them, and not on runtime-calculated expressions. Hence, you would need to create an extra column which contains the <code>year</code> part of your <code>date</code>, over which you could create a unique constraint together with <code>number</code>. To best use this approach, maybe you should store your <code>date</code> split up in three separate columns containing the day, month and year part. This could be done using default constraints in the table definition.</p>
0
2009-10-02T15:08:51Z
[ "python", "sqlalchemy", "constraints" ]
Compound UniqueConstraint with a function
1,510,018
<p><br /> A quick SQLAlchemy question... </p> <p>I have a class "Document" with attributes "Number" and "Date". I need to ensure that there's no duplicated number <em>for the same year</em>, is there a way to have a UniqueConstraint on "Number + year(Date)"? Should I use a unique Index instead? How would I declare the functional part?</p> <p>(SQLAlchemy 0.5.5, PostgreSQL 8.3.4)</p> <p>Thanks in advance!</p>
3
2009-10-02T14:52:57Z
1,517,153
<p>You should use a functional unique index to apply this constraint. Unfortunately the database generic database independent schema definition machinery in SQLAlchemy doesn't abstract functional indexes yet. You'll have to use the DDL construct to register custom schema definition clauses. If you are using the declarative approach to declaring your schema add the following after your class definition:</p> <pre><code>DDL( "CREATE UNIQUE INDEX doc_year_num_uniq ON %(fullname)s " "(EXTRACT(YEAR FROM date), number)" ).execute_at('after-create', Document.__table__) </code></pre> <p>This method works very nicely but throws a SADeprecation warning in v0.7 The syntax that I've used successfully:</p> <pre><code>from sqlalchemy import event event.listen(ModelObject.__table__, 'after_create', DDL("CREATE UNIQUE INDEX term_year ON %(fullname)s " "(EXTRACT(YEAR FROM start_date), term)", on = 'postgresql' ) ) </code></pre>
3
2009-10-04T19:11:39Z
[ "python", "sqlalchemy", "constraints" ]
Is there any framework like RoR on Python 3000?
1,510,084
<p>One of the feature I like in RoR is the db management, it can hide all the sql statement, also, it is very easy to change different db in RoR, is there any similar framework in Python 3000?</p>
1
2009-10-02T15:01:41Z
1,510,161
<p>There's Django but <a href="http://docs.djangoproject.com/en/dev/faq/install/#can-i-use-django-with-python-3-0" rel="nofollow">it works with Python 2.3+ only for now</a>.</p>
-1
2009-10-02T15:13:40Z
[ "python", "ruby-on-rails", "frameworks", "python-3.x" ]
Is there any framework like RoR on Python 3000?
1,510,084
<p>One of the feature I like in RoR is the db management, it can hide all the sql statement, also, it is very easy to change different db in RoR, is there any similar framework in Python 3000?</p>
1
2009-10-02T15:01:41Z
1,510,214
<p>This answer was awfully outdated. The current state of afairs is:</p> <ul> <li><a href="https://www.djangoproject.com/weblog/2012/mar/13/py3k/" rel="nofollow">Django is close to supporting Python 3</a></li> <li><a href="http://www.cherrypy.org/" rel="nofollow">CherryPy</a> <a href="http://www.cherrypy.org/wiki/WhatsNewIn32" rel="nofollow">supports Python 3 since version 3.2</a></li> <li><a href="http://www.pylonsproject.org/" rel="nofollow">Pyramid</a> has <a href="http://docs.pylonsproject.org/projects/pyramid/en/1.3-branch/whatsnew-1.3.html" rel="nofollow">Python 3 support since 1.3</a></li> <li><a href="http://bottlepy.org/docs/dev/" rel="nofollow">Bottle</a>, which is a lightweight WSGI micro web-framework, supports Python 3</li> </ul> <p>I'm sure this list will keep growing every coming month, specially considering that <a href="http://www.python.org/dev/peps/pep-0404/" rel="nofollow">there will never be a Python 2.8</a>.</p> <p>2.7 will be the end of the line for Python 2 development, and now the official upgrade path from 2.7 is Python 3.x. I'm sure that with this state of affairs, Python 3 support from web frameworks is only going to get better and better.</p> <hr> <p><sub>[OUTDATED]</sub><br> Python 3 is not yet in high deployment. It's still lacking a lot of third party libraries.</p> <p>The recommended Python version is 2.6.x, as it's the most current, it's backwards compatible, and has many backported features from 3.1.</p> <p>For Python 2.6 you will find quite a few frameworks:</p> <ul> <li><a href="http://wiki.python.org/moin/Django" rel="nofollow">Django</a></li> <li><a href="http://www.turbogears.org/" rel="nofollow">Turbogears</a></li> <li><a href="http://wiki.python.org/moin/CherryPy" rel="nofollow">CherryPy</a></li> <li><a href="http://www.zope.org/" rel="nofollow">Zope</a></li> <li><a href="http://wiki.python.org/moin/WebFrameworks" rel="nofollow">and many more</a></li> </ul>
4
2009-10-02T15:20:56Z
[ "python", "ruby-on-rails", "frameworks", "python-3.x" ]
Is there any framework like RoR on Python 3000?
1,510,084
<p>One of the feature I like in RoR is the db management, it can hide all the sql statement, also, it is very easy to change different db in RoR, is there any similar framework in Python 3000?</p>
1
2009-10-02T15:01:41Z
1,510,218
<p>Python 3 is not ready for practical use, because there is not yet enough libraries that have been updated to support Python 3. So the answer is: No.</p> <p>But there are LOADS of them on Python 2. Tens, at least.</p> <p>Django, Turbogears, BFG and of course the old man of the game: Zope. To tell which is best for you, you need to expand your requirements a lot. </p>
0
2009-10-02T15:21:04Z
[ "python", "ruby-on-rails", "frameworks", "python-3.x" ]
Is there any framework like RoR on Python 3000?
1,510,084
<p>One of the feature I like in RoR is the db management, it can hide all the sql statement, also, it is very easy to change different db in RoR, is there any similar framework in Python 3000?</p>
1
2009-10-02T15:01:41Z
1,510,491
<p>Python 3 isn't ready for web applications right now. The WSGI 1.0 specification isn't suitable for Py3k and the related standard libraries are 2to3 hacks that don't work consistently faced with bytes vs. unicode. It's a real mess.</p> <p>WEB-SIG are bashing out proposals for a WSGI revision; hopefully it can move forward soon, because although Python 3 isn't mainstream yet it's certainly heading that way, and the brokenness of webdev is rather embarrassing.</p>
1
2009-10-02T16:08:15Z
[ "python", "ruby-on-rails", "frameworks", "python-3.x" ]
Is there any framework like RoR on Python 3000?
1,510,084
<p>One of the feature I like in RoR is the db management, it can hide all the sql statement, also, it is very easy to change different db in RoR, is there any similar framework in Python 3000?</p>
1
2009-10-02T15:01:41Z
1,512,245
<p>I believe CherryPy is on the verge of being released for Python 3.X.</p>
2
2009-10-02T23:11:49Z
[ "python", "ruby-on-rails", "frameworks", "python-3.x" ]