title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
which style is preferred? | 2,114,540 | 9 | 2010-01-22T02:21:36Z | 2,114,572 | 11 | 2010-01-22T02:29:41Z | [
"python",
"exception",
"coding-style"
] | Option 1:
```
def f1(c):
d = {
"USA": "N.Y.",
"China": "Shanghai"
}
if c in d:
return d[c]
return "N/A"
```
Option 2:
```
def f2(c):
d = {
"USA": "N.Y.",
"China": "Shanghai"
}
try:
return d[c]
except:
return "N/A"
```
So that I can then call:
```
for c in ("China", "J... | In general terms (not necessarily Python), I tend to prefer the "try-then-tell-me-if-it-went-wrong" method (exceptions) in all but the simplest cases. This is because, in threaded environments or during database access, the underlying data can change between the key check and the value extraction.
If you're not changi... |
How to serialize db.Model objects to json? | 2,114,659 | 16 | 2010-01-22T02:53:41Z | 2,125,046 | 14 | 2010-01-23T22:51:12Z | [
"python",
"google-app-engine",
"simplejson"
] | When using
```
from django.utils import simplejson
```
on objects of types that derive from `db.Model` it throws exceptions. How to circumvent this? | Ok - my python not great so any help would be appreciated - You dont need to write a parser - this is the solution:
add this utlity class <http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55>
```
import datetime
import time
from google.appengine.api import users
from g... |
How to serialize db.Model objects to json? | 2,114,659 | 16 | 2010-01-22T02:53:41Z | 2,333,152 | 10 | 2010-02-25T10:07:40Z | [
"python",
"google-app-engine",
"simplejson"
] | When using
```
from django.utils import simplejson
```
on objects of types that derive from `db.Model` it throws exceptions. How to circumvent this? | The example provided by Jader Dias works fine for my concern after some twaeking. Remove the encode method as it contains a circular reference. The adjusted class should look like:
```
import datetime
import time
from google.appengine.api import users
from google.appengine.ext import db
from django.utils import ... |
What is the deal with the pony in Python community? | 2,115,360 | 31 | 2010-01-22T06:00:26Z | 2,115,369 | 15 | 2010-01-22T06:02:49Z | [
"python",
"django",
"pony"
] | Pony references are in several places:
* <http://www.mail-archive.com/python-dev@python.org/msg44751.html>
* <http://pypi.python.org/pypi/django-pony/>
* <http://djangopony.com/>
Is there a cultural reference that I am missing? What is the deal with ponies? | Its a Django unofficial mascot. See [this blog post for an explanation](http://twothirty.am/blog/2009/10/07/blessing-mythical-django-pony/).
Python generally uses Monty Python references (and sometimes snake references, for the misguided). |
What is the deal with the pony in Python community? | 2,115,360 | 31 | 2010-01-22T06:00:26Z | 2,115,375 | 57 | 2010-01-22T06:03:37Z | [
"python",
"django",
"pony"
] | Pony references are in several places:
* <http://www.mail-archive.com/python-dev@python.org/msg44751.html>
* <http://pypi.python.org/pypi/django-pony/>
* <http://djangopony.com/>
Is there a cultural reference that I am missing? What is the deal with ponies? | When you start listing what you want, "I want a fast HTTP parser", "I want ORM that just works", "I want higher order functions", the idea is that while you're wishing for things, you might as well wish for a pony too. This is probably a reference to a Calvin and Hobbes strip from "Someone under the bed is drooling", i... |
What is the deal with the pony in Python community? | 2,115,360 | 31 | 2010-01-22T06:00:26Z | 2,115,634 | 19 | 2010-01-22T07:09:03Z | [
"python",
"django",
"pony"
] | Pony references are in several places:
* <http://www.mail-archive.com/python-dev@python.org/msg44751.html>
* <http://pypi.python.org/pypi/django-pony/>
* <http://djangopony.com/>
Is there a cultural reference that I am missing? What is the deal with ponies? | See also [Bryan Veloso's post about the pony mascot image](http://avalonstar.com/legacy/blog/2008/sep/9/the-web-framework-for-ponies/). |
What is the deal with the pony in Python community? | 2,115,360 | 31 | 2010-01-22T06:00:26Z | 2,115,901 | 8 | 2010-01-22T08:18:55Z | [
"python",
"django",
"pony"
] | Pony references are in several places:
* <http://www.mail-archive.com/python-dev@python.org/msg44751.html>
* <http://pypi.python.org/pypi/django-pony/>
* <http://djangopony.com/>
Is there a cultural reference that I am missing? What is the deal with ponies? | Look at what the pony does!Â
* <http://code.djangoproject.com/ticket/10668>
* <http://www.flickr.com/photos/bastispicks/3400633546/> |
Does Python have a module for parsing HTTP requests and responses? | 2,115,410 | 20 | 2010-01-22T06:11:32Z | 5,964,334 | 37 | 2011-05-11T12:37:03Z | [
"python",
"http",
"parsing"
] | httplib (now http.client) and friends all have conn.getresponse() and an HTTPResponse class, but the server-side operations of conn.getrequest() and an HTTPRequest class seem to be lacking.
I understand that BaseHTTPServer and BaseHTTPRequestHandler can perform this functionality, but they don't expose these methods f... | Jeff, to enable parsing I create a small nine-line subclass of the base HTTP request handler:
```
from BaseHTTPServer import BaseHTTPRequestHandler
from StringIO import StringIO
class HTTPRequest(BaseHTTPRequestHandler):
def __init__(self, request_text):
self.rfile = StringIO(request_text)
self.ra... |
assigning value to shell variable using a function return value from Python | 2,115,615 | 10 | 2010-01-22T07:04:53Z | 2,115,632 | 27 | 2010-01-22T07:08:56Z | [
"python",
"shell"
] | I have a Python function, fooPy() that returns some value. ( int / double or string)
I want to use this value and assign it in a shell script. For example following is the python function:
```
def fooPy():
return "some string"
#return 10 .. alternatively, it can be an int
fooPy()
```
In the shell script I... | You can print your value in Python, like this:
```
print fooPy()
```
and in your shell script:
```
fooShell=$(python fooPy.py)
```
Be sure not to leave spaces around the `=` in the shell script. |
Python: Find identical items in multiple lists | 2,116,286 | 4 | 2010-01-22T09:36:47Z | 2,116,318 | 13 | 2010-01-22T09:42:51Z | [
"python",
"list"
] | I have a list of an arbitrary number of lists, for instance:
```
[[1,2,3], [3,4,5], [5,6,7], [7,8,9]]
```
Now I would like a list containing all elements that are present in more than one list:
```
[3,5,7]
```
How would I do that?
Thanks! | The same way as you'd do it by hand:
```
seen = set()
repeated = set()
for l in list_of_lists:
for i in set(l):
if i in seen:
repeated.add(i)
else:
seen.add(i)
```
By the way, here's the one liner (without counting the import) that some people were seeking (should be less efficient than the othe... |
Help me understand Inorder Traversal without using recursion | 2,116,662 | 28 | 2010-01-22T10:44:42Z | 2,116,755 | 71 | 2010-01-22T11:05:51Z | [
"python",
"algorithm",
"tree",
"tree-traversal",
"non-recursive"
] | I am able to understand preorder traversal without using recursion, but I'm having a hard time with inorder traversal. I just don't seem to get it, perhaps, because I haven't understood the inner working of recursion.
This is what I've tried so far:
```
def traverseInorder(node):
lifo = Lifo()
lifo.push(node)... | Start with the recursive algorithm (pseudocode) :
```
traverse(node):
if node != None do:
traverse(node.left)
print node.value
traverse(node.right)
endif
```
This is a clear case of tail recursion, so you can easily turn it into a while-loop.
```
traverse(node):
while node != None do:
traverse(... |
Help me understand Inorder Traversal without using recursion | 2,116,662 | 28 | 2010-01-22T10:44:42Z | 4,915,707 | 13 | 2011-02-06T19:55:31Z | [
"python",
"algorithm",
"tree",
"tree-traversal",
"non-recursive"
] | I am able to understand preorder traversal without using recursion, but I'm having a hard time with inorder traversal. I just don't seem to get it, perhaps, because I haven't understood the inner working of recursion.
This is what I've tried so far:
```
def traverseInorder(node):
lifo = Lifo()
lifo.push(node)... | Here is a simple in-order non-recursive c++ code ..
```
void inorder (node *n)
{
stack s;
while(n){
s.push(n);
n=n->left;
}
while(!s.empty()){
node *t=s.pop();
cout<<t->data;
t=t->right;
while(t){
s.push(t);
t = t->left;
... |
Python deep getsizeof list with contents? | 2,117,255 | 16 | 2010-01-22T12:49:08Z | 2,117,311 | 12 | 2010-01-22T13:00:52Z | [
"python",
"memory"
] | I was surprised that `sys.getsizeof( 10000*[x] )`
is 40036 regardless of x: 0, "a", 1000\*"a", {}.
Is there a `deep_getsizeof`
which properly considers elements that share memory ?
(The question came from looking at in-memory database tables like
range(1000000) -> province names: list or dict ?)
(Python is 2.6.4 ... | 10000 \* [x] will produce a list of 10000 times *the same object*, so the sizeof is actually closer to correct than you think. However, a deep sizeof is very problematic because it's impossible to tell Python when you want to stop the measurement. Every object references a typeobject. Should the typeobject be counted? ... |
Convert a timedelta to days, hours and minutes | 2,119,472 | 79 | 2010-01-22T18:20:38Z | 2,119,509 | 12 | 2010-01-22T18:25:45Z | [
"python",
"timedelta"
] | I've got a timedelta. I want the days, hours and minutes from that - either as a tuple or a dictionary... I'm not fussed.
I must have done this a dozen times in a dozen languages over the years but Python usually has a simple answer to everything so I thought I'd ask here before busting out some nauseatingly simple (y... | ```
days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60
```
As for DST, I think the best thing is to convert both `datetime` objects to seconds. This way the system calculates DST for you.
```
>>> m13 = datetime(2010, 3, 13, 8, 0, 0) # 2010 March 13 8:00 AM
>>> m14 = datetime(2010, 3, 14, 8, 0,... |
Convert a timedelta to days, hours and minutes | 2,119,472 | 79 | 2010-01-22T18:20:38Z | 2,119,512 | 115 | 2010-01-22T18:26:00Z | [
"python",
"timedelta"
] | I've got a timedelta. I want the days, hours and minutes from that - either as a tuple or a dictionary... I'm not fussed.
I must have done this a dozen times in a dozen languages over the years but Python usually has a simple answer to everything so I thought I'd ask here before busting out some nauseatingly simple (y... | If you have a `datetime.timedelta` value `td`, `td.days` already gives you the "days" you want. `timedelta` values keep fraction-of-day as seconds (not directly hours or minutes) so you'll indeed have to perform "nauseating simple mathematics", e.g.:
```
def days_hours_minutes(td):
return td.days, td.seconds//3600... |
Convert a timedelta to days, hours and minutes | 2,119,472 | 79 | 2010-01-22T18:20:38Z | 10,981,895 | 35 | 2012-06-11T14:16:53Z | [
"python",
"timedelta"
] | I've got a timedelta. I want the days, hours and minutes from that - either as a tuple or a dictionary... I'm not fussed.
I must have done this a dozen times in a dozen languages over the years but Python usually has a simple answer to everything so I thought I'd ask here before busting out some nauseatingly simple (y... | This is a bit more compact, you get the hours, minutes and seconds in two lines.
```
hours, remainder = divmod(td.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
``` |
Calling a python function from bash script | 2,119,702 | 10 | 2010-01-22T19:00:27Z | 2,119,716 | 13 | 2010-01-22T19:03:05Z | [
"python",
"bash",
"function",
"scripting"
] | I have an "alarm email" function inside a python module. I want to be able to call this function from a bash script. I know you can call a module using 'python ' in the script, but I'm not if you can or how you would call a specific function within the module. | You can use the `-c` option:
```
python -c "import random; print random.uniform(0, 1)"
```
Modify as you need. |
Calling a python function from bash script | 2,119,702 | 10 | 2010-01-22T19:00:27Z | 2,119,728 | 23 | 2010-01-22T19:04:19Z | [
"python",
"bash",
"function",
"scripting"
] | I have an "alarm email" function inside a python module. I want to be able to call this function from a bash script. I know you can call a module using 'python ' in the script, but I'm not if you can or how you would call a specific function within the module. | ```
python -c'import themodule; themodule.thefunction("boo!")'
``` |
Simple Python Challenge: Fastest Bitwise XOR on Data Buffers | 2,119,761 | 47 | 2010-01-22T19:08:49Z | 2,119,943 | 10 | 2010-01-22T19:39:34Z | [
"python",
"algorithm",
"performance",
"xor"
] | **Challenge:**
Perform a bitwise XOR on two equal sized buffers. The buffers will be required to be the python `str` type since this is traditionally the type for data buffers in python. Return the resultant value as a `str`. Do this as fast as possible.
The inputs are two 1 megabyte (2\*\*20 byte) strings.
The chal... | An easy speedup is to use a larger 'chunk':
```
def faster_xor(aa,bb):
a=frombuffer(aa,dtype=uint64)
b=frombuffer(bb,dtype=uint64)
c=bitwise_xor(a,b)
r=c.tostring()
return r
```
with `uint64` also imported from `numpy` of course. I `timeit` this at 4 milliseconds, vs 6 milliseconds for the `byte` ... |
Simple Python Challenge: Fastest Bitwise XOR on Data Buffers | 2,119,761 | 47 | 2010-01-22T19:08:49Z | 2,174,000 | 17 | 2010-02-01T00:22:05Z | [
"python",
"algorithm",
"performance",
"xor"
] | **Challenge:**
Perform a bitwise XOR on two equal sized buffers. The buffers will be required to be the python `str` type since this is traditionally the type for data buffers in python. Return the resultant value as a `str`. Do this as fast as possible.
The inputs are two 1 megabyte (2\*\*20 byte) strings.
The chal... | Here are my results for cython
```
slow_xor 0.456888198853
faster_xor 0.400228977203
cython_xor 0.232881069183
cython_xor_vectorised 0.171468019485
```
Vectorising in cython shaves about 25% off the for loop on my computer, However more than half the time is spent building the python string (the `return` statement)... |
Simple Python Challenge: Fastest Bitwise XOR on Data Buffers | 2,119,761 | 47 | 2010-01-22T19:08:49Z | 2,179,687 | 29 | 2010-02-01T20:07:58Z | [
"python",
"algorithm",
"performance",
"xor"
] | **Challenge:**
Perform a bitwise XOR on two equal sized buffers. The buffers will be required to be the python `str` type since this is traditionally the type for data buffers in python. Return the resultant value as a `str`. Do this as fast as possible.
The inputs are two 1 megabyte (2\*\*20 byte) strings.
The chal... | # First Try
Using [`scipy.weave`](http://www.scipy.org/Weave) and [SSE2](http://en.wikipedia.org/wiki/SSE2) intrinsics gives a marginal improvement. The first invocation is a bit slower since the code needs to be loaded from the disk and cached, subsequent invocations are faster:
```
import numpy
import time
from os ... |
Simple Python Challenge: Fastest Bitwise XOR on Data Buffers | 2,119,761 | 47 | 2010-01-22T19:08:49Z | 2,566,106 | 33 | 2010-04-02T10:15:59Z | [
"python",
"algorithm",
"performance",
"xor"
] | **Challenge:**
Perform a bitwise XOR on two equal sized buffers. The buffers will be required to be the python `str` type since this is traditionally the type for data buffers in python. Return the resultant value as a `str`. Do this as fast as possible.
The inputs are two 1 megabyte (2\*\*20 byte) strings.
The chal... | ## Performance comparison: numpy vs. Cython vs. C vs. Fortran vs. Boost.Python (pyublas)
```
| function | time, usec | ratio | type |
|------------------------+------------+-------+--------------|
| slow_xor | 2020 | 1.0 | numpy |
| xorf_int16 | 1570... |
Why do Python function docs include the comma after the bracket for optional args? | 2,120,507 | 4 | 2010-01-22T21:06:36Z | 2,120,518 | 14 | 2010-01-22T21:08:59Z | [
"python",
"documentation",
"notation"
] | The format of the function signatures in the Python docs is a bit confusing. What is the significance in putting the comma after the open bracket, rather than before? What is the significance of nesting the brackets?
How they are:
```
RegexObject.match(string[, pos[, endpos]])
```
I would expect one of the following... | The square bracket means that the contents are optional, but everything outside of square brackets is compulsory.
With your notation:
```
RegexObject.match(string, [pos], [endpos])
```
I would expect to have to write:
```
r.match("foo",,)
```
The nesting is required because if you supply the third parameter then y... |
Django InlineModelAdmin: Show partially an inline model and link to the complete model | 2,120,813 | 29 | 2010-01-22T21:53:14Z | 2,201,828 | 27 | 2010-02-04T17:34:26Z | [
"python",
"django",
"django-admin"
] | Hi everybody
I defined several models: Journals, volumes, volume\_scanInfo etc.
A journal can have more volumes and a volume can have more scanInfo.
What I want to do is:
* in the admin page of journals I want to have the list of the volumes inline (done)
* connect each volume of the previous list to its admin page ... | **UPDATE:**
Since Django 1.8, this is built in.
See [this answer](http://stackoverflow.com/a/28170958/493272) and [the official documentation](https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin.show_change_link).
**OLD ANSWER:**
At the end I found a simple solution.
I cre... |
Django InlineModelAdmin: Show partially an inline model and link to the complete model | 2,120,813 | 29 | 2010-01-22T21:53:14Z | 9,452,596 | 25 | 2012-02-26T11:14:08Z | [
"python",
"django",
"django-admin"
] | Hi everybody
I defined several models: Journals, volumes, volume\_scanInfo etc.
A journal can have more volumes and a volume can have more scanInfo.
What I want to do is:
* in the admin page of journals I want to have the list of the volumes inline (done)
* connect each volume of the previous list to its admin page ... | Keep your code in **models.py** with conditional case:
```
def selflink(self):
if self.id:
return "<a href='/link/to/volume/%s' target='_blank'>Edit</a>" % str(self.id)
else:
return "Not present"
selflink.allow_tags = True
```
In **admin.py**, add selflink as [readonly](https://docs.djangopro... |
Django InlineModelAdmin: Show partially an inline model and link to the complete model | 2,120,813 | 29 | 2010-01-22T21:53:14Z | 21,079,750 | 13 | 2014-01-12T20:14:24Z | [
"python",
"django",
"django-admin"
] | Hi everybody
I defined several models: Journals, volumes, volume\_scanInfo etc.
A journal can have more volumes and a volume can have more scanInfo.
What I want to do is:
* in the admin page of journals I want to have the list of the volumes inline (done)
* connect each volume of the previous list to its admin page ... | Here's a reusable mixin based on some of the other answers. This is handy because it works with both Tabular and Stacked inlines, and doesn't cruft up your model or admin code.
```
# put this somewhere like admin_helpers.py
from django.core.urlresolvers import reverse
class InlineEditLinkMixin(object):
readonly_f... |
Why does this code have the "ball" seem to slide along the edge | 2,121,287 | 4 | 2010-01-22T23:34:42Z | 2,121,304 | 10 | 2010-01-22T23:37:43Z | [
"python"
] | My son asked me if I could write a small program to have a ball bounce around the screen then have me explain it.
Spotting a neat father-son opportunity I said "Yes!, no problem". So I dug out my python skills and wrote this..
```
#!/usr/bin/python
#
# We have to tell python what stuff we're
# going to use. We do thi... | You need to add twice dir\_\* in the "change direction" code. |
Python3 http.server POST example | 2,121,481 | 13 | 2010-01-23T00:29:38Z | 2,124,520 | 10 | 2010-01-23T20:11:22Z | [
"python",
"python-3.x"
] | I'm converting a Python2.6 app into a Python3 app and I'm getting stuck with the server. I've managed to get it serving up GET requests just fine but POST continues to elude me. Here is what I started with in 2.6 that worked but in 3.x the normal server does not handle POST requests. From my reading of the Python manua... | After poking and a few more hours of googling I've found the following works.
```
def do_POST(self):
length = int(self.headers['Content-Length'])
post_data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))
# You now have a dictionary of the post data
self.wfile.write("Lorem Ipsum".encod... |
rstrip not removing newline char what am I doing wrong? | 2,121,839 | 9 | 2010-01-23T02:32:27Z | 2,121,843 | 13 | 2010-01-23T02:36:14Z | [
"python",
"newline"
] | Pulling my hair out here... have been playing around with this for the last hour but I cannot get it to do what I want, ie. remove the newline sequence.
```
def add_quotes( fpath ):
ifile = open( fpath, 'r' )
ofile = open( 'ofile.txt', 'w' )
for line in ifile:
if line == '\n':
... | The clue is in the signature of `rstrip`.
It returns a copy of the string, but with the desired characters stripped, thus you'll need to assign `line` the new value:
```
line = line.rstrip('\n')
```
This allows for the sometimes very handy chaining of operations:
```
"a string".strip().upper()
```
As [Max. S](http... |
Python pickling after changing a module's directory | 2,121,874 | 15 | 2010-01-23T02:52:39Z | 2,121,918 | 25 | 2010-01-23T03:11:03Z | [
"python",
"pickle"
] | I've recently changed my program's directory layout: before, I had all my modules inside the "main" folder. Now, I've moved them into a directory named after the program, and placed an `__init__.py` there to make a package.
Now I have a single .py file in my main directory that is used to launch my program, which is m... | As [pickle's docs](http://docs.python.org/library/pickle.html?highlight=pickle#relationship-to-other-python-modules) say, in order to save and restore a class instance (actually a function, too), you must respect certain constraints:
> pickle can save and restore class
> instances transparently, however the
> class de... |
Word wrap on report lab PDF table | 2,121,909 | 11 | 2010-01-23T03:05:58Z | 2,123,359 | 11 | 2010-01-23T13:56:08Z | [
"python",
"reportlab"
] | I'm using the Table of Report Lab library to print a table on a PDF report. I would like to know if it's possible to configure the table to perform an automatic wrapping of the content of a cell.
For example, I have a text that doesn't fit on a cell inside a column. I would like that the table performs the wrap automa... | You can put any flowable in a table element. It is probably good practice to have all table elements as flowables, so they can be styled the same. For your case you will most likely need a Paragraph flowable. eg.
```
styles = getSampleStyleSheet()
text = Paragraph("long line",
styles['Normal'])
```
You ... |
Python: urllib2 or Pycurl? | 2,121,945 | 2 | 2010-01-23T03:20:58Z | 2,121,976 | 8 | 2010-01-23T03:29:38Z | [
"python",
"urllib2",
"pycurl"
] | I have extensive experience with PHP cURL but for the last few months I've been coding primarily in Java, utilizing the HttpClient library.
My new project requires me to use Python, once again putting me at the crossroads of seemingly comparable libraries: pycurl and urllib2.
Putting aside my previous experience with... | CURL has a lot more features as stated in its [web page](http://pycurl.sourceforge.net/), so if you need, say fast concurrent connections, safe threading, etc then its for you. However, its not included in the distribution. If you foresee that your task is very simple, then use urllib2 and those HTTP modules that come ... |
Dynamic terminal printing with python | 2,122,385 | 16 | 2010-01-23T06:33:29Z | 2,122,972 | 23 | 2010-01-23T11:31:21Z | [
"python",
"terminal"
] | Certain applications like hellanzb have a way of printing to the terminal with the appearance of dynamically refreshing data, kind of like top().
Whats the best method in python for doing this? I have read up on logging and curses, but don't know what to use. I am creating a reimplementation of top. If you have any ot... | The simplest way, if you only ever need to update a single line (for instance, creating a progress bar), is to use `'\r'` (carriage return) and `sys.stdout`:
```
import sys
import time
for i in range(10):
sys.stdout.write("\r{0}>".format("="*i))
sys.stdout.flush()
time.sleep(0.5)
```
If you need a proper... |
Python: multiple properties, one setter/getter | 2,123,585 | 11 | 2010-01-23T15:08:34Z | 2,123,602 | 19 | 2010-01-23T15:14:16Z | [
"python",
"properties",
"setter",
"getter-setter"
] | Consider the following class definitions
```
class of2010(object):
def __init__(self):
self._a = 1
self._b = 2
self._c = 3
def set_a(self,value):
print('setting a...')
self._a = value
def set_b(self,value):
print('setting b...')
self._b = value
d... | ```
def attrsetter(attr):
def set_any(self, value):
setattr(self, attr, value)
return set_any
a = property(fset=attrsetter('_a'))
b = property(fset=attrsetter('_b'))
c = property(fset=attrsetter('_c'))
``` |
when does Python allocate new memory for identical strings? | 2,123,925 | 26 | 2010-01-23T17:08:14Z | 2,123,934 | 14 | 2010-01-23T17:12:02Z | [
"python",
"memory",
"memory-management"
] | Two Python strings with the same characters, a == b,
may share memory, id(a) == id(b),
or may be in memory twice, id(a) != id(b).
Try
```
ab = "ab"
print id( ab ), id( "a"+"b" )
```
Here Python recognizes that the newly created "a"+"b" is the same
as the "ab" already in memory -- not bad.
Now consider an N-long list... | I strongly suspect that Python is behaving like many other languages here - recognising string constants *within your source code* and using a common table for those, but *not* applying the same rules when creating strings dynamically. This makes sense as there will only be a finite set of strings within your source co... |
when does Python allocate new memory for identical strings? | 2,123,925 | 26 | 2010-01-23T17:08:14Z | 2,124,011 | 33 | 2010-01-23T17:34:30Z | [
"python",
"memory",
"memory-management"
] | Two Python strings with the same characters, a == b,
may share memory, id(a) == id(b),
or may be in memory twice, id(a) != id(b).
Try
```
ab = "ab"
print id( ab ), id( "a"+"b" )
```
Here Python recognizes that the newly created "a"+"b" is the same
as the "ab" already in memory -- not bad.
Now consider an N-long list... | Each *implementation* of the Python language is free to make its own tradeoffs in allocating immutable objects (such as strings) -- either making a new one, or finding an existing equal one and using one more reference to it, are just fine from the language's point of view. In practice, of course, real-world implementa... |
when does Python allocate new memory for identical strings? | 2,123,925 | 26 | 2010-01-23T17:08:14Z | 2,125,618 | 8 | 2010-01-24T02:09:13Z | [
"python",
"memory",
"memory-management"
] | Two Python strings with the same characters, a == b,
may share memory, id(a) == id(b),
or may be in memory twice, id(a) != id(b).
Try
```
ab = "ab"
print id( ab ), id( "a"+"b" )
```
Here Python recognizes that the newly created "a"+"b" is the same
as the "ab" already in memory -- not bad.
Now consider an N-long list... | A side note: it is very important to know the lifetime of objects in Python. Note the following session:
```
Python 2.6.4 (r264:75706, Dec 26 2009, 01:03:10)
[GCC 4.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a="a"
>>> b="b"
>>> print id(a+b), id(b+a)
134898720 134898720
... |
How do I implement interfaces in python? | 2,124,190 | 17 | 2010-01-23T18:29:07Z | 2,124,211 | 13 | 2010-01-23T18:33:56Z | [
"c#",
"python",
"oop"
] | ```
public interface IInterface
{
void show();
}
public class MyClass : IInterface
{
#region IInterface Members
public void show()
{
Console.WriteLine("Hello World!");
}
#endregion
}
```
How do I implement Python equivalent of this C# code ?
```
class IInterface(object):
def _... | There are third-party implementations of interfaces for Python (most popular is [Zope's](http://www.zope.org/Products/ZopeInterface), also used in [Twisted](http://twistedmatrix.com/documents/current/core/howto/plugin.html)), but more commonly Python coders prefer to use the richer concept known as an "Abstract Base Cl... |
How do I implement interfaces in python? | 2,124,190 | 17 | 2010-01-23T18:29:07Z | 2,124,220 | 9 | 2010-01-23T18:36:23Z | [
"c#",
"python",
"oop"
] | ```
public interface IInterface
{
void show();
}
public class MyClass : IInterface
{
#region IInterface Members
public void show()
{
Console.WriteLine("Hello World!");
}
#endregion
}
```
How do I implement Python equivalent of this C# code ?
```
class IInterface(object):
def _... | Something like this (might not work as I don't have Python around):
```
class IInterface:
def show(self): raise NotImplementedError
class MyClass(IInterface):
def show(self): print "Hello World!"
``` |
How do I implement interfaces in python? | 2,124,190 | 17 | 2010-01-23T18:29:07Z | 2,124,415 | 26 | 2010-01-23T19:35:30Z | [
"c#",
"python",
"oop"
] | ```
public interface IInterface
{
void show();
}
public class MyClass : IInterface
{
#region IInterface Members
public void show()
{
Console.WriteLine("Hello World!");
}
#endregion
}
```
How do I implement Python equivalent of this C# code ?
```
class IInterface(object):
def _... | As mentioned by other here:
Interfaces is not necessary in Python. This is because Python has proper multiple inheritance, and also ducktyping, which means that the places where you *must* have interfaces in Java, you don't have to have them in Python.
That said, there is still several uses of interfaces. Some of the... |
How do I implement interfaces in python? | 2,124,190 | 17 | 2010-01-23T18:29:07Z | 23,134,110 | 13 | 2014-04-17T13:11:36Z | [
"c#",
"python",
"oop"
] | ```
public interface IInterface
{
void show();
}
public class MyClass : IInterface
{
#region IInterface Members
public void show()
{
Console.WriteLine("Hello World!");
}
#endregion
}
```
How do I implement Python equivalent of this C# code ?
```
class IInterface(object):
def _... | Using the abc module for abstract base classes seems to do the trick.
```
from abc import ABCMeta, abstractmethod
class IInterface:
__metaclass__ = ABCMeta
@classmethod
def version(self): return "1.0"
@abstractmethod
def show(self): raise NotImplementedError
class MyServer(IInterface):
def s... |
how to generate permutations of array in python? | 2,124,347 | 20 | 2010-01-23T19:12:57Z | 2,124,365 | 9 | 2010-01-23T19:16:25Z | [
"python",
"permutation"
] | i have an array of 27 elements,and i don't want to generate all permutations of array (27!)
i need 5000 randomly choosed permutations,any tip will be useful... | ```
import random
perm_list = []
for i in range(5000):
temp = range(27)
random.shuffle(temp)
perm_list.append(temp)
print(perm_list)
```
`10888869450418352160768000000` I love big numbers! :)
AND
**`10888869450418352160768000001` is PRIME!!**
**EDIT:**
```
#with duplicates check as suggested in the ... |
how to generate permutations of array in python? | 2,124,347 | 20 | 2010-01-23T19:12:57Z | 2,124,370 | 30 | 2010-01-23T19:17:12Z | [
"python",
"permutation"
] | i have an array of 27 elements,and i don't want to generate all permutations of array (27!)
i need 5000 randomly choosed permutations,any tip will be useful... | To generate one permutation use [`random.shuffle`](http://docs.python.org/library/random.html#random.shuffle) and store a copy of the result. Repeat this operation in a loop and each time check for duplicates (there probably won't be any though). Once you have 5000 items in your result set, stop.
To address the point ... |
Why am I getting dups with random.shuffle in Python? | 2,124,748 | 4 | 2010-01-23T21:11:22Z | 2,124,788 | 19 | 2010-01-23T21:22:06Z | [
"python",
"random",
"probability",
"birthday-paradox"
] | For a list of 10 ints, there are 10! possible orders or permutations. Why does random.shuffle give duplicates after only 5000 tries?
```
>>> L = range(10)
>>> rL = list()
>>> for i in range(5000):
... random.shuffle(L)
... rL.append(L[:])
...
>>> rL = [tuple(e) for e in rL]
>>> len(set(rL))
4997
>>> for i,t i... | It's called the [Birthday Paradox](http://en.wikipedia.org/wiki/Birthday_problem).
According to this formula from Wikipedia:

but replacing `365` with `10!` you would only need about 2200 examples to have a 50% chance of a collision, and... |
How to return the count of related entities in sqlalchemy query | 2,125,041 | 9 | 2010-01-23T22:50:03Z | 2,132,503 | 8 | 2010-01-25T13:21:34Z | [
"python",
"sql",
"sqlalchemy"
] | I'm new to sqlalchemy, and while the documentation seems fairly thorough, I couldn't find a way to do quite what I want.
Say I have two tables: forum and post. Each forum has a parent forum, and any number of posts. What I want is:
* A list of top-level forums
* Eagerly loaded child forums accessible through the top-... | Because you want the post count to be accessible on the child Forum objects you'll need to declare it as a column property when setting up the mappers. The column property declaration should look something like this (assuming you use declarative):
```
Forum.post_count = column_property(select([func.count()],
M... |
Unit Conversion in Python | 2,125,076 | 35 | 2010-01-23T23:02:21Z | 2,209,188 | 23 | 2010-02-05T17:49:50Z | [
"python",
"units-of-measurement"
] | I'm working on a project that lets users track different data types over time. Part of the base idea is that a user should be able to enter data using any units that they need to. I've been looking at both units:
<http://pypi.python.org/pypi/units/>
and quantities:
<http://pypi.python.org/pypi/quantities/>
However ... | I applaud use of explicit units in scientific computing applications. Using explicit units is analogous brushing your teeth. It adds some tedium up front, but the type safety you get can save a lot of trouble in the long run. Like, say, [not crashing $125 million orbiters into planets](http://www.cnn.com/TECH/space/990... |
Unit Conversion in Python | 2,125,076 | 35 | 2010-01-23T23:02:21Z | 17,034,705 | 10 | 2013-06-11T00:06:16Z | [
"python",
"units-of-measurement"
] | I'm working on a project that lets users track different data types over time. Part of the base idea is that a user should be able to enter data using any units that they need to. I've been looking at both units:
<http://pypi.python.org/pypi/units/>
and quantities:
<http://pypi.python.org/pypi/quantities/>
However ... | [Pint](https://pint.readthedocs.org/en/latest/) has recently come onto the field. Anybody care to share their experiences? Looks good. FYI: It looks like [Pint will be integrated with Uncertainties](http://pythonhosted.org/uncertainties/#future-developments) in the near future. |
Python property | 2,125,166 | 8 | 2010-01-23T23:22:07Z | 2,125,180 | 18 | 2010-01-23T23:26:50Z | [
"python",
"properties"
] | The output seems a bit fishy given the following code. Why is "get in Base" only printed once? And why is not "set in Base" printed at all? The actual getting/setting seems to work fine though. What am I missing?
```
class Base:
def __init__(self):
self.s = "BaseStr"
def getstr(self):
print "g... | You need to use [new-style classes](http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes) for properties to work correctly. To do so derive your class from `object`:
```
class Base(object):
...
``` |
stopping a cherrypy server over http | 2,125,175 | 6 | 2010-01-23T23:24:38Z | 2,130,438 | 7 | 2010-01-25T05:47:14Z | [
"python",
"cherrypy"
] | I have a cherrypy app that I'm controlling over http with a wxpython ui. I want to kill the server when the ui closes, but I don't know how to do that. Right now I'm just doing a sys.exit() on the window close event but thats resulting in
```
Traceback (most recent call last):
File "ui.py", line 67, in exitevent
... | How are you stopping CherryPy? By sending a SIGKILL to itself? You should send TERM instead at the least, but even better would be to call `cherrypy.engine.exit()` (version 3.1+). Both techniques will allow CherryPy to shut down more gracefully, which includes allowing any in-process requests (like your "?sigkill=1" re... |
Python and Rpy2: Calling plot function with options that have "." in them | 2,125,218 | 8 | 2010-01-23T23:36:47Z | 2,125,767 | 7 | 2010-01-24T03:13:26Z | [
"python",
"rpy2"
] | I'm just starting to learn how to use rpy2 with python. I'm able to make simple plots and such, but I've run into the problem that many options in R use ".". For example, here's an R call that works:
> barplot(t, col=heat.colors(2), names.arg=c("pwn", "pwn2"))
where t is a matrix.
I want to use the same call in pyth... | You can use a dictionary here for the named arguments ([using \*\*](http://docs.python.org/tutorial/controlflow.html#keyword-arguments)) as [described](http://rpy.sourceforge.net/rpy2/doc/html/robjects.html#functions) in the docs, and call R directly for the functions. Also remember that RPy2 expects its [own vector ob... |
How to play sound in Python WITHOUT interrupting music/other sounds from playing | 2,125,547 | 7 | 2010-01-24T01:40:38Z | 2,125,558 | 8 | 2010-01-24T01:45:08Z | [
"python",
"linux",
"audio",
"timer"
] | I'm working on a timer in python which sounds a chime when the waiting time is over. I use the following code:
```
from wave import open as wave_open
from ossaudiodev import open as oss_open
def _play_chime():
"""
Play a sound file once.
"""
sound_file = wave_open('chime.wav','rb')
(nc,sw,fr,nf,c... | The easy answer is "Switch from OSS to PulseAudio." (Or set up ALSA to use dmix, or get a soundcard with better Linux drivers...)
The more complicated answer is, your code already works the way you want it to... on some soundcards. OSS drivers can expose hardware mixers so that you can have multiple audio streams play... |
How to suppress console output in Python? | 2,125,702 | 13 | 2010-01-24T02:43:59Z | 2,125,776 | 10 | 2010-01-24T03:16:54Z | [
"python",
"sdl",
"pygame"
] | I'm using Pygame/SDL's joystick module to get input from a gamepad. Every time I call its `get_hat()` method it prints to the console. This is problematic since I use the console to help me debug and now it gets flooded with `SDL_JoystickGetHat value:0:` 60 times every second. Is there a way I can disable this? Either ... | You can get around this by assigning the standard out/error (I don't know which one it's going to) to the null device. In Python, the standard out/error files are `sys.stdout`/`sys.stderr`, and the null device is `os.devnull`, so you do
```
sys.stdout = os.devnull
sys.stderr = os.devnull
```
This should disable these... |
How to suppress console output in Python? | 2,125,702 | 13 | 2010-01-24T02:43:59Z | 25,061,573 | 11 | 2014-07-31T14:31:13Z | [
"python",
"sdl",
"pygame"
] | I'm using Pygame/SDL's joystick module to get input from a gamepad. Every time I call its `get_hat()` method it prints to the console. This is problematic since I use the console to help me debug and now it gets flooded with `SDL_JoystickGetHat value:0:` 60 times every second. Is there a way I can disable this? Either ... | Just for completeness, here's a nice solution from [Dave Smith's blog](http://thesmithfam.org/blog/2012/10/25/temporarily-suppress-console-output-in-python/):
```
from contextlib import contextmanager
import sys, os
@contextmanager
def suppress_stdout():
with open(os.devnull, "w") as devnull:
old_stdout =... |
After breaking a python program into functions, how do I make one the main function? | 2,125,825 | 10 | 2010-01-24T03:42:27Z | 2,125,860 | 12 | 2010-01-24T03:52:13Z | [
"python"
] | This is the biggest newbie question on the planet, but I'm just not sure. I've written a bunch of functions that perform some task, and I want a "main" function that will, for example, when I call "someProgram.py", run function1, function2 and quit. I vaguely remember something about "**main**" but I have no clue. | Python scripts are not collections of functions, but rather collections of statements - function and class definitions are just statements that bind names to function or class objects.
If you put a print statement at the top or middle of your program, it will run normally without being in any function. What this means... |
How limiting are web frameworks | 2,125,865 | 7 | 2010-01-24T03:53:02Z | 2,126,011 | 8 | 2010-01-24T04:58:13Z | [
"python",
"ruby-on-rails",
"django",
"rest"
] | This is a general question about how limiting are web development frameworks such as Django and ruby-on-rails.
I am planning on building a RESTful web service which will have a purely JSON/XML interface, no GUI. The service will rely on a database however for a few of the more important operations there is no clear wa... | Web frameworks tend to optimize around building websites, making most normal use cases simpler to accomplish. Once you start to do more "out of the box" stuff with a framework, you might find that you spend more time working around it then you save using it in the first place.
It's hard to generalize here (especially ... |
How to organize an app-engine application | 2,125,951 | 3 | 2010-01-24T04:27:43Z | 2,126,290 | 11 | 2010-01-24T07:21:54Z | [
"python",
"google-app-engine"
] | I want to create a directory structure like the following. How can I get the account.py and game.py to handle the requests that go to \account\ and \game\ respectfully. All the app-engine examples I have seen have all the logic in on main.py that handle all urls.
```
app\account\
\account.py
\game\
... | You need the following in your `app.yaml`:
```
- url: /account
script: account/account.py
- url: /game
script: game/game.py
- url: .*
script: main.py
```
BTW, I suggest you try to forget backslashes (characters like this: \ ) -- think *normal* slashes (characters like this: / ). Backslashes are a Windows anom... |
Python os.path is ntpath, how? | 2,126,301 | 4 | 2010-01-24T07:28:19Z | 2,126,323 | 7 | 2010-01-24T07:39:25Z | [
"python",
"path",
"module",
"alias"
] | Can someone tell me how Python "aliases" `os.path` to `ntpath`?
```
>>> import os.path
>>> os.path
<module 'ntpath' from 'C:\Python26\lib\ntpath.pyc'>
>>>
``` | Look at [os.py](http://svn.python.org/view/python/trunk/Lib/os.py?annotate=77218), lines 55-67:
```
elif 'nt' in _names:
name = 'nt'
linesep = '\r\n'
from nt import *
try:
from nt import _exit
except ImportError:
pass
import ntpath as path
import nt
__all__.extend(_get_... |
An equivalent to string.ascii_letters for unicode strings in python 2.x? | 2,126,551 | 10 | 2010-01-24T09:26:57Z | 2,127,648 | 11 | 2010-01-24T15:58:49Z | [
"python",
"unicode",
"python-2.x"
] | In the "string" module of the standard library,
```
string.ascii_letters ## Same as string.ascii_lowercase + string.ascii_uppercase
```
is
```
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
```
Is there a similar constant which would include everything that is considered a letter in unicode? | You can construct your own constant of Unicode upper and lower case letters with:
```
import unicodedata as ud
all_unicode = ''.join(unichr(i) for i in xrange(65536))
unicode_letters = ''.join(c for c in all_unicode
if ud.category(c)=='Lu' or ud.category(c)=='Ll')
```
This makes a string 215... |
Processing a simple workflow in Python | 2,126,811 | 9 | 2010-01-24T11:20:47Z | 2,126,863 | 9 | 2010-01-24T11:41:21Z | [
"python",
"workflow"
] | I am working on a code which takes a dataset and runs some algorithms on it.
User uploads a dataset, and then selects which algorithms will be run on this dataset and creates a workflow like this:
```
workflow =
{0: {'dataset': 'some dataset'},
1: {'algorithm1': "parameters"},
2: {'algorithm2': "parameters"},
3: ... | You want to run a pipeline on some dataset. That sounds like a reduce operation (fold in some languages). No need for anything complicated:
```
result = reduce(lambda data, (aname, p): algo_by_name(aname)(p, data), workflow)
```
This assumes workflow looks like (text-oriented so you can load it with YAML/JSON):
```
... |
Can you really scale up with Django...given that you can only use one database? (In the models.py and settings.py) | 2,127,067 | 5 | 2010-01-24T12:46:44Z | 2,127,076 | 11 | 2010-01-24T12:49:51Z | [
"python",
"django",
"web-services",
"scalability"
] | Django only allows you to use one database in settings.py.
Does that prevent you from scaling up? (millions of users) | Django now has [support for multiple databases](http://code.djangoproject.com/wiki/MultipleDatabaseSupport). |
Can you really scale up with Django...given that you can only use one database? (In the models.py and settings.py) | 2,127,067 | 5 | 2010-01-24T12:46:44Z | 2,127,141 | 8 | 2010-01-24T13:08:22Z | [
"python",
"django",
"web-services",
"scalability"
] | Django only allows you to use one database in settings.py.
Does that prevent you from scaling up? (millions of users) | The database isn't your bottleneck.
Check your browser carefully.
For each page of HTML you're sending (on average) 8 other files, some of which may be quite large. These are your JS, CSS, graphics, etc.
The actual performance bottleneck is the browser requesting those files and accepting the bytes s... l... o... w.... |
Easy to use time-stamps in Python | 2,127,447 | 3 | 2010-01-24T15:01:42Z | 2,127,476 | 7 | 2010-01-24T15:11:47Z | [
"python",
"datetime",
"time",
"timestamp"
] | I'm working on a journal-type application in Python. The application basically permits the user write entries in the journal and adds a time-stamp for later querying the journal.
As of now, I use the `time.ctime()` function to generate time-stamps that are visually friendly. The journal entries thus look like:
```
Th... | Option 1: Don't change anything. Use [time.strptime](http://docs.python.org/library/time.html#time.strptime) to parse your timestamps.
Option 2: Change to `datetime`. You can format the timestamps the same way, and use [datetime.strptime](http://docs.python.org/library/datetime.html#datetime.datetime.strptime) to pars... |
Easy to use time-stamps in Python | 2,127,447 | 3 | 2010-01-24T15:01:42Z | 2,127,501 | 9 | 2010-01-24T15:18:19Z | [
"python",
"datetime",
"time",
"timestamp"
] | I'm working on a journal-type application in Python. The application basically permits the user write entries in the journal and adds a time-stamp for later querying the journal.
As of now, I use the `time.ctime()` function to generate time-stamps that are visually friendly. The journal entries thus look like:
```
Th... | You might want to consider changing to [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601). Will help with sorting for example, or transferring data between different systems. |
Python Syntax Error but looks fine to me. Help? | 2,127,735 | 2 | 2010-01-24T16:20:08Z | 2,127,766 | 7 | 2010-01-24T16:26:31Z | [
"python",
"syntax-error"
] | Right now I'm working on a Tetris Game (sorta, I found a Tetris example for Python on a website, I've been copying it but adding some of my own stuff), and just finished writing all the code but have had a couple syntax errors. I've been able to fix all of them but this last syntax error is confusing to me.
```
de... | You didn't close the parenthesis of `self.setShapeAt`. |
Network programming in Python | 2,128,266 | 2 | 2010-01-24T18:51:42Z | 2,129,373 | 7 | 2010-01-24T23:27:10Z | [
"python",
"sockets",
"network-programming"
] | What library should I use for network programming? Is `sockets` the best, or is there a higher level interface, that is standard?
I need something that will be pretty cross platform (ie. Linux, Windows, Mac OS X), and it only needs to be able to connect to other Python programs using the same library. | You just want to send python data between nodes (possibly on separate computers)? You might want to look at SimpleXMLRPCServer. It's based on the inbuilt HTTP server, which is based on the inbuilt Socket server, neither of which are the most industrial-strength servers around, but it's easy to set up in a hurry:
```
f... |
What's the difference between filter and filter_by in SQLAlchemy? | 2,128,505 | 144 | 2010-01-24T19:49:46Z | 2,128,558 | 160 | 2010-01-24T20:02:56Z | [
"python",
"sqlalchemy"
] | Could anyone explain the difference between `filter` and `filter_by` functions in SQLAlchemy? I am confused and can't really see the difference. Which one should I be using? | `filter_by` is used for simple queries on the column names like
`db.users.filter_by(name='Joe')`
The same can be accomplished with `filter` by writing
`db.users.filter(db.users.name=='Joe')`
but you can also write more powerful queries containing expressions like
`db.users.filter(or_(db.users.name=='Ryan', db.user... |
What's the difference between filter and filter_by in SQLAlchemy? | 2,128,505 | 144 | 2010-01-24T19:49:46Z | 2,128,567 | 25 | 2010-01-24T20:04:59Z | [
"python",
"sqlalchemy"
] | Could anyone explain the difference between `filter` and `filter_by` functions in SQLAlchemy? I am confused and can't really see the difference. Which one should I be using? | `filter_by` uses keyword arguments, whereas `filter` allows pythonic filtering arguments like `filter(User.name=="john")` |
What's the difference between filter and filter_by in SQLAlchemy? | 2,128,505 | 144 | 2010-01-24T19:49:46Z | 2,157,930 | 80 | 2010-01-28T21:04:50Z | [
"python",
"sqlalchemy"
] | Could anyone explain the difference between `filter` and `filter_by` functions in SQLAlchemy? I am confused and can't really see the difference. Which one should I be using? | We actually had these merged together originally, i.e. there was a "filter"-like method that accepted \*args and \*\*kwargs, where you could pass a SQL expression or keyword arguments (or both). I actually find that a lot more convenient, but people were always confused by it, since they're usually still getting over t... |
What's the difference between filter and filter_by in SQLAlchemy? | 2,128,505 | 144 | 2010-01-24T19:49:46Z | 31,560,897 | 15 | 2015-07-22T10:45:58Z | [
"python",
"sqlalchemy"
] | Could anyone explain the difference between `filter` and `filter_by` functions in SQLAlchemy? I am confused and can't really see the difference. Which one should I be using? | It is a syntax sugar for faster query writing. Its implementation in pseudocode:
```
def filter_by(self, **kwargs):
return self.filter(sql.and_(**kwargs))
```
For AND you can simply write:
```
Users.query.filter_by(name='Joe', surname='Dodson')
```
btw
```
db.users.filter(or_(db.users.name=='Ryan', db.users.co... |
SQLAlchemy printing raw SQL from create() | 2,128,717 | 20 | 2010-01-24T20:40:52Z | 2,134,301 | 8 | 2010-01-25T17:44:10Z | [
"python",
"sqlalchemy",
"pylons"
] | I am giving Pylons a try with SQLAlchemy, and I love it, there is just one thing, is it possible to print out the raw SQL CREATE TABLE data generated from Table().create() before it's executed? | Something like this? (from the SQLA FAQ)
<http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html> |
SQLAlchemy printing raw SQL from create() | 2,128,717 | 20 | 2010-01-24T20:40:52Z | 3,150,687 | 40 | 2010-06-30T15:22:21Z | [
"python",
"sqlalchemy",
"pylons"
] | I am giving Pylons a try with SQLAlchemy, and I love it, there is just one thing, is it possible to print out the raw SQL CREATE TABLE data generated from Table().create() before it's executed? | ```
from sqlalchemy.schema import CreateTable
print CreateTable(table)
```
If you are using declarative syntax:
```
print CreateTable(Model.__table__)
```
**Update:**
Since I have the accepted answer and there is important information in [klenwell answer](http://stackoverflow.com/a/10216304/242786), I'll also add ... |
SQLAlchemy printing raw SQL from create() | 2,128,717 | 20 | 2010-01-24T20:40:52Z | 10,216,304 | 9 | 2012-04-18T19:13:02Z | [
"python",
"sqlalchemy",
"pylons"
] | I am giving Pylons a try with SQLAlchemy, and I love it, there is just one thing, is it possible to print out the raw SQL CREATE TABLE data generated from Table().create() before it's executed? | I needed to get the raw table sql in order to setup tests for some existing models. Here's a successful unit test that I created for SQLAlchemy 0.7.4 based on [Antoine's answer](http://stackoverflow.com/a/3150687/1093087) as proof of concept:
```
from sqlalchemy import create_engine
from sqlalchemy.schema import Creat... |
Python, len, and size of ints | 2,128,989 | 5 | 2010-01-24T21:40:33Z | 2,129,017 | 11 | 2010-01-24T21:45:59Z | [
"python",
"int"
] | So, cPython (2.4) has some interesting behaviour when the length of something gets near to 1<<32 (the size of an int).
```
r = xrange(1<<30)
assert len(r) == 1<<30
```
is fine, but:
```
r = xrange(1<<32)
assert len(r) == 1<<32
ValueError: xrange object size cannot be reported`__len__() should return 0 <= outcome
```... | cPython assumes that lists fit in memory. This extends to objects that behave like lists, such as xrange. essentially, the `len` function expects the `__len__` method to return something that is convertable to `size_t`, which won't happen if the number of logical elements is too large, even if those elements don't actu... |
Clojure Jython interop | 2,129,253 | 12 | 2010-01-24T22:51:46Z | 2,130,855 | 12 | 2010-01-25T07:42:30Z | [
"python",
"interop",
"lisp",
"clojure",
"jython"
] | I was wondering if anyone has tried somehow calling Jython functions
from within Clojure, and how you went about doing this if so. I have
not used Jython, but I would imagine the Jython interpreter can be
invoked in the same way as any other java code, and Python programs
can be run within it. However I wonder if it wo... | **A note:** I just realised that the question is specifically about calling Jython functions from Clojure and *not* about building a full-fledged Jython-Clojure interop solution... But! I've already produced a smallish write-up on my initial thoughts on the latter and I guess that's the logical next step anyway. I mean... |
Dynamically assign special methods to objects but not classes in Python | 2,129,643 | 4 | 2010-01-25T01:06:43Z | 2,129,652 | 8 | 2010-01-25T01:12:09Z | [
"python",
"dynamic",
"methods"
] | I would like to do the following:
```
class A(object): pass
a = A()
a.__int__ = lambda self: 3
i = int(a)
```
Unfortunately, this throws:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'A'
```
This only seems to work if I as... | Python always looks up special methods on the class, not the instance (except in the old, aka "legacy", kind of classes -- they're deprecated and have gone away in Python 3, because of the quirky semantics that mostly comes from looking up special methods on the instance, so you really **don't** want to use them, belie... |
How can I set up Celery to call a custom initialization function before running my tasks? | 2,129,820 | 15 | 2010-01-25T02:07:42Z | 2,145,587 | 13 | 2010-01-27T09:07:57Z | [
"python",
"django",
"daemon",
"amqp",
"celery"
] | I have a Django project and I'm trying to use Celery to submit tasks for background processing ( <http://ask.github.com/celery/introduction.html> ). Celery integrates well with Django and I've been able to submit my custom tasks and get back results.
The only problem is that I can't find a sane way of performing custo... | You can either write a custom loader, or use the signals.
Loaders have the `on_task_init` method, which is called when a task is about to be executed,
and `on_worker_init` which is called by the celery+celerybeat main process.
Using signals is probably the easiest, the signals available are:
0.8.x:
* `task_prerun(t... |
splitting a list of arbitrary size into only roughly N-equal parts | 2,130,016 | 46 | 2010-01-25T03:19:28Z | 2,130,035 | 29 | 2010-01-25T03:27:31Z | [
"python",
"list",
"chunks"
] | what is the best way to divide a list into *roughly* equal parts? for example, if I have a list with 54 elements and i want to split it into 3 roughly equal parts? I'd like the parts to be as even as possible, hopefully assigning the elements that do not fit in a way that gives the most equal parts. to give a concrete ... | Here's one that could work:
```
def chunkIt(seq, num):
avg = len(seq) / float(num)
out = []
last = 0.0
while last < len(seq):
out.append(seq[int(last):int(last + avg)])
last += avg
return out
```
Testing:
```
>>> chunkIt(range(10), 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
>>> chunkIt(range(11), 3)... |
splitting a list of arbitrary size into only roughly N-equal parts | 2,130,016 | 46 | 2010-01-25T03:19:28Z | 2,130,042 | 14 | 2010-01-25T03:30:11Z | [
"python",
"list",
"chunks"
] | what is the best way to divide a list into *roughly* equal parts? for example, if I have a list with 54 elements and i want to split it into 3 roughly equal parts? I'd like the parts to be as even as possible, hopefully assigning the elements that do not fit in a way that gives the most equal parts. to give a concrete ... | Changing the code to yield `n` chunks rather than chunks of `n`:
```
def chunks(l, n):
""" Yield n successive chunks from l.
"""
newn = int(len(l) / n)
for i in xrange(0, n-1):
yield l[i*newn:i*newn+newn]
yield l[n*newn-newn:]
l = range(56)
three_chunks = chunks (l, 3)
print three_chunks.n... |
splitting a list of arbitrary size into only roughly N-equal parts | 2,130,016 | 46 | 2010-01-25T03:19:28Z | 2,135,920 | 26 | 2010-01-25T21:48:42Z | [
"python",
"list",
"chunks"
] | what is the best way to divide a list into *roughly* equal parts? for example, if I have a list with 54 elements and i want to split it into 3 roughly equal parts? I'd like the parts to be as even as possible, hopefully assigning the elements that do not fit in a way that gives the most equal parts. to give a concrete ... | You can write it fairly simply as a list generator:
```
def split(a, n):
k, m = len(a) / n, len(a) % n
return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in xrange(n))
```
Example:
```
>>> list(split(range(11), 3))
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10]]
``` |
splitting a list of arbitrary size into only roughly N-equal parts | 2,130,016 | 46 | 2010-01-25T03:19:28Z | 2,136,090 | 37 | 2010-01-25T22:18:16Z | [
"python",
"list",
"chunks"
] | what is the best way to divide a list into *roughly* equal parts? for example, if I have a list with 54 elements and i want to split it into 3 roughly equal parts? I'd like the parts to be as even as possible, hopefully assigning the elements that do not fit in a way that gives the most equal parts. to give a concrete ... | As long as you don't want anything silly like continuous chunks:
```
>>> def chunkify(lst,n):
... return [ lst[i::n] for i in xrange(n) ]
...
>>> chunkify( range(13), 3)
[[0, 3, 6, 9, 12], [1, 4, 7, 10], [2, 5, 8, 11]]
``` |
Adding a string in front of a string for each item in a list in python | 2,130,552 | 8 | 2010-01-25T06:17:17Z | 2,130,577 | 14 | 2010-01-25T06:22:03Z | [
"python",
"string",
"loops",
"for-loop"
] | I have a list of websites in a string and I was doing a for loop to add "http" in the front if the first index is not "h" but when I return it, the list did not change.
n is my list of websites
h is "http"
```
for p in n:
if p[0]!="h":
p= h+ p
else:
continue
return n
```
when i return the lis... | This could also be done using list comprehension:
```
n = [i if i.startswith('h') else 'http' + i for i in n]
``` |
No plot window in matplotlib | 2,130,913 | 50 | 2010-01-25T08:01:58Z | 2,130,963 | 8 | 2010-01-25T08:11:54Z | [
"python",
"ubuntu",
"matplotlib"
] | I just installed matplotlib in Ubuntu 9.10 using the synaptic package system.
However, when I try the following simple example
```
>>> from pylab import plot;
>>> plot([1,2,3],[1,2,3])
[<matplotlib.lines.Line2D object at 0x9aa78ec>]
```
I get no plot window. Any ideas on how to get the plot window to show? | Any errors show up? This might an issue of not having set the backend. You can set it from the Python interpreter or from a config file (`.matplotlib/matplotlibrc`) in you home directory.
To set the backend in code you can do
```
import matplotlib
matplotlib.use('Agg')
```
where 'Agg' is the name of the backend. Whi... |
No plot window in matplotlib | 2,130,913 | 50 | 2010-01-25T08:01:58Z | 2,130,968 | 77 | 2010-01-25T08:12:35Z | [
"python",
"ubuntu",
"matplotlib"
] | I just installed matplotlib in Ubuntu 9.10 using the synaptic package system.
However, when I try the following simple example
```
>>> from pylab import plot;
>>> plot([1,2,3],[1,2,3])
[<matplotlib.lines.Line2D object at 0x9aa78ec>]
```
I get no plot window. Any ideas on how to get the plot window to show? | You can type
```
import pylab
pylab.show()
```
or better, use `ipython -pylab`. |
No plot window in matplotlib | 2,130,913 | 50 | 2010-01-25T08:01:58Z | 2,131,021 | 28 | 2010-01-25T08:27:41Z | [
"python",
"ubuntu",
"matplotlib"
] | I just installed matplotlib in Ubuntu 9.10 using the synaptic package system.
However, when I try the following simple example
```
>>> from pylab import plot;
>>> plot([1,2,3],[1,2,3])
[<matplotlib.lines.Line2D object at 0x9aa78ec>]
```
I get no plot window. Any ideas on how to get the plot window to show? | `pylab.show()` works but blocks (you need to close the window).
A much more convenient solution is to do `pylab.ion()` (interactive mode on) when you start: all (the pylab equivalents of) `pyplot.*` commands display their plot immediately. [More information on the interactive mode](http://matplotlib.sourceforge.net/fa... |
No plot window in matplotlib | 2,130,913 | 50 | 2010-01-25T08:01:58Z | 4,839,002 | 9 | 2011-01-29T19:38:33Z | [
"python",
"ubuntu",
"matplotlib"
] | I just installed matplotlib in Ubuntu 9.10 using the synaptic package system.
However, when I try the following simple example
```
>>> from pylab import plot;
>>> plot([1,2,3],[1,2,3])
[<matplotlib.lines.Line2D object at 0x9aa78ec>]
```
I get no plot window. Any ideas on how to get the plot window to show? | Try this:
```
import matplotlib
matplotlib.use('TkAgg')
```
BEFORE import pylab |
Creating a mock web service from a WSDL file in Python | 2,131,207 | 10 | 2010-01-25T09:14:32Z | 2,131,261 | 8 | 2010-01-25T09:25:46Z | [
"python",
"soap",
"wsdl",
"mocking"
] | We are writing a client for a remote service that exposes SOAP web services and publishes a WSDL definition for those services.
We don't have access to the system during testing, so we'd like to write a mock service. We're using Python for the client, so ideally we'd want to use Python for the mock server, although I ... | As a mock server I would really recommend soapUI (<http://www.soapui.org>).
It takes a WSDL and generates the services and service methods automatically. You can then go on and define static returns or dynamic ones using Groovy scripts. Take a look [here](http://www.soapui.org/userguide/mock/index.html) for the docume... |
How can I normalize/collapse paths or URLs in Python in OS independent way? | 2,131,290 | 5 | 2010-01-25T09:30:58Z | 2,131,301 | 8 | 2010-01-25T09:33:59Z | [
"python",
"url",
"path",
"normalize"
] | I tried to use `os.normpath` in order to convert `http://example.com/a/b/c/../` to `http://example.com/a/b/` but it doesn't work on Windows because it does convert the slash to backslash. | Here is how to do it
```
>>> import urlparse
>>> urlparse.urljoin("ftp://domain.com/a/b/c/d/", "../..")
'ftp://domain.com/a/b/'
>>> urlparse.urljoin("ftp://domain.com/a/b/c/d/e.txt", "../..")
'ftp://domain.com/a/b/'
```
Remember that `urljoin` consider a path/directory all until the last `/` - after this is the filen... |
Alternative ways to browse the python api | 2,131,419 | 14 | 2010-01-25T09:57:48Z | 2,131,611 | 7 | 2010-01-25T10:30:29Z | [
"python",
"documentation",
"standard-library"
] | Is it just me, or the python standard library documentation is extremely difficult to browse through?
* <http://docs.python.org/3.1/library/index.html>
* <http://docs.python.org/3.1/modindex.html>
Java has its brilliant [Javadocs](http://java.sun.com/javase/6/docs/api/), Ruby has its helpful [Ruby-Docs](http://ruby-d... | I usually use the built-in [pydoc](http://docs.python.org/library/pydoc.html), if you are on windows it should be called Module Docs if you are on linux use `pydoc -p 8000` and connect through browser. |
Django-registration, force unique e-mail | 2,131,533 | 12 | 2010-01-25T10:16:23Z | 7,377,850 | 13 | 2011-09-11T11:16:01Z | [
"python",
"django"
] | Can I force users to make unique e-mail addresses in django-registration? | from rych's answer, I tested that the following runs ok - it only uses urls.py, you needn't write another cusotmer form.
```
from registration.forms import RegistrationFormUniqueEmail
url(r'^accounts/register/$', 'registration.views.register',
{'form_class': RegistrationFormUniqueEmail,
'backend': 'registrat... |
Django-registration, force unique e-mail | 2,131,533 | 12 | 2010-01-25T10:16:23Z | 19,383,392 | 13 | 2013-10-15T14:10:05Z | [
"python",
"django"
] | Can I force users to make unique e-mail addresses in django-registration? | For later versions of django\_registration (that use class-based views), you can do this:
```
from registration.forms import RegistrationFormUniqueEmail
from registration.backends.default.views import RegistrationView
urlpatterns = patterns('',
url(r'^register/$',
RegistrationView.as_view(form_class=Regis... |
Django and SSL question | 2,131,727 | 22 | 2010-01-25T10:56:07Z | 2,132,293 | 27 | 2010-01-25T12:50:15Z | [
"python",
"django",
"ssl"
] | I am planning to sell products by charging credit cards thus using SSL will be critical for Django-powered website. And I am very naive for this.
My initial django setup plan was using Apache as the webserver and using mod\_wsgi to communicate with Django, static media again served by Apache. All seemed good until SSL... | I have deployed Django apps on SSL using Apache's `mod_ssl` and `mod_wsgi`.
I am no Apache expert, but here's how I setup SSL for one site (put the directives below in the `httpd.conf` file, or in a file referenced from that file, for instance in the `sites-enabled` directory, if that is used in your Apache installati... |
Django and SSL question | 2,131,727 | 22 | 2010-01-25T10:56:07Z | 8,064,356 | 14 | 2011-11-09T11:28:42Z | [
"python",
"django",
"ssl"
] | I am planning to sell products by charging credit cards thus using SSL will be critical for Django-powered website. And I am very naive for this.
My initial django setup plan was using Apache as the webserver and using mod\_wsgi to communicate with Django, static media again served by Apache. All seemed good until SSL... | For those coming through Google, heres an example config for Nginx:
```
server {
listen 443 ssl default;
server_name example.com;
ssl on;
ssl_certificate /etc/nginx/server.crt;
ssl_certificate_key /etc/nginx/server.key;
add_header Cache-Control "public, must-revalidate";
# add_header Cach... |
Best way to handle list.index(might-not-exist) in python? | 2,132,718 | 42 | 2010-01-25T13:59:37Z | 2,132,727 | 32 | 2010-01-25T14:02:07Z | [
"python",
"list",
"find",
"indexing"
] | I have code which looks something like this:
```
thing_index = thing_list.index(thing)
otherfunction(thing_list, thing_index)
```
ok so that's simplified but you get the idea. Now `thing` might not actually be in the list, in which case I want to pass -1 as `thing_index`. In other languages this is what you'd expect ... | There is nothing "dirty" about using try-except clause. This is the pythonic way. `ValueError` will be raised by the `.index` method only, because it's the only code you have there!
To answer the comment:
In Python, [*easier to ask forgiveness than to get permission*](http://docs.python.org/3.1/glossary.html#term-ea... |
Best way to handle list.index(might-not-exist) in python? | 2,132,718 | 42 | 2010-01-25T13:59:37Z | 2,132,769 | 9 | 2010-01-25T14:08:51Z | [
"python",
"list",
"find",
"indexing"
] | I have code which looks something like this:
```
thing_index = thing_list.index(thing)
otherfunction(thing_list, thing_index)
```
ok so that's simplified but you get the idea. Now `thing` might not actually be in the list, in which case I want to pass -1 as `thing_index`. In other languages this is what you'd expect ... | The [`dict` type](http://docs.python.org/library/stdtypes.html#dict) has a [`get` function](http://docs.python.org/library/stdtypes.html#dict.get), where if the key doesn't exist in the dictionary, the 2nd argument to `get` is the value that it should return. Similarly there is [`setdefault`](http://docs.python.org/lib... |
Best way to handle list.index(might-not-exist) in python? | 2,132,718 | 42 | 2010-01-25T13:59:37Z | 2,133,116 | 22 | 2010-01-25T15:01:25Z | [
"python",
"list",
"find",
"indexing"
] | I have code which looks something like this:
```
thing_index = thing_list.index(thing)
otherfunction(thing_list, thing_index)
```
ok so that's simplified but you get the idea. Now `thing` might not actually be in the list, in which case I want to pass -1 as `thing_index`. In other languages this is what you'd expect ... | ```
thing_index = thing_list.index(elem) if elem in thing_list else -1
```
One line. Simple. No exceptions. |
How to import or include data structures (e.g. a dict) into a Python file from a separate file | 2,132,985 | 11 | 2010-01-25T14:41:33Z | 2,133,011 | 8 | 2010-01-25T14:44:49Z | [
"python",
"import",
"module"
] | I know I can include Python code from a common file using `import MyModuleName` - but how do I go about importing just a dict?
The problem I'm trying to solve is I have a dict that needs to be in a file in an editable location, while the actual script is in another file. The dict might also be edited by hand, by a non... | Assuming your `import myDict` works, you need to do the following:
```
from myDict import airportCode
``` |
How to import or include data structures (e.g. a dict) into a Python file from a separate file | 2,132,985 | 11 | 2010-01-25T14:41:33Z | 2,133,037 | 22 | 2010-01-25T14:48:14Z | [
"python",
"import",
"module"
] | I know I can include Python code from a common file using `import MyModuleName` - but how do I go about importing just a dict?
The problem I'm trying to solve is I have a dict that needs to be in a file in an editable location, while the actual script is in another file. The dict might also be edited by hand, by a non... | Just import it
```
import script
print script.airportCode
```
or, better
```
from script import airportCode
print airportCode
```
Just be careful to put both scripts on the same directory (or make a python package, a subdir with `__init__.py` file; or put the path to script.py on the PYTHONPATH; but these are "adva... |
Is MATLAB faster than Python? | 2,133,031 | 29 | 2010-01-25T14:47:42Z | 2,133,050 | 7 | 2010-01-25T14:51:05Z | [
"python",
"matlab",
"matrix",
"performance"
] | I want to compute magnetic fields of some conductors using the [BiotâSavart law](http://en.wikipedia.org/wiki/Biot%E2%80%93Savart_law) and I want to use a 1000x1000x1000 matrix. Before I use MATLAB, but now I want to use Python. Is Python slower than MATLAB ? How can I make Python faster?
EDIT:
Maybe the best way is... | The only valid test is to benchmark it. It really depends on what your platform is, and how well the Biot-Savart Law maps to Matlab or NumPy/SciPy built-in operations.
As for making Python faster, Google's working on Unladen Swallow, a JIT compiler for Python. There are probably other projects like this as well. |
Is MATLAB faster than Python? | 2,133,031 | 29 | 2010-01-25T14:47:42Z | 2,133,556 | 25 | 2010-01-25T16:02:50Z | [
"python",
"matlab",
"matrix",
"performance"
] | I want to compute magnetic fields of some conductors using the [BiotâSavart law](http://en.wikipedia.org/wiki/Biot%E2%80%93Savart_law) and I want to use a 1000x1000x1000 matrix. Before I use MATLAB, but now I want to use Python. Is Python slower than MATLAB ? How can I make Python faster?
EDIT:
Maybe the best way is... | You might find some useful results at the bottom of this link
<http://wiki.scipy.org/PerformancePython>
From the introduction,
> A comparison of weave with NumPy, Pyrex, Psyco, Fortran (77 and 90) and C++ for solving Laplace's equation.
It also compares MATLAB and seems to show similar speeds to when using Python a... |
Is MATLAB faster than Python? | 2,133,031 | 29 | 2010-01-25T14:47:42Z | 2,133,569 | 14 | 2010-01-25T16:04:27Z | [
"python",
"matlab",
"matrix",
"performance"
] | I want to compute magnetic fields of some conductors using the [BiotâSavart law](http://en.wikipedia.org/wiki/Biot%E2%80%93Savart_law) and I want to use a 1000x1000x1000 matrix. Before I use MATLAB, but now I want to use Python. Is Python slower than MATLAB ? How can I make Python faster?
EDIT:
Maybe the best way is... | [NumPy](http://en.wikipedia.org/wiki/NumPy) and MATLAB both use an underlying [BLAS](http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms) implementation for standard linear algebra operations. For some time both used [ATLAS](http://en.wikipedia.org/wiki/Automatically_Tuned_Linear_Algebra_Software), but nowada... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.