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 |
|---|---|---|---|---|---|---|---|---|---|
Fixture loading works with loaddata but fails silently in unit test in Django | 1,504,255 | 4 | 2009-10-01T14:21:21Z | 1,504,290 | 9 | 2009-10-01T14:26:14Z | [
"python",
"django",
"unit-testing",
"fixtures"
] | I can load the fixture file in my django application by using loaddata:
```
manage.py loaddata palamut
```
The fixture `palamut.yaml` is in the directory `palamut/fixtures/`
I have a unit test module `service_tests.py` in `palamut/tests/`. Its content is here:
```
import unittest
from palamut.models import *
from p... | Your TestCase should be an instance of django.test.TestCase, not unittest.TestCase |
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result? | 1,504,717 | 593 | 2009-10-01T15:40:14Z | 1,504,739 | 77 | 2009-10-01T15:45:02Z | [
"python",
"string",
"comparison"
] | I've got a Python program where two variables are set to the value `'public'`. In a conditional expression I have the comparison `var1 is var2` which fails, but if I change it to `var1 == var2` it returns `True`.
Now if I open my Python interpreter and do the same "is" comparison, it succeeds.
```
>>> s1 = 'public'
>... | The `is` keyword is a test for object identity while `==` is a value comparison.
If you use `is`, the result will be true if and only if the object is the same object. However, `==` will be true any time the values of the object are the same. |
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result? | 1,504,717 | 593 | 2009-10-01T15:40:14Z | 1,504,740 | 9 | 2009-10-01T15:45:07Z | [
"python",
"string",
"comparison"
] | I've got a Python program where two variables are set to the value `'public'`. In a conditional expression I have the comparison `var1 is var2` which fails, but if I change it to `var1 == var2` it returns `True`.
Now if I open my Python interpreter and do the same "is" comparison, it succeeds.
```
>>> s1 = 'public'
>... | I think it has to do with the fact that, when the 'is' comparison evaluates to false, two distinct objects are used. If it evaluates to true, that means internally it's using the same exact object and not creating a new one, possibly because you created them within a fraction of 2 or so seconds and because there isn't ... |
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result? | 1,504,717 | 593 | 2009-10-01T15:40:14Z | 1,504,742 | 857 | 2009-10-01T15:45:20Z | [
"python",
"string",
"comparison"
] | I've got a Python program where two variables are set to the value `'public'`. In a conditional expression I have the comparison `var1 is var2` which fails, but if I change it to `var1 == var2` it returns `True`.
Now if I open my Python interpreter and do the same "is" comparison, it succeeds.
```
>>> s1 = 'public'
>... | `is` is identity testing, `==` is equality testing. what happens in your code would be emulated in the interpreter like this:
```
>>> a = 'pub'
>>> b = ''.join(['p', 'u', 'b'])
>>> a == b
True
>>> a is b
False
```
so, no wonder they're not the same, right?
In other words: `is` is the `id(a) == id(b)` |
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result? | 1,504,717 | 593 | 2009-10-01T15:40:14Z | 1,504,756 | 13 | 2009-10-01T15:48:07Z | [
"python",
"string",
"comparison"
] | I've got a Python program where two variables are set to the value `'public'`. In a conditional expression I have the comparison `var1 is var2` which fails, but if I change it to `var1 == var2` it returns `True`.
Now if I open my Python interpreter and do the same "is" comparison, it succeeds.
```
>>> s1 = 'public'
>... | From my limited experience with python, `is` is used to compare two objects to see if they are the same object as opposed to two different objects with the same value. `==` is used to determine if the values are identical.
Here is a good example:
```
>>> s1 = u'public'
>>> s2 = 'public'
>>> s1 is s2
False
>>> s1 == s... |
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result? | 1,504,717 | 593 | 2009-10-01T15:40:14Z | 1,504,829 | 7 | 2009-10-01T15:59:38Z | [
"python",
"string",
"comparison"
] | I've got a Python program where two variables are set to the value `'public'`. In a conditional expression I have the comparison `var1 is var2` which fails, but if I change it to `var1 == var2` it returns `True`.
Now if I open my Python interpreter and do the same "is" comparison, it succeeds.
```
>>> s1 = 'public'
>... | I believe that this is known as "interned" strings. Python does this, so does Java, and so do C and C++ when compiling in optimized modes.
If you use two identical strings, instead of wasting memory by creating two string objects, all interned strings with the same contents point to the same memory.
This results in t... |
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result? | 1,504,717 | 593 | 2009-10-01T15:40:14Z | 1,504,848 | 285 | 2009-10-01T16:02:14Z | [
"python",
"string",
"comparison"
] | I've got a Python program where two variables are set to the value `'public'`. In a conditional expression I have the comparison `var1 is var2` which fails, but if I change it to `var1 == var2` it returns `True`.
Now if I open my Python interpreter and do the same "is" comparison, it succeeds.
```
>>> s1 = 'public'
>... | SilentGhost and others are correct here. `is` is used for *identity* comparison, while `==` is used for *equality* comparison.
The reason this works interactively is that (most) string literals are [interned](http://en.wikipedia.org/wiki/String_interning) by default. From Wikipedia:
> Interned strings speed up string... |
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result? | 1,504,717 | 593 | 2009-10-01T15:40:14Z | 1,504,870 | 34 | 2009-10-01T16:04:48Z | [
"python",
"string",
"comparison"
] | I've got a Python program where two variables are set to the value `'public'`. In a conditional expression I have the comparison `var1 is var2` which fails, but if I change it to `var1 == var2` it returns `True`.
Now if I open my Python interpreter and do the same "is" comparison, it succeeds.
```
>>> s1 = 'public'
>... | One last thing to note, you may use the intern function to ensure that you're getting a reference to the same string:
```
>>> a = intern('a')
>>> a2 = intern('a')
>>> a is a2
True
```
As pointed out above, you should probably not be doing is to determine equality on strings. But this may be helpful to know if you hav... |
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result? | 1,504,717 | 593 | 2009-10-01T15:40:14Z | 1,505,189 | 17 | 2009-10-01T16:57:09Z | [
"python",
"string",
"comparison"
] | I've got a Python program where two variables are set to the value `'public'`. In a conditional expression I have the comparison `var1 is var2` which fails, but if I change it to `var1 == var2` it returns `True`.
Now if I open my Python interpreter and do the same "is" comparison, it succeeds.
```
>>> s1 = 'public'
>... | If you're not sure what you're doing, use the '=='.
If you have a little more knowledge about it you can use 'is' for known objects like 'None'.
Otherwise you'll end up wondering why things doesn't work and why this happens:
```
>>> a = 1
>>> b = 1
>>> b is a
True
>>> a = 6000
>>> b = 6000
>>> b is a
False
```
I'm n... |
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result? | 1,504,717 | 593 | 2009-10-01T15:40:14Z | 1,505,779 | 18 | 2009-10-01T18:51:32Z | [
"python",
"string",
"comparison"
] | I've got a Python program where two variables are set to the value `'public'`. In a conditional expression I have the comparison `var1 is var2` which fails, but if I change it to `var1 == var2` it returns `True`.
Now if I open my Python interpreter and do the same "is" comparison, it succeeds.
```
>>> s1 = 'public'
>... | This is a side note, but in idiomatic python, you will often see things like:
```
if x is None:
# some clauses
```
This is safe, because [there is guaranteed to be one instance of the Null Object (i.e., None)](http://docs.python.org/library/stdtypes.html#the-null-object). |
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result? | 1,504,717 | 593 | 2009-10-01T15:40:14Z | 16,269,793 | 18 | 2013-04-29T00:56:52Z | [
"python",
"string",
"comparison"
] | I've got a Python program where two variables are set to the value `'public'`. In a conditional expression I have the comparison `var1 is var2` which fails, but if I change it to `var1 == var2` it returns `True`.
Now if I open my Python interpreter and do the same "is" comparison, it succeeds.
```
>>> s1 = 'public'
>... | `is` is identity testing, `==` is equality testing. What this means is that `is` is a way to check whether two things are the *same* things, or just equivalent.
Say you've got a simple `person` object. If it is named 'Jack' and is '23' years old, it's equivalent to another 23yr old Jack, but its not the same person.
... |
Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result? | 1,504,717 | 593 | 2009-10-01T15:40:14Z | 25,208,597 | 7 | 2014-08-08T17:04:58Z | [
"python",
"string",
"comparison"
] | I've got a Python program where two variables are set to the value `'public'`. In a conditional expression I have the comparison `var1 is var2` which fails, but if I change it to `var1 == var2` it returns `True`.
Now if I open my Python interpreter and do the same "is" comparison, it succeeds.
```
>>> s1 = 'public'
>... | I am answering the question even though the question is to old because no answers above quotes the language reference
Actually the is operator checks for identity and == operator checks for equality,
***From Language Reference:***
Types affect almost all aspects of object behavior. Even the importance of object iden... |
Automatically remove *.pyc files and otherwise-empty directories when I check out a new branch | 1,504,724 | 48 | 2009-10-01T15:41:22Z | 1,504,760 | 40 | 2009-10-01T15:48:41Z | [
"git",
"python",
"bash"
] | So here's an interesting situation when using git and python, and I'm sure it happens for other situations as well.
Let's say I make a git repo with a folder /foo/. In that folder I put /foo/program.py. I run program.py and program.pyc is created. I have \*.pyc in the .gitignore file, so git doesn't track it.
Now let... | There is a `post-checkout` hook, to be placed in .git/hooks/post-checkout. There's probably a sample there, possibly named .sample or possibly not executable, depending on your git version. Short description: it gets three parameters, the previous HEAD, the new HEAD, and a flag which is 1 if the branch changed and 0 if... |
Automatically remove *.pyc files and otherwise-empty directories when I check out a new branch | 1,504,724 | 48 | 2009-10-01T15:41:22Z | 1,810,193 | 33 | 2009-11-27T18:46:39Z | [
"git",
"python",
"bash"
] | So here's an interesting situation when using git and python, and I'm sure it happens for other situations as well.
Let's say I make a git repo with a folder /foo/. In that folder I put /foo/program.py. I run program.py and program.pyc is created. I have \*.pyc in the .gitignore file, so git doesn't track it.
Now let... | Just copying and updating a good solution by Apreche that was buried in the comments:
Save this shell script to the file `/path/to/repo/.git/hooks/post-checkout`, and make it executable.
```
#! /bin/sh
# Start from the repository root.
cd ./$(git rev-parse --show-cdup)
# Delete .pyc files and empty directories.
fin... |
Python: json.loads chokes on escapes | 1,505,454 | 11 | 2009-10-01T17:53:17Z | 1,505,477 | 16 | 2009-10-01T17:58:41Z | [
"python",
"json",
"escaping"
] | I have an application that is sending a JSON object (formatted with Prototype) to an ASP server. On the server, the Python 2.6 "json" module tries to loads() the JSON, but it's choking on some combination of backslashes. Observe:
```
>>> s
'{"FileExists": true, "Version": "4.3.2.1", "Path": "\\\\host\\dir\\file.exe"}'... | The correct json is:
```
r'{"FileExists": true, "Version": "4.3.2.1", "Path": "\\\\host\\dir\\file.exe"}'
```
Note the letter `r` if you omit it you need to escape `\` for Python too.
```
>>> import json
>>> d = json.loads(s)
>>> d.keys()
[u'FileExists', u'Path', u'Version']
>>> d.values()
[True, u'\\\\host\\dir\\fi... |
Making a portable (exe) with Python 3.1? | 1,505,783 | 7 | 2009-10-01T18:52:02Z | 1,505,819 | 13 | 2009-10-01T19:00:18Z | [
"python",
"py2exe"
] | Is there a way to make a portable/stand-alone exe for python apps?
I've read about p2exe but it doesn't support the latest version. I'm reluctant to go to 2.6 because I'd rather stay with the latest version instead of worrying about incompatibilities as soon as 2.6 becomes too outdated. | cx\_freeze has worked for me. Here's a link. The page claims to support 3.1. Good luck!
<http://cx-freeze.sourceforge.net/> |
How to use export with Python on Linux | 1,506,010 | 26 | 2009-10-01T19:39:35Z | 1,506,046 | 38 | 2009-10-01T19:46:21Z | [
"python",
"linux",
"export"
] | I need to make an export like this in Python :
```
# export MY_DATA="my_export"
```
I've tried to do :
```
# -*- python-mode -*-
# -*- coding: utf-8 -*-
import os
os.system('export MY_DATA="my_export"')
```
But when I list export, "MY\_DATA" not appear :
```
# export
```
How I can do an export with Python without... | You actually want to do
```
import os
os.environ["MY_DATA"] = "my_export"
``` |
How to use export with Python on Linux | 1,506,010 | 26 | 2009-10-01T19:39:35Z | 1,506,108 | 7 | 2009-10-01T19:58:30Z | [
"python",
"linux",
"export"
] | I need to make an export like this in Python :
```
# export MY_DATA="my_export"
```
I've tried to do :
```
# -*- python-mode -*-
# -*- coding: utf-8 -*-
import os
os.system('export MY_DATA="my_export"')
```
But when I list export, "MY\_DATA" not appear :
```
# export
```
How I can do an export with Python without... | Not that simple:
```
python -c "import os; os.putenv('MY_DATA','1233')"
$ echo $MY_DATA # <- empty
```
But:
```
python -c "import os; os.putenv('MY_DATA','123'); os.system('bash')"
$ echo $MY_DATA #<- 123
``` |
How to use export with Python on Linux | 1,506,010 | 26 | 2009-10-01T19:39:35Z | 1,506,185 | 42 | 2009-10-01T20:11:47Z | [
"python",
"linux",
"export"
] | I need to make an export like this in Python :
```
# export MY_DATA="my_export"
```
I've tried to do :
```
# -*- python-mode -*-
# -*- coding: utf-8 -*-
import os
os.system('export MY_DATA="my_export"')
```
But when I list export, "MY\_DATA" not appear :
```
# export
```
How I can do an export with Python without... | `export` is a command that you give directly to the shell (e.g. `bash`), to tell it to add or modify one of its environment variables. You can't change your shell's environment from a child process (such as Python), it's just not possible.
Here's what's happening with you try `os.system('export MY_DATA="my_export"')`.... |
Cleanest and most Pythonic way to get tomorrow's date? | 1,506,901 | 43 | 2009-10-01T22:45:11Z | 1,506,916 | 90 | 2009-10-01T22:49:11Z | [
"python",
"datetime",
"date",
"time"
] | 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. | `datetime.date.today() + datetime.timedelta(days=1)` should do the trick |
Cleanest and most Pythonic way to get tomorrow's date? | 1,506,901 | 43 | 2009-10-01T22:45:11Z | 1,506,917 | 23 | 2009-10-01T22:49:24Z | [
"python",
"datetime",
"date",
"time"
] | 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. | [`timedelta`](http://docs.python.org/library/datetime.html#timedelta-objects) can handle adding days, seconds, microseconds, milliseconds, minutes, hours, or weeks.
```
>>> import datetime
>>> today = datetime.date.today()
>>> today
datetime.date(2009, 10, 1)
>>> today + datetime.timedelta(days=1)
datetime.date(2009, ... |
How do I get fluent in Python? | 1,507,041 | 10 | 2009-10-01T23:32:12Z | 1,507,045 | 8 | 2009-10-01T23:33:25Z | [
"python"
] | 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 *Python-ic*.
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 inco... | Have you read the [Python Cookbook](http://rads.stackoverflow.com/amzn/click/0596007973)? It's a pretty good source for Pythonic.
Plus you'll find [much more from Alex Martelli on Stack Overflow](http://stackoverflow.com/search?q=user%3a95810%20%5Bpython%5D&tab=votes). |
How do I get fluent in Python? | 1,507,041 | 10 | 2009-10-01T23:32:12Z | 1,507,054 | 10 | 2009-10-01T23:35:48Z | [
"python"
] | 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 *Python-ic*.
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 inco... | Read other people's code. Write some of your own code. Repeat for a year or two.
Study the Python documentation and learn the built-in modules.
Read Python in a Nutshell.
Subscribe your RSS reader to the Python tag on Stack Overflow. |
How do I get fluent in Python? | 1,507,041 | 10 | 2009-10-01T23:32:12Z | 1,507,504 | 7 | 2009-10-02T02:31:13Z | [
"python"
] | 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 *Python-ic*.
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 inco... | I can tell you what I've done.
1. [Idiomatic Python](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html)
2. Bookmark SO with the python keyword.
3. Read other's *good* python code.
4. [The Python Challenge](http://www.pythonchallenge.com/)
That order is probably good, too. This is where things get ... |
Python: is it bad form to raise exceptions within __init__? | 1,507,082 | 59 | 2009-10-01T23:47:38Z | 1,507,127 | 82 | 2009-10-01T23:59:26Z | [
"python",
"exception"
] | 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? | Raising exceptions within `__init__()` 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.
The error class to raise, of course, is up to you. `ValueError` is b... |
Python: is it bad form to raise exceptions within __init__? | 1,507,082 | 59 | 2009-10-01T23:47:38Z | 1,507,130 | 8 | 2009-10-02T00:01:01Z | [
"python",
"exception"
] | 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? | I don't see any reason that it should be bad form.
On the contrary, one of the things exceptions are known for doing well, as opposed to returning error codes, is that error codes usually **can't** be returned by constructors. So at least in languages like C++, raising exceptions is the only way to signal errors. |
Python: is it bad form to raise exceptions within __init__? | 1,507,082 | 59 | 2009-10-01T23:47:38Z | 7,501,167 | 8 | 2011-09-21T14:04:02Z | [
"python",
"exception"
] | 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? | 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 init... |
How to check dimensions of all images in a directory using python? | 1,507,084 | 10 | 2009-10-01T23:47:48Z | 3,175,473 | 13 | 2010-07-04T17:01:48Z | [
"python",
"image",
"directory"
] | 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? | 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:
<http://code.google.com/p/bfg-pages/source/browse/trunk/pages/getimageinfo.py>
```
import StringIO
import struct
def getImageInfo(data):
data = str(data)
size = le... |
python MySQLDB query timeout | 1,507,091 | 7 | 2009-10-01T23:51:06Z | 1,510,167 | 7 | 2009-10-02T15:14:05Z | [
"python",
"timeout",
"mysql"
] | 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 no... | @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....:
```
import multiprocessing
def query_with_timeout(dbc, timeout, query, *a, **k):
conn1, conn2 = multiprocessing.Pipe(False)
subproc = multiprocessing.Process(target=do_q... |
How and when to appropriately use weakref in Python | 1,507,566 | 38 | 2009-10-02T03:03:40Z | 1,507,578 | 23 | 2009-10-02T03:10:11Z | [
"python",
"circular-reference"
] | I have some code where instances of classes have parent<->child references to each other, e.g.:
```
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(), Nod... | Yep, weakref's excellent here. Specifically, instead of:
```
self.children = {}
```
use:
```
self.children = weakref.WeakValueDictionary()
```
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 `children` map that has t... |
How and when to appropriately use weakref in Python | 1,507,566 | 38 | 2009-10-02T03:03:40Z | 1,508,284 | 11 | 2009-10-02T08:17:00Z | [
"python",
"circular-reference"
] | I have some code where instances of classes have parent<->child references to each other, e.g.:
```
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(), Nod... | I suggest using `child.parent = weakref.proxy(self)`. This is good solution to avoid circular references in case when lifetime of (external references to) `parent` covers lifetime of `child`. Contrary, use `weakref` for `child` (as Alex suggested) when lifetime of `child` covers lifetime of `parent`. But never use `wea... |
How does Smalltalk (Pharo for example) compare to Python? | 1,508,256 | 6 | 2009-10-02T08:09:36Z | 1,508,312 | 7 | 2009-10-02T08:26:55Z | [
"python",
"comparison",
"language-features",
"smalltalk",
"language-comparisons"
] | I've seen some comparisons between **Smalltalk and Ruby** on the one hand and **Ruby and Python** on the other, but **not between Python and Smalltalk**. I'd especially like to know what the fundamental differences in Implementation, Syntax, Extensiabillity and Philosophy are.
*For example Python does not seem to have... | Python certainly does have metaclasses.
Smalltalk has some unusual features:
* 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.
* In Sma... |
How does Smalltalk (Pharo for example) compare to Python? | 1,508,256 | 6 | 2009-10-02T08:09:36Z | 1,510,402 | 9 | 2009-10-02T15:54:15Z | [
"python",
"comparison",
"language-features",
"smalltalk",
"language-comparisons"
] | I've seen some comparisons between **Smalltalk and Ruby** on the one hand and **Ruby and Python** on the other, but **not between Python and Smalltalk**. I'd especially like to know what the fundamental differences in Implementation, Syntax, Extensiabillity and Philosophy are.
*For example Python does not seem to have... | > For example Python does not seem to
> have Metaclasses.
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 `type` by default. Python's design philosophy, aka "The Zen of Python", can be perused by doing `import this` at an interacti... |
fast string modification in python | 1,508,464 | 4 | 2009-10-02T09:06:17Z | 1,510,511 | 9 | 2009-10-02T16:12:59Z | [
"python",
"string"
] | This is partially a theoretical question:
I have a string (say UTF-8), and I need to modify it so that each character (not byte) becomes 2 characters, for instance:
```
"Nissim" becomes "N-i-s-s-i-m-"
"01234" becomes "0a1b2c3d4e"
```
and so on.
I would suspect that naive concatenation in a loop would be too expens... | @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), **but** measuring a single case, as in all the `timeit` examples proffered so far, misses a crucial consideration -- **big-O**.
Your instinc... |
Log exception with traceback | 1,508,467 | 56 | 2009-10-02T09:07:15Z | 1,508,761 | 84 | 2009-10-02T10:24:09Z | [
"python",
"exception",
"logging",
"error-handling"
] | How can I log my Python errors?
```
try:
do_something()
except:
# How can I log my exception here, complete with its traceback?
``` | Use [`logging.exception`](https://docs.python.org/library/logging.html#logging.exception) from with an `except:` handler to log the current exception, prepended with a message.
```
import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
logging.debug('T... |
Log exception with traceback | 1,508,467 | 56 | 2009-10-02T09:07:15Z | 9,929,970 | 31 | 2012-03-29T16:58:57Z | [
"python",
"exception",
"logging",
"error-handling"
] | How can I log my Python errors?
```
try:
do_something()
except:
# How can I log my exception here, complete with its traceback?
``` | 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 `traceback.print_exception`.
I have a write up at [http://www.bbarrows.com/](http://www.bbarrows.com... |
Log exception with traceback | 1,508,467 | 56 | 2009-10-02T09:07:15Z | 29,556,246 | 16 | 2015-04-10T08:00:52Z | [
"python",
"exception",
"logging",
"error-handling"
] | How can I log my Python errors?
```
try:
do_something()
except:
# How can I log my exception here, complete with its traceback?
``` | Use exc\_info options may be better, remains warning or error title:
```
try:
# coode in here
except Exception, e:
logging.error(e, exc_info=True)
``` |
python 2.6 or python 3.1? | 1,508,906 | 6 | 2009-10-02T11:03:38Z | 1,508,929 | 10 | 2009-10-02T11:12:05Z | [
"python"
] | 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 =)
---
edit: Is the difference really big between the two? If I learn python 2 will i have trouble learning python 3? | I would go with 2.6 for a couple of reasons.
1. 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.
2. The majority of libraries you'll want to pull in are still aimed at 2.6. This will change in ... |
python 2.6 or python 3.1? | 1,508,906 | 6 | 2009-10-02T11:03:38Z | 1,509,018 | 15 | 2009-10-02T11:37:37Z | [
"python"
] | 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 =)
---
edit: Is the difference really big between the two? If I learn python 2 will i have trouble learning python 3? | * If you're looking to **develop software
right now** stick with Python 2.6.
* If
you're looking to **learn the language
and experiment** go with Python
3.1.
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'r... |
Parsing large pseudo-xml files in python | 1,508,938 | 4 | 2009-10-02T11:15:49Z | 1,508,976 | 10 | 2009-10-02T11:26:55Z | [
"python",
"xml"
] | 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?
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... | <http://docs.python.org/library/xml.sax.html>
Note, that you can pass a 'stream' object to `xml.sax.parse`. This means you can probably pass any object that has file-like methods (like `read`) to the `parse` call... Make your own object, which will firstly put your virtual root start-tag, then the contents of file, th... |
How to make this Python program compile? | 1,510,609 | 4 | 2009-10-02T16:28:09Z | 1,510,617 | 7 | 2009-10-02T16:29:34Z | [
"python",
"syntax-error"
] | I have this Python code:
```
import re
s = "aa67bc54c9"
for t, n in re.findall(r"([a-z]+)([0-9]+)", s)
```
And I get this error message when I try to run it:
```
File "<stdin>", line 1
for t, n in re.findall(r"([a-z]+)([0-9]+)", s)
^
SyntaxError: invalid syntax
... | `for` starts a loop, so you need to end the line with a `:`, and put the loop body, indented, on the following lines.
EDIT:
For further information I suggest you go to the [main documentation](http://docs.python.org/reference/compound%5Fstmts.html#the-for-statement). |
py2exe and the file system | 1,511,461 | 3 | 2009-10-02T19:49:55Z | 1,844,634 | 10 | 2009-12-04T03:20:38Z | [
"python",
"configuration",
"file",
"py2exe"
] | I have a Python app. It loads config files (and various other files) by
doing stuff such as:
```
_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONFIG_DIR = os.path.join(_path, 'conf')
```
This works fine. However, when I package the app with py2exe, bad things happen:
```
File "proj\config.py... | The usual approach to doing this sort of thing (if I understand properly) is this:
1. check sys.frozen, which py2exe contrives to set, using something like getattr(sys, 'frozen', '')
2. if that's not set, use the usual method since you're running from source
3. if it's set, check sys.executable since that will point y... |
Parse a cron entry in Python | 1,511,854 | 4 | 2009-10-02T21:22:56Z | 1,516,146 | 7 | 2009-10-04T10:55:53Z | [
"python",
"module",
"cron"
] | All. I am trying to find a python module that I can use to parse a cron entry and get the next time it will run. With perl I use the Schedule::Cron::Events module but I would like to convert to python. Thanks in advance. | The documentation for python-crontab is in [docstrings](http://en.wikipedia.org/wiki/Docstring#Python) in the source code, as is usual for python. You can also explore the documentation via the python interpreter with the built-in `help()` function. The full source for python-crontab is less than 500 lines anyway and i... |
Django: Get an object form the DB, or 'None' if nothing matches | 1,512,059 | 73 | 2009-10-02T22:15:33Z | 1,512,094 | 113 | 2009-10-02T22:27:49Z | [
"python",
"django"
] | Is there any Django function which will let me get an object form the database, or None if nothing matches?
Right now I'm using something like:
```
foo = Foo.objects.filter(bar=baz)
foo = len(foo) > 0 and foo.get() or None
```
But that's not very clear, and it's messy to have everywhere. | There are two ways to do this;
```
try:
foo = Foo.objects.get(bar=baz)
except model.DoesNotExist:
foo = None
```
Or you can use a wrapper:
```
def get_or_none(model, *args, **kwargs):
try:
return model.objects.get(*args, **kwargs)
except model.DoesNotExist:
return None
```
Call it li... |
Django: Get an object form the DB, or 'None' if nothing matches | 1,512,059 | 73 | 2009-10-02T22:15:33Z | 1,512,104 | 9 | 2009-10-02T22:30:44Z | [
"python",
"django"
] | Is there any Django function which will let me get an object form the database, or None if nothing matches?
Right now I'm using something like:
```
foo = Foo.objects.filter(bar=baz)
foo = len(foo) > 0 and foo.get() or None
```
But that's not very clear, and it's messy to have everywhere. | Give Foo [its custom manager](http://www.djangoproject.com/documentation/models/custom_managers/). It's pretty easy - just put your code into function in custom manager, set custom manager in your model and call it with `Foo.objects.your_new_func(...)`.
If you need generic function (to use it on any model not just tha... |
Django: Get an object form the DB, or 'None' if nothing matches | 1,512,059 | 73 | 2009-10-02T22:15:33Z | 2,021,833 | 69 | 2010-01-07T16:24:54Z | [
"python",
"django"
] | Is there any Django function which will let me get an object form the database, or None if nothing matches?
Right now I'm using something like:
```
foo = Foo.objects.filter(bar=baz)
foo = len(foo) > 0 and foo.get() or None
```
But that's not very clear, and it's messy to have everywhere. | To add some sample code to sorki's answer (I'd add this as a comment, but this is my first post, and I don't have enough reputation to leave comments), I implemented a get\_or\_none custom manager like so:
```
from django.db import models
class GetOrNoneManager(models.Manager):
"""Adds get_or_none method to objec... |
Django: Get an object form the DB, or 'None' if nothing matches | 1,512,059 | 73 | 2009-10-02T22:15:33Z | 17,938,407 | 59 | 2013-07-30T04:37:02Z | [
"python",
"django"
] | Is there any Django function which will let me get an object form the database, or None if nothing matches?
Right now I'm using something like:
```
foo = Foo.objects.filter(bar=baz)
foo = len(foo) > 0 and foo.get() or None
```
But that's not very clear, and it's messy to have everywhere. | In Django **1.6** you can use the `first()` Queryset method. It returns the first object matched by the queryset, or None if there is no matching object.
Usage:
```
p = Article.objects.order_by('title', 'pub_date').first()
``` |
Django: Get an object form the DB, or 'None' if nothing matches | 1,512,059 | 73 | 2009-10-02T22:15:33Z | 23,548,184 | 10 | 2014-05-08T17:04:40Z | [
"python",
"django"
] | Is there any Django function which will let me get an object form the database, or None if nothing matches?
Right now I'm using something like:
```
foo = Foo.objects.filter(bar=baz)
foo = len(foo) > 0 and foo.get() or None
```
But that's not very clear, and it's messy to have everywhere. | You can also try to use django annoying (it has another useful functions!)
install it with:
```
pip install django-annoying
from annoying.functions import get_object_or_None
get_object_or_None(Foo, bar=baz)
``` |
Determining if stdout for a Python process is redirected | 1,512,457 | 10 | 2009-10-03T00:51:25Z | 1,512,494 | 26 | 2009-10-03T01:11:17Z | [
"python"
] | I've noticed that curl can tell whether or not I'm redirecting its output (in which case it puts up a progress bar).
Is there a reasonable way to do this in a Python script? So:
$ python my\_script.py
Not redirected
$ python my\_script.py > output.txt
Redirected! | ```
import sys
if sys.stdout.isatty():
print "Not redirected"
else:
sys.stderr.write("Redirected!\n")
``` |
Determining if stdout for a Python process is redirected | 1,512,457 | 10 | 2009-10-03T00:51:25Z | 1,512,526 | 7 | 2009-10-03T01:31:14Z | [
"python"
] | I've noticed that curl can tell whether or not I'm redirecting its output (in which case it puts up a progress bar).
Is there a reasonable way to do this in a Python script? So:
$ python my\_script.py
Not redirected
$ python my\_script.py > output.txt
Redirected! | Actually, what you want to do here is find out if `stdin` and `stdout` are the same thing.
```
$ cat test.py
import os
print os.fstat(0) == os.fstat(1)
$ python test.py
True
$ python test.py > f
$ cat f
False
$
```
The longer but more traditional version of the *are they the same file* test just compares `st_ino` and... |
can't install lxml (python 2.6.3, osx 10.6 snow leopard) | 1,512,530 | 4 | 2009-10-03T01:33:26Z | 1,512,681 | 7 | 2009-10-03T03:08:05Z | [
"python",
"osx",
"port",
"osx-leopard",
"lxml"
] | I try to:
> easy\_install lxml
and I get this error:
> File "build/bdist.macosx-10.3-fat/egg/setuptools/command/build\_ext.py", line 85, in get\_ext\_filename
> KeyError: 'etree'
any hints? | Due to incompatible changes in the 2.6.3 version of python's distutils, the old `easy_install` from [setuptools](http://pypi.python.org/pypi/setuptools) no longer works. You need to replace it with `easy_install` from [Distribute](http://pypi.python.org/pypi/distribute). Follow the instructions there, basically:
```
$... |
Is there a portable way of finding if a path is absolute, using Python? | 1,513,155 | 2 | 2009-10-03T08:06:23Z | 1,513,159 | 13 | 2009-10-03T08:08:20Z | [
"python",
"absolute-path"
] | Is there some built-in function that tells me if a path is absolute or not? I'd like something that is platform independent. | The [`os.path.isabs`](http://docs.python.org/library/os.path.html#os.path.isabs) function does this. |
What should I use instead of assignment-in-an-expression in Python? | 1,513,436 | 3 | 2009-10-03T10:33:33Z | 1,514,109 | 10 | 2009-10-03T15:49:48Z | [
"python"
] | according to [this page](http://pyfaq.infogami.com/why-can-t-i-use-an-assignment-in-an-expression) one can't use code like
```
if variable = something():
#do something with variable, whose value is the result of something() and is true
```
So in case I want to have the following code structure:
```
if a = something(... | I had this problem years ago, in 2001 -- since I was transliterating to Python from a reference-algorithm in C which used assign-and-test heavily, I was keen to keep a similar structure for the first draft (then refactor later once correctness was well tested). So I wrote a [recipe](http://books.google.com/books?id=1Sh... |
python: is there an XML parser implemented as a generator? | 1,513,592 | 8 | 2009-10-03T12:14:31Z | 1,513,640 | 14 | 2009-10-03T12:40:25Z | [
"python",
"xml",
"parsing",
"generator"
] | I'd like to parse a big XML file "on the fly". I'd like to use a python generator to perform this. I've tried "iterparse" of "xml.etree.cElementTree" (which is really nice) but still not a generator.
Other suggestions? | `xml.etree.cElementTree` comes close to a generator with correct usage; by default you receive each element after its 'end' event, at which point you can process it. You should use element.clear() on the element if you don't need it after processing; thereby you save the memory.
---
Here is a complete example what I ... |
Python .sort() not working as expected | 1,513,727 | 3 | 2009-10-03T13:22:03Z | 1,513,735 | 16 | 2009-10-03T13:25:20Z | [
"python",
"list",
"sorting"
] | Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren't quite what I expect. The program iterates through every combination from 100 - 999 and checks if the product is a palindome. If it is, append to the list. I need the list sorted :D Here's my progr... | You are sorting strings, not numbers. `'101101' < '10201'` because `'1' < '2'`. Change `list.append(reversed)` to `list.append(int(reversed))` and it will work (or use a different sorting function). |
Python .sort() not working as expected | 1,513,727 | 3 | 2009-10-03T13:22:03Z | 1,513,790 | 8 | 2009-10-03T13:45:35Z | [
"python",
"list",
"sorting"
] | Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren't quite what I expect. The program iterates through every combination from 100 - 999 and checks if the product is a palindome. If it is, append to the list. I need the list sorted :D Here's my progr... | Sort is doing its job. If you intended to store integers in the list, take Lukáš advice. You can also tell sort how to sort, for example by making ints:
```
list.sort(key=int)
```
the key parameter takes a function that calculates an item to take the list object's place in all comparisons. An integer will compare n... |
Python Implementation of the Object Pool Design Pattern | 1,514,120 | 18 | 2009-10-03T15:55:44Z | 1,514,269 | 20 | 2009-10-03T16:57:21Z | [
"python",
"design-patterns",
"data-structures"
] | I need an [Object Pool](http://en.wikipedia.org/wiki/Object_pool), and rather than implement it myself, I thought I would look around for a ready-made and tested Python library.
What I found was plenty of other people [looking](http://mail.python.org/pipermail/python-list/2009-July/719988.html), but not getting many s... | It seems to me, from your description, that what you need is a pool of *connections*, not of objects. For simple thread-safety, just keep the reusable connections in a `Queue.Queue` instance, call it `pool`. When a thread instantiates a connection-wrapping object, the object gets its connection via `pool.get()` (which ... |
Is it reasonable to save data as python modules? | 1,514,228 | 3 | 2009-10-03T16:40:01Z | 1,514,250 | 7 | 2009-10-03T16:48:31Z | [
"python",
"data-persistence",
"dynamic-import"
] | This is what I've done for a project. I have a few data structures that are bascially dictionaries with some methods that operate on the data. When I save them to disk, I write them out to .py files as code that when imported as a module will load the same data into such a data structure.
Is this reasonable? Are there... | By operating this way, you may gain some modicum of convenience, but you pay many kinds of price for that. The space it takes to save your data, and the time it takes to both save and reload it, go up substantially; and your security exposure is unbounded -- you must ferociously guard the paths from which you reload mo... |
C#: Does a dictionary in C# have something similar to the Python setdefault? | 1,514,457 | 3 | 2009-10-03T18:10:29Z | 1,514,470 | 12 | 2009-10-03T18:16:12Z | [
"c#",
"python",
"dictionary"
] | Trying to translate [some methods](http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number/118712#118712) written in Python over into C#. The line looks like this:
```
d[p] = d.setdefault(p, 0) + 1
```
What exactly does setdefault do? And is there anything similar I c... | From the [Python docs](http://docs.python.org/library/stdtypes.html):
> `setdefault(key[, default])`
>
> If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.
There is no direct implementation of this in the .NET framework, but you can ... |
How to declare an array in Python? | 1,514,553 | 198 | 2009-10-03T19:03:40Z | 1,514,557 | 168 | 2009-10-03T19:07:12Z | [
"python",
"arrays"
] | How do I declare an array in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
I can't find any reference to arrays in the documentation. | ```
variable = []
```
Now `variable` refers to an empty list\*.
Of course this is an assignment, not a declaration. There's no way to say in Python "this variable should never refer to anything other than a list", since Python is dynamically typed.
---
\*The default built-in Python type is called a *list*, not an a... |
How to declare an array in Python? | 1,514,553 | 198 | 2009-10-03T19:03:40Z | 1,514,559 | 12 | 2009-10-03T19:07:49Z | [
"python",
"arrays"
] | How do I declare an array in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
I can't find any reference to arrays in the documentation. | This is how:
```
my_array = [1, 'rebecca', 'allard', 15]
``` |
How to declare an array in Python? | 1,514,553 | 198 | 2009-10-03T19:03:40Z | 1,514,561 | 15 | 2009-10-03T19:08:05Z | [
"python",
"arrays"
] | How do I declare an array in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
I can't find any reference to arrays in the documentation. | You don't declare anything in Python. You just use it. I recommend you start out with something like <http://diveintopython.net>. |
How to declare an array in Python? | 1,514,553 | 198 | 2009-10-03T19:03:40Z | 1,514,564 | 9 | 2009-10-03T19:09:13Z | [
"python",
"arrays"
] | How do I declare an array in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
I can't find any reference to arrays in the documentation. | I would normally just do `a = [1,2,3]` which is actually a `list` but for `arrays` look at this formal [definition](http://docs.python.org/library/array.html) |
How to declare an array in Python? | 1,514,553 | 198 | 2009-10-03T19:03:40Z | 1,514,649 | 56 | 2009-10-03T19:44:18Z | [
"python",
"arrays"
] | How do I declare an array in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
I can't find any reference to arrays in the documentation. | You don't actually declare things, but this is how you create an array in Python:
```
from array import array
intarray = array('i')
```
For more info see the array module: <http://docs.python.org/library/array.html>
Now possible you don't want an array, but a list, but others have answered that already. :) |
How to declare an array in Python? | 1,514,553 | 198 | 2009-10-03T19:03:40Z | 4,476,624 | 33 | 2010-12-18T04:25:20Z | [
"python",
"arrays"
] | How do I declare an array in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
I can't find any reference to arrays in the documentation. | I think you (meant)want an list with the first 30 cells already filled.
So
```
f = []
for i in range(30):
f.append(0)
```
An example to where this could be used is in Fibonacci sequence.
See problem 2 in [Project Euler](http://projecteuler.net/) |
How to declare an array in Python? | 1,514,553 | 198 | 2009-10-03T19:03:40Z | 6,768,818 | 9 | 2011-07-20T21:31:58Z | [
"python",
"arrays"
] | How do I declare an array in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
I can't find any reference to arrays in the documentation. | for calculations, use [numpy](http://numpy.scipy.org/) arrays like this:
```
import numpy as np
a = np.ones((3,2)) # a 2D array with 3 rows, 2 columns, filled with ones
b = np.array([1,2,3]) # a 1D array initialised using a list [1,2,3]
c = np.linspace(2,3,100) # an array with 100 points beteen (and inclu... |
How to declare an array in Python? | 1,514,553 | 198 | 2009-10-03T19:03:40Z | 36,042,565 | 7 | 2016-03-16T17:16:04Z | [
"python",
"arrays"
] | How do I declare an array in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29)?
I can't find any reference to arrays in the documentation. | This is surprisingly complex topic in Python.
# Practical answer
Arrays are represented by class `list` (see [reference](https://docs.python.org/2/tutorial/datastructures.html) and do not mix them with [generators](https://wiki.python.org/moin/Generators)).
Check out usage examples:
```
# empty array
arr = []
# i... |
Neural Network Example Source-code (preferably Python) | 1,514,573 | 11 | 2009-10-03T19:13:20Z | 1,514,631 | 7 | 2009-10-03T19:35:38Z | [
"python",
"neural-network"
] | I wonder if anyone has some example code of a Neural network in python. If someone know of some sort of tutorial with a complete walkthrough that would be awesome, but just example source would be great as well!
Thanks | Here is a simple example by Armin Rigo: <http://codespeak.net/pypy/dist/demo/bpnn.py>.
If you want to use more sophisticated stuff, there is also <http://pybrain.org>.
**Edit:** Link is broken. Anyway, the current way to go with neural nets in python is probably [Theano](http://deeplearning.net/software/theano/index.h... |
Display Pretty Code in Django | 1,514,874 | 3 | 2009-10-03T21:11:56Z | 1,514,879 | 8 | 2009-10-03T21:13:49Z | [
"python",
"html",
"django"
] | I'm looking for something I can use within django to display preformatted code. Ideally this would include out-of-the-box syntax highlighting for various programming languages, although just starting with something that displayed html and xml well would be a good starting point.
Does something like this exist?
Basica... | You could use [Pygments](http://pygments.org) to do the syntax highlighting and get HTML to display.
Example code :
```
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
highlighted = highlight('# Some Python code', PythonLexer(), HtmlFormatter())
``... |
Entity groups in Google App Engine Datastore | 1,515,135 | 6 | 2009-10-03T23:27:57Z | 2,016,369 | 11 | 2010-01-06T21:26:32Z | [
"python",
"google-app-engine",
"schemaless"
] | So I have an app that if I'm honest doesn't really need transactional integrity (lots of updates, none of them critical). So I was planning on simply leaving entity groups by the wayside for now. But I'd still like to understand it (coming from a relational background).
The way I see it, all queries for my app will be... | > The way I see it, if I want transactions (on a per-user basis), I will need some kind of root user entity as the parent of all entities that are part of the hierarchy of her data, no matter how thin this entity would actually be i.e. basically no properties.
I wouldn't just create a root user entity and throw everyt... |
Simple example of how to use ast.NodeVisitor? | 1,515,357 | 31 | 2009-10-04T01:38:14Z | 1,515,403 | 59 | 2009-10-04T02:05:23Z | [
"python",
"python-2.6",
"abstract-syntax-tree"
] | Does anyone have a simple example using ast.NodeVisitor to walk the abstract syntax tree in Python 2.6? The difference between visit and generic\_visit is unclear to me, and I cannot find any example using google codesearch or plain google. | `ast.visit` -- unless you override it in a subclass, of course -- when called to visit an `ast.Node` of class `foo`, calls `self.visit_foo` if that method exists, otherwise `self.generic_visit`. The latter, again in its implementation in class `ast` itself, just calls `self.visit` on every child node (and performs no o... |
Simple example of how to use ast.NodeVisitor? | 1,515,357 | 31 | 2009-10-04T01:38:14Z | 26,374,977 | 7 | 2014-10-15T05:17:50Z | [
"python",
"python-2.6",
"abstract-syntax-tree"
] | Does anyone have a simple example using ast.NodeVisitor to walk the abstract syntax tree in Python 2.6? The difference between visit and generic\_visit is unclear to me, and I cannot find any example using google codesearch or plain google. | Looking at the code in [ast.py](https://github.com/python/cpython/blob/master/Lib/ast.py) it's not that hard to copy paste and roll your own walker. E.g.
```
import ast
def str_node(node):
if isinstance(node, ast.AST):
fields = [(name, str_node(val)) for name, val in ast.iter_fields(node) if name not in ('... |
Case insensitive urls for Django? | 1,515,634 | 28 | 2009-10-04T04:56:10Z | 1,515,657 | 71 | 2009-10-04T05:12:44Z | [
"python",
"django"
] | It seems by default django's url solver perform case sensitive search for solving url and differentiate between '/Login' and 'login'. My url patterns are as follows.
```
urlpatterns = patterns('',
(r'^admin/(.*)', admin.site.root),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root... | Just put `(?i)` at the start of every `r'...'` string, i.e.:
```
urlpatterns = patterns('',
(r'^(?i)admin/(.*)', admin.site.root),
(r'^(?i)static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_DOC_ROOT, 'show_indexes': True}),
(r'^(?i)login/$', 'django.contrib.auth.views.login'),
(r... |
how to run both python 2.6 and 3.0 on the same windows XP box? | 1,515,850 | 3 | 2009-10-04T07:45:12Z | 1,515,859 | 9 | 2009-10-04T07:51:59Z | [
"python",
"windows-xp"
] | What kind of setup do people use to run both python 2.6 and python 3.0 on the same windows machine? | No problem, each version is installed in its own directory. On my Windows box, I have `C:\Python26\` and `C:\Python31\`. The *Start Menu* items are also distinct. Just use the standard installers from the Python Programming Language [Official Website](http://www.python.org/download/), or the ready-to-install distributi... |
Python: List Sorting with Multiple Attributes and Mixed Order | 1,516,249 | 12 | 2009-10-04T12:10:07Z | 1,516,449 | 22 | 2009-10-04T13:48:13Z | [
"python",
"list",
"sorting"
] | I have to sort a python list, with multiple attributes. I can do that in ascending order for ALL attributes easily with
```
L.sort(key=operator.attrgetter(attribute))....
```
but the problem is, that I have use mixed configurations for ascending/descending... I have to "imitate" a bit the SQL Order By where you can d... | If your attributes are numeric, you have this.
```
def mixed_order( a ):
return ( a.attribute1, -a.attribute2 )
someList.sort( key=mixed_order )
```
If your attributes includes strings or other more complex objects, you have some choices.
The `.sort()` method is stable: you can do multiple passes. This is perha... |
python varargs before function name? | 1,516,467 | 2 | 2009-10-04T13:56:21Z | 1,516,477 | 11 | 2009-10-04T13:59:53Z | [
"python",
"varargs"
] | I'm doing some Python coding in a clients code base and I stumbled on a line of code that looks something like this (the variable names have been changed to protect the innocent):
```
reply = function1(a=foo, **function2(bar, b=baz))
```
Normally \*\* in the argument list collects remaining keyword arguments but what... | I'd say that this is just calling a function that returns a dict-like object and therefor the asterisks just convert the returned dict into the keyword arguments for function1, just as usual. |
sqlite3 in Python | 1,516,508 | 6 | 2009-10-04T14:13:24Z | 1,516,527 | 9 | 2009-10-04T14:22:18Z | [
"python",
"sqlite3"
] | How do I check if the database file already exists or not?
And, if the it exists, how do I check if it already has a specific table or not? | To see if a database exists, you can [`sqlite3.connect`](http://docs.python.org/library/sqlite3.html#sqlite3.connect) to the file that you think contains the database, and try running a query on it. If it is *not* a database, you will get this error:
```
>>> c.execute("SELECT * FROM tbl")
Traceback (most recent call l... |
Python insert not getting desired results? | 1,516,889 | 3 | 2009-10-04T17:07:30Z | 1,516,896 | 12 | 2009-10-04T17:11:18Z | [
"python"
] | #!/usr/bin/python
```
numbers = [1, 2, 3, 5, 6, 7]
clean = numbers.insert(3, 'four')
print clean
# desire results [1, 2, 3, 'four', 5, 6, 7]
```
I am getting "None". What am I doing wrong? | Mutating-methods on lists tend to return `None`, **not** the modified list as you expect -- such metods perform their effect by altering the list in-place, not by building and returning a new one. So, `print numbers` instead of `print clean` will show you the altered list.
If you need to keep `numbers` intact, first y... |
python refresh/reload | 1,517,038 | 21 | 2009-10-04T18:23:26Z | 1,517,072 | 17 | 2009-10-04T18:40:08Z | [
"python",
"refresh",
"reload"
] | This is a very basic question - but I haven't been able to find an answer by searching online.
I am using python to control ArcGIS, and I have a simple python script, that calls some pre-written code.
However, when I make a change to the pre-written code, it does not appear to result in any change. I import this modu... | One way to do this is to call [`reload`](http://docs.python.org/library/functions.html#reload).
Example: Here is the contents of `foo.py`:
```
def bar():
return 1
```
In an interactive session, I can do:
```
>>> import foo
>>> foo.bar()
1
```
Then in another window, I can change `foo.py` to:
```
def bar():
... |
python refresh/reload | 1,517,038 | 21 | 2009-10-04T18:23:26Z | 1,517,087 | 24 | 2009-10-04T18:46:24Z | [
"python",
"refresh",
"reload"
] | This is a very basic question - but I haven't been able to find an answer by searching online.
I am using python to control ArcGIS, and I have a simple python script, that calls some pre-written code.
However, when I make a change to the pre-written code, it does not appear to result in any change. I import this modu... | It's unclear what you mean with "refresh", but the normal behavior of Python is that you need to restart the software for it to take a new look on a Python module and reread it.
If your changes isn't taken care of even after restart, then this is due to one of two errors:
1. The timestamp on the pyc-file is incorrect... |
How do I install SciPy on 64 bit Windows? | 1,517,129 | 54 | 2009-10-04T19:01:43Z | 1,523,358 | 29 | 2009-10-06T02:47:52Z | [
"python",
"windows",
"64bit",
"numpy",
"scipy"
] | How do I install SciPy on my system?
For the NumPy part (that SciPy depends on) there is actually an installer for 64 bit Windows: [numpy-1.3.0.win-amd64-py2.6.msi](http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0/numpy-1.3.0.win-amd64-py2.6.msi) (is direct download URL, 2310144 bytes).
Running the SciPy super... | Short answer: windows 64 support is still work in progress at this time. The superpack will certainly not work on a 64 bits python (but it should work fine on a 32 bits python, even on windows 64).
The main issue with windows 64 is that building with mingw-w64 is not stable at this point: it may be our's (numpy devs) ... |
How do I install SciPy on 64 bit Windows? | 1,517,129 | 54 | 2009-10-04T19:01:43Z | 2,114,531 | 52 | 2010-01-22T02:18:23Z | [
"python",
"windows",
"64bit",
"numpy",
"scipy"
] | How do I install SciPy on my system?
For the NumPy part (that SciPy depends on) there is actually an installer for 64 bit Windows: [numpy-1.3.0.win-amd64-py2.6.msi](http://dfn.dl.sourceforge.net/project/numpy/NumPy/1.3.0/numpy-1.3.0.win-amd64-py2.6.msi) (is direct download URL, 2310144 bytes).
Running the SciPy super... | Unofficial 64-bit installers for [NumPy](http://en.wikipedia.org/wiki/NumPy) and [SciPy](http://en.wikipedia.org/wiki/SciPy) are available at <http://www.lfd.uci.edu/~gohlke/pythonlibs/> |
Basic cocoa application using dock in Python, but not Xcode and all that extras | 1,517,342 | 2 | 2009-10-04T20:46:22Z | 1,517,691 | 8 | 2009-10-04T23:18:09Z | [
"python",
"cocoa",
"pyobjc",
"dock"
] | It seems that if I want to create a very basic Cocoa application with a dock icon and the like, I would [have to use](http://developer.apple.com/cocoa/pyobjc.html) Xcode and the GUI builder (w/ **PyObjC**).
The application I am intending to write is largely concerned with algorithms and basic IO - and thus, not mostly... | Install the latest [py2app](http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html), then make a new directory -- cd to it -- in it make a `HelloWorld.py` file such as:
```
# generic Python imports
import datetime
import os
import sched
import sys
import tempfile
import threading
import time
# need PyObjC on sys... |
About Python's built in sort() method | 1,517,347 | 43 | 2009-10-04T20:48:00Z | 1,517,363 | 60 | 2009-10-04T20:53:10Z | [
"python",
"algorithm",
"sorting",
"python-internals"
] | What algorithm is the built in `sort()` method in Python using? Is it possible to have a look at the code for that method? | Sure! The code's [here](http://svn.python.org/view/python/trunk/Objects/listobject.c?revision=69227&view=markup), starting with function `islt` and proceeding for QUITE a while;-). As Chris's comment suggests, it's C code. You'll also want to read [this](http://svn.python.org/view/python/trunk/Objects/listsort.txt?revi... |
About Python's built in sort() method | 1,517,347 | 43 | 2009-10-04T20:48:00Z | 1,517,648 | 19 | 2009-10-04T23:03:41Z | [
"python",
"algorithm",
"sorting",
"python-internals"
] | What algorithm is the built in `sort()` method in Python using? Is it possible to have a look at the code for that method? | I just wanted to supply a very helpful link that I missed in Alex's otherwise comprehensive answer: [A high-level explanation of Python's timsort](http://corte.si/posts/code/timsort/index.html) (with graph visualizations!).
(Yes, the algorithm is basically known as [Timsort](http://en.wikipedia.org/wiki/Timsort) now) |
Closing sockets in python | 1,517,418 | 3 | 2009-10-04T21:24:44Z | 1,517,457 | 11 | 2009-10-04T21:44:33Z | [
"python",
"sockets",
"try-catch"
] | I'm modifying Python code that have this form:
```
def foo(self):
try:
connect socket
except Exception, e:
some error reporting stuff
return an error
use the socket
do some other stuff
if some condition:
return
do some more stuff
socket.close()
return ... | You can use a `try-finally` block, which was added in Python 2.5:
```
try:
open socket
do stuff with socket
finally:
close socket
```
Or you can use the `with` statement, which was added in Python 2.6 (and can be used in 2.5 with a `from __future__ import with_statement` declaration):
```
with open_the_s... |
Stream large binary files with urllib2 to file | 1,517,616 | 44 | 2009-10-04T22:50:47Z | 1,517,728 | 79 | 2009-10-04T23:42:58Z | [
"python",
"file",
"streaming",
"urllib2"
] | I use the following code to stream large files from the Internet into a local file:
```
fp = open(file, 'wb')
req = urllib2.urlopen(url)
for line in req:
fp.write(line)
fp.close()
```
This works but it downloads quite slowly. Is there a faster way? (The files are large so I don't want to keep them in memory.) | No reason to work line by line (small chunks AND requires Python to find the line ends for you!-), just chunk it up in bigger chunks, e.g.:
```
from urllib2 import urlopen # Python 2
# from urllib.request import urlopen # Python 3
response = urlopen(url)
CHUNK = 16 * 1024
with open(file, 'wb') as f:
while True:
... |
Stream large binary files with urllib2 to file | 1,517,616 | 44 | 2009-10-04T22:50:47Z | 5,397,438 | 56 | 2011-03-22T20:28:18Z | [
"python",
"file",
"streaming",
"urllib2"
] | I use the following code to stream large files from the Internet into a local file:
```
fp = open(file, 'wb')
req = urllib2.urlopen(url)
for line in req:
fp.write(line)
fp.close()
```
This works but it downloads quite slowly. Is there a faster way? (The files are large so I don't want to keep them in memory.) | You can also use [shutil](http://docs.python.org/library/shutil.html):
```
import shutil
from urllib2 import urlopen # Python 2
# from urllib.request import urlopen # Python 3
req = urlopen(url)
with open(file, 'wb') as fp:
shutil.copyfileobj(req, fp)
``` |
Is it possible to save a list of values into a SQLite column? | 1,517,771 | 4 | 2009-10-05T00:26:26Z | 1,518,067 | 8 | 2009-10-05T02:45:13Z | [
"python",
"sqlite"
] | I want 3 columns to have 9 different values, like a list in Python.
Is it possible? If not in SQLite, then on another database engine? | You must serialize the list (or other Python object) into a string of bytes, aka "BLOB";-), through your favorite means (`marshal` is good for lists of elementary values such as numbers or strings &c, `cPickle` if you want a very general solution, etc), and deserialize it when you fetch it back. Of course, that basical... |
Using lookahead with generators | 1,517,862 | 16 | 2009-10-05T01:10:55Z | 1,517,965 | 13 | 2009-10-05T02:03:46Z | [
"python",
"generator",
"lookahead"
] | I have implemented a generator-based scanner in Python that tokenizes a string into tuples of the form *(token type, token value)*:
```
for token in scan("a(b)"):
print token
```
would print
```
("literal", "a")
("l_paren", "(")
...
```
The next task implies parsing the token stream and for that, I need be able... | You can write a wrapper that buffers some number of items from the generator, and provides a lookahead() function to peek at those buffered items:
```
class Lookahead:
def __init__(self, iter):
self.iter = iter
self.buffer = []
def __iter__(self):
return self
def next(self):
... |
Using lookahead with generators | 1,517,862 | 16 | 2009-10-05T01:10:55Z | 1,518,097 | 18 | 2009-10-05T03:00:18Z | [
"python",
"generator",
"lookahead"
] | I have implemented a generator-based scanner in Python that tokenizes a string into tuples of the form *(token type, token value)*:
```
for token in scan("a(b)"):
print token
```
would print
```
("literal", "a")
("l_paren", "(")
...
```
The next task implies parsing the token stream and for that, I need be able... | Pretty good answers there, but my favorite approach would be to use `itertools.tee` -- given an iterator, it returns two (or more if requested) that can be advanced independently. It buffers in memory just as much as needed (i.e., not much, if the iterators don't get very "out of step" from each other). E.g.:
```
impo... |
What's the best way to read python documentation for all installed packages? | 1,517,885 | 5 | 2009-10-05T01:20:07Z | 1,517,890 | 9 | 2009-10-05T01:25:04Z | [
"python",
"documentation"
] | I use python.org a lot for reading python documentation. I also use ipython help function, but I would prefer a GUI app that I could run on my machine that would show documentation for all installed packages.
Do you know if anything like this exists?
Do you have any suggestions? | The `pydoc` command has a built-in HTTP server, which you can start with:
```
pydoc -p 8080
```
Then head to <http://localhost:8080/> in your browser. It will have documentation for all modules installed on its search path, which includes anything in `site-packages`. |
Django - use reverse url mapping in settings | 1,518,286 | 28 | 2009-10-05T04:40:49Z | 1,519,675 | 39 | 2009-10-05T12:03:31Z | [
"python",
"django",
"url",
"dry"
] | A few of the options in the django settings file are urls, for example `LOGIN_URL` and `LOGIN_REDIRECT_URL`. Is it possible to avoid hardcoding these urls, and instead use reverse url mapping? At the moment this is really the only place where I find myself writing the same urls in multiple places. | # Django 1.5 and later
As of Django 1.5, `LOGIN_URL` and `LOGIN_REDIRECT_URL` accept named URL patterns. That means you don't need to hardcode any urls in your settings.
```
LOGIN_URL = 'login' # name of url pattern
```
For Django 1.5 - 1.9, you can also use the view function name, but this is deprecated in Django 1... |
Django - use reverse url mapping in settings | 1,518,286 | 28 | 2009-10-05T04:40:49Z | 8,790,991 | 11 | 2012-01-09T15:42:51Z | [
"python",
"django",
"url",
"dry"
] | A few of the options in the django settings file are urls, for example `LOGIN_URL` and `LOGIN_REDIRECT_URL`. Is it possible to avoid hardcoding these urls, and instead use reverse url mapping? At the moment this is really the only place where I find myself writing the same urls in multiple places. | In django development version reverse\_lazy() becomes an option:
<https://docs.djangoproject.com/en/dev/ref/urlresolvers/#reverse-lazy> |
Python most common element in a list | 1,518,522 | 63 | 2009-10-05T06:35:44Z | 1,518,531 | 8 | 2009-10-05T06:39:56Z | [
"python",
"list"
] | What is an efficient way to find the most common element in a Python list?
My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:
```
>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goo... | If they are not hashable, you can sort them and do a single loop over the result counting the items (identical items will be next to each other). But it might be faster to make them hashable and use a dict.
```
def most_common(lst):
cur_length = 0
max_length = 0
cur_i = 0
max_i = 0
cur_item = None
... |
Python most common element in a list | 1,518,522 | 63 | 2009-10-05T06:35:44Z | 1,518,632 | 253 | 2009-10-05T07:14:52Z | [
"python",
"list"
] | What is an efficient way to find the most common element in a Python list?
My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:
```
>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goo... | A simpler one-liner:
```
def most_common(lst):
return max(set(lst), key=lst.count)
``` |
Python most common element in a list | 1,518,522 | 63 | 2009-10-05T06:35:44Z | 1,520,716 | 49 | 2009-10-05T15:16:29Z | [
"python",
"list"
] | What is an efficient way to find the most common element in a Python list?
My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:
```
>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goo... | With so many solutions proposed, I'm amazed nobody's proposed what I'd consider an obvious one (for non-hashable but comparable elements) -- [`itertools.groupby`][1]. `itertools` offers fast, reusable functionality, and lets you delegate some tricky logic to well-tested standard library components. Consider for example... |
Python most common element in a list | 1,518,522 | 63 | 2009-10-05T06:35:44Z | 20,872,750 | 45 | 2014-01-01T20:10:48Z | [
"python",
"list"
] | What is an efficient way to find the most common element in a Python list?
My list items may not be hashable so can't use a dictionary.
Also in case of draws the item with the lowest index should be returned. Example:
```
>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goo... | Borrowing from [here](http://stackoverflow.com/questions/10797819/finding-the-mode-of-a-list-in-python), this can be used with Python 2.7:
```
from collections import Counter
def Most_Common(lst):
data = Counter(lst)
return data.most_common(1)[0][0]
```
Works around 4-6 times faster than Alex's solutions, an... |
Python and indentation, having touble getting started | 1,518,659 | 2 | 2009-10-05T07:22:33Z | 1,518,665 | 11 | 2009-10-05T07:24:39Z | [
"python"
] | I have just started learning python and am getting caught up. I come from mostly C background.
```
class Alarm:
def timer():
def main():
print ("Timer has Started")
main()
```
I always get a silly error when I try to run this code::
```
alarm > python alarm.py
File "alarm.py", line 5
def m... | You have an empty def
```
def timer():
```
use
```
def timer():
pass
```
instead. |
How can I detect when a flash drive is plugged in under Linux? | 1,518,699 | 5 | 2009-10-05T07:40:27Z | 1,518,753 | 9 | 2009-10-05T08:02:41Z | [
"python",
"linux"
] | How can I detect when a flash drive is plugged in? I'm using a bare Debian installation, without any GUI and want to be notified in my Python script when a new flash drive appears... I know that D-BUS distributes such information, but i dont want to use D-BUS. Is there a more bare access to that information? Shouldn't ... | All mayor Linux distros include [udev](http://www.reactivated.net/writing%5Fudev%5Frules.html), that allows you to write custom scripts on hardware events. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.