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 |
|---|---|---|---|---|---|---|---|---|---|
Use different Python version with virtualenv | 1,534,210 | 501 | 2009-10-07T21:11:22Z | 11,301,911 | 119 | 2012-07-02T22:17:14Z | [
"python",
"virtualenv",
"virtualenvwrapper"
] | I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?
I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary... | These are steps when you are on shared hosting environment and need to install & complie Python from source and then create venv from your Python version. For Python 2.7.9 you would do something along these lines:
```
mkdir ~/src
wget http://www.python.org/ftp/python/2.7.9/Python-2.7.9.tgz
tar -zxvf Python-2.7.9.tgz
c... |
Use different Python version with virtualenv | 1,534,210 | 501 | 2009-10-07T21:11:22Z | 20,834,097 | 9 | 2013-12-30T05:51:49Z | [
"python",
"virtualenv",
"virtualenvwrapper"
] | I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?
I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary... | Suppose you currently have python 2.7 installed in your virtualenv. But want to make use of python3.2. You would have to update this with:
```
virtualenv --python=/usr/bin/python3.2 name_of_your_virtualenv
```
Then activate your virtualenv and type `python --version` in shell to check whether your version is now upda... |
Use different Python version with virtualenv | 1,534,210 | 501 | 2009-10-07T21:11:22Z | 27,972,633 | 16 | 2015-01-15T20:43:25Z | [
"python",
"virtualenv",
"virtualenvwrapper"
] | I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?
I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary... | Mac OSX 10.6.8 (Snow Leopard):
1) When you do `pip install virtualenv`, the pip command is associated with one of your python versions, and `virtualenv` gets installed into that version of python (you can do
```
$ which pip
```
to see what version of python that is). By default, that will be the version of python t... |
Convert Variable Name to String? | 1,534,504 | 29 | 2009-10-07T22:06:13Z | 1,534,553 | 7 | 2009-10-07T22:15:55Z | [
"python",
"string",
"variables"
] | I would like to convert a python variable name into the string equivalent as shown. Any ideas how?
```
var = {}
print ??? # Would like to see 'var'
something_else = 3
print ??? # Would print 'something_else'
``` | This is not possible.
In Python, there really isn't any such thing as a "variable". What Python really has are "names" which can have objects bound to them. It makes no difference to the object what names, if any, it might be bound to. It might be bound to dozens of different names, or none.
Consider this example:
`... |
Convert Variable Name to String? | 1,534,504 | 29 | 2009-10-07T22:06:13Z | 1,534,618 | 7 | 2009-10-07T22:37:22Z | [
"python",
"string",
"variables"
] | I would like to convert a python variable name into the string equivalent as shown. Any ideas how?
```
var = {}
print ??? # Would like to see 'var'
something_else = 3
print ??? # Would print 'something_else'
``` | Technically the information is available to you, but as others have asked, how would you make use of it in a sensible way?
```
>>> x = 52
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__',
'x': 52, '__doc__': None, '__package__': None}
```
This shows that the variable name is p... |
Convert Variable Name to String? | 1,534,504 | 29 | 2009-10-07T22:06:13Z | 3,683,258 | 27 | 2010-09-10T08:46:57Z | [
"python",
"string",
"variables"
] | I would like to convert a python variable name into the string equivalent as shown. Any ideas how?
```
var = {}
print ??? # Would like to see 'var'
something_else = 3
print ??? # Would print 'something_else'
``` | There is an usage scenario where you might need this. I'm not implying there are not better ways or achieving the same functionality.
This would be useful in order to 'dump' an arbitrary list of dictionaries in case of error, in debug modes and other similar situations.
What would be needed, is the reverse of the `ev... |
Can I sort text by its numeric value in Python? | 1,534,542 | 10 | 2009-10-07T22:13:17Z | 1,534,568 | 18 | 2009-10-07T22:21:10Z | [
"python",
"string",
"sorting"
] | I have dict in Python with keys of the following form:
```
mydict = {'0' : 10,
'1' : 23,
'2.0' : 321,
'2.1' : 3231,
'3' : 3,
'4.0.0' : 1,
'4.0.1' : 10,
'5' : 11,
# ... etc
'10' : 32,
'11.0' : 3,
... | You can sort the keys the way that you want, by splitting them on '.' and then converting each of the components into an integer, like this:
```
sorted(mydict.keys(), key=lambda a:map(int,a.split('.')))
```
which returns this:
```
['0',
'1',
'2.0',
'2.1',
'3',
'4.0.0',
'4.0.1',
'5',
'10',
'11.0',
'11.1',
... |
Creating a program to be broadcasted by avahi | 1,534,655 | 3 | 2009-10-07T22:52:11Z | 18,104,922 | 9 | 2013-08-07T13:37:46Z | [
"python",
"dbus",
"avahi"
] | I'm trying to write a program that outputs data that can be served over a network with avahi. The documentation I've looked at seems to say I have to register the service with dbus and then connect it to avahi, but the documentation to do this is pretty sparse. Does anyone know of good documentation for it? I've been l... | I realise this answer is pretty late, considering your question was asked four years ago. However, it might help others.
The following announces a service using avahi/dbus:
```
import avahi
import dbus
from time import sleep
class ServiceAnnouncer:
def __init__(self, name, service, port, txt):
bus = dbu... |
How to trim a list in Python | 1,534,939 | 14 | 2009-10-08T00:14:38Z | 1,534,957 | 41 | 2009-10-08T00:17:36Z | [
"python",
"list"
] | Suppose I have a list with X elements
```
[4,76,2,8,6,4,3,7,2,1...]
```
I'd like the first 5 elements. Unless it has less than 5 elements.
```
[4,76,2,8,6]
```
How to do that? | You just subindex it with `[:5]` indicating that you want (up to) the first 5 elements.
```
>>> [1,2,3,4,5,6,7,8][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
>>> x = [6,7,8,9,10,11,12]
>>> x[:5]
[6, 7, 8, 9, 10]
```
Also, putting the colon on the right of the number means count from the nth element onwards -- don't... |
How to trim a list in Python | 1,534,939 | 14 | 2009-10-08T00:14:38Z | 4,339,929 | 11 | 2010-12-02T21:09:43Z | [
"python",
"list"
] | Suppose I have a list with X elements
```
[4,76,2,8,6,4,3,7,2,1...]
```
I'd like the first 5 elements. Unless it has less than 5 elements.
```
[4,76,2,8,6]
```
How to do that? | To trim a list in place without creating copies of it, use `del`:
```
>>> t = [1, 2, 3, 4, 5]
>>> # delete elements starting from index 4 to the end
>>> del t[4:]
>>> t
[1, 2, 3, 4]
>>> # delete elements starting from index 5 to the end
>>> # but the list has only 4 elements -- no error
>>> del t[5:]
>>> t
[1, 2, 3, 4... |
How do I override delete() on a model and have it still work with related deletes | 1,534,986 | 15 | 2009-10-08T00:31:38Z | 1,539,182 | 19 | 2009-10-08T17:05:11Z | [
"python",
"django",
"django-models",
"method-overloading"
] | I'm having a problem because I'm deleting a Widget by using some\_widget\_instance.delete(). I also have a model called WidgetFile with an override delete() method so that I can delete files off my hard drive when a WidgetFile is deleted. The problem I'm having is that if I delete a Widget, and it has WidgetFiles relat... | I figured it out. I just put this on that Widget model:
```
def delete(self):
files = WidgetFile.objects.filter(widget=self)
if files:
for file in files:
file.delete()
super(Widget, self).delete()
```
This triggered the necessary delete() method on each of the related objects, thus tri... |
How do I override delete() on a model and have it still work with related deletes | 1,534,986 | 15 | 2009-10-08T00:31:38Z | 12,678,428 | 41 | 2012-10-01T17:55:56Z | [
"python",
"django",
"django-models",
"method-overloading"
] | I'm having a problem because I'm deleting a Widget by using some\_widget\_instance.delete(). I also have a model called WidgetFile with an override delete() method so that I can delete files off my hard drive when a WidgetFile is deleted. The problem I'm having is that if I delete a Widget, and it has WidgetFiles relat... | I'm doing the same thing and noticed a nugget in the Django docs that you should think about.
[Overriding predefined model methods](https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-model-methods)
> Overriding Delete
> Note that the delete() method for an object is not necessarily called when deletin... |
How to write an efficient hit counter for websites | 1,535,261 | 5 | 2009-10-08T02:12:09Z | 1,535,311 | 7 | 2009-10-08T02:28:22Z | [
"php",
"python",
"mysql",
"tracking"
] | I want to write a hit counter script to keep track of hits on images on a website and the originating IPs. Impressions are upwards of hundreds of thousands per day, so the counters will be incremented many times a second.
I'm looking for a simple, self-hosted method (php, python scripts, etc.). I was thinking of using... | A fascinating subject. Incrementing a counter, simple as it may be, just *has* to be a transaction... meaning, it can lock out the whole DB for longer than makes sense!-) It can easily be the bottleneck for the whole system.
If you need rigorously exact counts but don't need them to be instantly up-to-date, my favorit... |
How to print a class or objects of class using print()? | 1,535,327 | 236 | 2009-10-08T02:35:30Z | 1,535,336 | 247 | 2009-10-08T02:39:35Z | [
"python",
"class",
"printing",
"object"
] | I am learning the ropes in Python. When I try to print an object of class **`Foobar`** using the **`print()`** function, I get an output like this:
```
<__main__.Foobar instance at 0x7ff2a18c>
```
Is there a way I can set the *printing behaviour* (or the *string representation*) of a *class* and its *objects*? For in... | ```
>>> class Test:
... def __repr__(self):
... return "Test()"
... def __str__(self):
... return "member of Test"
...
>>> t = Test()
>>> t
Test()
>>> print t
member of Test
```
The `__str__` method is what happens when you print it, and the `__repr__` method is what happens when you use the `... |
How to print a class or objects of class using print()? | 1,535,327 | 236 | 2009-10-08T02:35:30Z | 1,535,375 | 66 | 2009-10-08T02:55:04Z | [
"python",
"class",
"printing",
"object"
] | I am learning the ropes in Python. When I try to print an object of class **`Foobar`** using the **`print()`** function, I get an output like this:
```
<__main__.Foobar instance at 0x7ff2a18c>
```
Is there a way I can set the *printing behaviour* (or the *string representation*) of a *class* and its *objects*? For in... | As Chris Lutz mentioned, this is defined by the `__repr__` method in your class.
From the documentation of [`repr()`](http://docs.python.org/library/functions.html#repr):
> For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to `eval()`, otherwi... |
How to print a class or objects of class using print()? | 1,535,327 | 236 | 2009-10-08T02:35:30Z | 13,971,187 | 8 | 2012-12-20T11:27:39Z | [
"python",
"class",
"printing",
"object"
] | I am learning the ropes in Python. When I try to print an object of class **`Foobar`** using the **`print()`** function, I get an output like this:
```
<__main__.Foobar instance at 0x7ff2a18c>
```
Is there a way I can set the *printing behaviour* (or the *string representation*) of a *class* and its *objects*? For in... | Just to add my two cents to @dbr's answer, following is an example of how to implement this sentence from the official documentation he's cited:
> "[...] to return a string that would yield an object with the same value when passed to eval(), [...]"
Given this class definition:
```
class Test(object):
def __init... |
How to print a class or objects of class using print()? | 1,535,327 | 236 | 2009-10-08T02:35:30Z | 14,354,579 | 9 | 2013-01-16T09:04:00Z | [
"python",
"class",
"printing",
"object"
] | I am learning the ropes in Python. When I try to print an object of class **`Foobar`** using the **`print()`** function, I get an output like this:
```
<__main__.Foobar instance at 0x7ff2a18c>
```
Is there a way I can set the *printing behaviour* (or the *string representation*) of a *class* and its *objects*? For in... | You need to use `__repr__`. This is a standard function like `__init__`.
For example:
```
class Foobar():
"""This will create Foobar type object."""
def __init__(self):
print "Foobar object is created."
def __repr__(self):
return "Type what do you want to see here."
a = Foobar()
print a... |
How to interpret status code in Python commands.getstatusoutput() | 1,535,672 | 4 | 2009-10-08T04:43:50Z | 1,535,703 | 8 | 2009-10-08T04:54:19Z | [
"python",
"documentation",
"subprocess",
"command",
"exit-code"
] | In a [related question](http://stackoverflow.com/questions/1535564), I asked where to find the documentation for the C function "wait." This was an attempt to figure out return codes for the commands.getstatusoutput() module. Stackoverflow came through, but the documentation didn't help. Here's what puzzles me:
```
#!... | There is a set of functions in `os` module (`os.WIFCONTINUED`, `os.WIFSTOPPED`, `os.WTERMSIG`, `os.WCOREDUMP`, `os.WIFEXITED`, `os.WEXITSTATUS`, `os.WIFSIGNALED`, `os.WSTOPSIG`), which correspond to macros from [wait(2)](http://linux.die.net/man/2/wait) manual. You should use them to interpret the status code.
For exa... |
Python not a standardized language? | 1,535,702 | 8 | 2009-10-08T04:54:18Z | 1,535,727 | 28 | 2009-10-08T05:04:44Z | [
"php",
"python",
"standardized"
] | I stumbled upon this 'list of programming' languages and found that popular languages like Python are not standardized? Why is that, and what does 'Standardized' mean anyway? | "Standardized" means that the language has a formal, approved standard, generally written by ISO or ANSI or ECMA. Many modern open-source languages, like Python, Perl, and Ruby, are not formally standardized by an external body, and instead have a *de-facto* standard: whatever the original working implementation does.
... |
How to do email-confirmation after registration in Django? | 1,536,766 | 2 | 2009-10-08T09:54:50Z | 1,536,774 | 8 | 2009-10-08T09:56:18Z | [
"python",
"django"
] | I am using Django's authentication system. Is there an easy way to do this? | Have a look at James Bennett's [django-registration](http://bitbucket.org/ubernostrum/django-registration/wiki/Home) project. |
Variables inside and outside of a class __init__() function | 1,537,202 | 73 | 2009-10-08T11:25:27Z | 1,537,226 | 87 | 2009-10-08T11:29:15Z | [
"python"
] | I'm trying to understand, is there any difference at all between these classes besides the name? Does it make any difference if I use or don't use the \_\_init\_\_() function in declaring the variable "value"?
```
class WithClass ():
def __init__(self):
self.value = "Bob"
def my_func(self):
pri... | Variable set outside `__init__` belong to the class. They're shared by all instances.
Variables created inside `__init__` (and all other method functions) and prefaced with `self.` belong to the object instance. |
Variables inside and outside of a class __init__() function | 1,537,202 | 73 | 2009-10-08T11:25:27Z | 26,529,574 | 27 | 2014-10-23T13:46:36Z | [
"python"
] | I'm trying to understand, is there any difference at all between these classes besides the name? Does it make any difference if I use or don't use the \_\_init\_\_() function in declaring the variable "value"?
```
class WithClass ():
def __init__(self):
self.value = "Bob"
def my_func(self):
pri... | **Without Self**
Create some objects:
```
class foo(object):
x = 'original class'
c1, c2 = foo(), foo()
```
I can change the c1 instance, and it will not affect the c2 instance:
```
c1.x = 'changed instance'
c2.x
>>> 'original class'
```
But if I change the foo class, all instances of that class will be chang... |
How can I get the name of an object in Python? | 1,538,342 | 11 | 2009-10-08T14:54:21Z | 1,538,380 | 17 | 2009-10-08T14:58:40Z | [
"python",
"introspection"
] | Is there any way to get the name of an object in Python? For instance:
```
my_list = [x, y, z] # x, y, z have been previously defined
for bla in my_list:
print "handling object ", name(bla) # <--- what would go instead of `name`?
# do something to bla
```
**Edit:** Some context:
What I'm actually doing is c... | Objects do not necessarily have names in python, so you can't get the name.
It's not unusual for objects to have a `__name__` attribute in those cases that they do have a name, but this is not a part of standard python, and most built in types do not have one.
When you create a variable, like the x, y, z above then th... |
HTTP Download very Big File | 1,538,617 | 12 | 2009-10-08T15:43:00Z | 1,657,324 | 31 | 2009-11-01T14:37:00Z | [
"python",
"http",
"download",
"twisted"
] | I'm working at a web application in Python/Twisted.
I want the user to be able to download a very big file (> 100 Mb). I don't want to load all the file in memory (of the server), of course.
server side I have this idea:
```
...
request.setHeader('Content-Type', 'text/plain')
fp = open(fileName, 'rb')
try:
r = N... | Two big problems with the sample code you posted are that it is non-cooperative and it loads the entire file into memory before sending it.
```
while r != '':
r = fp.read(1024)
request.write(r)
```
Remember that Twisted uses cooperative multitasking to achieve any sort of concurrency. So the first problem wit... |
Why are python strings and tuples are made immutable? | 1,538,663 | 37 | 2009-10-08T15:48:57Z | 1,538,685 | 25 | 2009-10-08T15:51:29Z | [
"python",
"string",
"immutability",
"tuples"
] | I am not sure why strings and tuples were made to be immutable; what are the advantages and disadvantage of making them immutable? | > One is performance: knowing that a
> string is immutable makes it easy to
> lay it out at construction time â
> fixed and unchanging storage
> requirements. This is also one of the
> reasons for the distinction between
> tuples and lists. This also allows the
> implementation to safely reuse string
> objects. For e... |
Why are python strings and tuples are made immutable? | 1,538,663 | 37 | 2009-10-08T15:48:57Z | 1,538,689 | 10 | 2009-10-08T15:52:09Z | [
"python",
"string",
"immutability",
"tuples"
] | I am not sure why strings and tuples were made to be immutable; what are the advantages and disadvantage of making them immutable? | One big advantage of making them immutable is that they can be used as keys in a dictionary. I'm sure the internal data structures used by dictionaries would get quite messed up if the keys were allowed to change. |
Why are python strings and tuples are made immutable? | 1,538,663 | 37 | 2009-10-08T15:48:57Z | 1,632,939 | 61 | 2009-10-27T18:56:17Z | [
"python",
"string",
"immutability",
"tuples"
] | I am not sure why strings and tuples were made to be immutable; what are the advantages and disadvantage of making them immutable? | Imagine a language called FakeMutablePython, where you can alter strings using list assignment and such (such as `mystr[0] = 'a'`)
```
a = "abc"
```
That creates an entry in memory in memory address 0x1, containing "abc", and the identifier `a` pointing to it.
Now, say you do..
```
b = a
```
This creates the ident... |
can't import gdal in python? | 1,538,725 | 9 | 2009-10-08T15:56:25Z | 1,538,763 | 14 | 2009-10-08T16:02:01Z | [
"python",
"gdal"
] | I have `gdal` installed and running on Ubuntu Jaunty but I can't run `gdal2tiles` because I get the error:
```
Traceback (most recent call last):
File "/usr/local/bin/gdal2tiles.py", line 42, in <module>
import gdal
ImportError: No module named gdal
```
When I open python and type `import gdal` I get the same e... | Ith seems to be a "***Python Path***" issue. Python libraries are looked-up within a defined path. Try
```
import sys
sys.path
```
If the directory where the gdal.py and related files is not in this list, then Python cannot find it. That's for the "diagnostics" part. To fix the situation, you have several options...... |
Is the single underscore "_" a built-in variable in Python? | 1,538,832 | 26 | 2009-10-08T16:11:33Z | 1,538,868 | 39 | 2009-10-08T16:16:42Z | [
"python"
] | I don't understand what this single underscore means. Is it a magic variable? I can't see it in locals() and globals().
```
>>> 'abc'
'abc'
>>> len(_)
3
>>>
``` | In the standard Python REPL, `_` represents the last returned value -- at the point where you called `len(_)`, `_` was the value `'abc'`.
For example:
```
>>> 10
10
>>> _
10
>>> _ + 5
15
>>> _ + 5
20
```
Note that there is no such functionality within Python *scripts*. In a script, `_` has no special meaning and wil... |
Is the single underscore "_" a built-in variable in Python? | 1,538,832 | 26 | 2009-10-08T16:11:33Z | 1,538,917 | 15 | 2009-10-08T16:23:16Z | [
"python"
] | I don't understand what this single underscore means. Is it a magic variable? I can't see it in locals() and globals().
```
>>> 'abc'
'abc'
>>> len(_)
3
>>>
``` | Why you can't see it? It is in `__builtins__`
```
>>> __builtins__._ is _
True
```
So it's neither global nor local. 1
And where does this assignment happen? `sys.displayhook`:
```
>>> import sys
>>> help(sys.displayhook)
Help on built-in function displayhook in module sys:
displayhook(...)
displayhook(object)... |
Python client library for WebDAV | 1,539,378 | 22 | 2009-10-08T17:38:32Z | 6,898,536 | 9 | 2011-08-01T12:39:09Z | [
"python",
"client",
"webdav"
] | I'd like to implement a piece of functionality in my application that uploads and manipulates files on a WebDAV server. I'm looking for a mature Python library that would give an interface similar to the `os.*` modules for working with the remote files. Googling has turned up a smattering of options for WebDAV in Pytho... | I just had a similar need and ended up testing a few Python WebDAV clients for my needs (uploading and downloading files from a WebDAV server). Here's a summary of my experience:
1) The one that worked for me is [python-webdav-lib](https://launchpad.net/python-webdav-lib).
Not much documentation, but a quick look at ... |
Python client library for WebDAV | 1,539,378 | 22 | 2009-10-08T17:38:32Z | 12,193,865 | 38 | 2012-08-30T09:32:22Z | [
"python",
"client",
"webdav"
] | I'd like to implement a piece of functionality in my application that uploads and manipulates files on a WebDAV server. I'm looking for a mature Python library that would give an interface similar to the `os.*` modules for working with the remote files. Googling has turned up a smattering of options for WebDAV in Pytho... | It's sad that for this question ("What Python webdav library to use?"), which for sure interests more than one person, unrelated answer was accepted ("don't use Python webdav library"). Well, common problem on Stackexchange.
For people who will be looking for real answers, and given the requirements in the original qu... |
Determine which Button was pressed in Tkinter? | 1,539,787 | 6 | 2009-10-08T18:59:23Z | 1,543,336 | 11 | 2009-10-09T11:51:46Z | [
"python",
"button",
"tkinter"
] | I'm making a simple little utility while learning Python. It dynamically generates a list of buttons:
```
for method in methods:
button = Button(self.methodFrame, text=method, command=self.populateMethod)
button.pack({'fill': 'x', 'expand': 1, 'padx': 5, 'pady': 3})
```
That part works fine. However, I need t... | You can use lambda to pass arguments to a command:
```
def populateMethod(self, method):
print "method:", method
for method in ["one","two","three"]:
button = Button(self.methodFrame, text=method,
command=lambda m=method: self.populateMethod(m))
button.pack({'fill': 'x', 'expand': 1, 'padx': 5, '... |
Replace values in list using Python | 1,540,049 | 59 | 2009-10-08T19:54:18Z | 1,540,069 | 90 | 2009-10-08T19:58:50Z | [
"python",
"list",
"performance",
"replace"
] | I have a list where I want to replace values with None where condition() returns True.
```
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
For example, if condition checks bool(item%2) should return:
```
[None, 1, None, 3, None, 5, None, 7, None, 9, None]
```
What is the most efficient way to do this? | The most efficient:
```
items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for index, item in enumerate(items):
if not (item % 2):
items[index] = None
```
The easiest to read:
```
new_items = [x if x % 2 else None for x in items]
``` |
Replace values in list using Python | 1,540,049 | 59 | 2009-10-08T19:54:18Z | 1,540,071 | 44 | 2009-10-08T19:58:57Z | [
"python",
"list",
"performance",
"replace"
] | I have a list where I want to replace values with None where condition() returns True.
```
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
For example, if condition checks bool(item%2) should return:
```
[None, 1, None, 3, None, 5, None, 7, None, 9, None]
```
What is the most efficient way to do this? | ```
ls = [x if (condition) else None for x in ls]
``` |
Replace values in list using Python | 1,540,049 | 59 | 2009-10-08T19:54:18Z | 1,541,791 | 10 | 2009-10-09T04:29:08Z | [
"python",
"list",
"performance",
"replace"
] | I have a list where I want to replace values with None where condition() returns True.
```
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
For example, if condition checks bool(item%2) should return:
```
[None, 1, None, 3, None, 5, None, 7, None, 9, None]
```
What is the most efficient way to do this? | Riffing on a side question asked by the OP in a comment, i.e.:
> what if I had a generator that yields
> the values from range(11) instead of a
> list. Would it be possible to replace
> values in the generator?
Sure, it's trivially easy...:
```
def replaceiniter(it, predicate, replacement=None):
for item in it:
... |
How to print the function name as a string in Python from inside that function | 1,540,177 | 6 | 2009-10-08T20:21:45Z | 1,540,211 | 7 | 2009-10-08T20:27:10Z | [
"python"
] | ```
def applejuice(q):
print THE FUNCTION NAME!
```
It should result in "applejuice" as a string. | ```
def applejuice(**args):
print "Running the function 'applejuice'"
pass
```
or use:
```
myfunc.__name__
>>> print applejuice.__name__
'applejuice'
```
Also, see [how-to-get-the-function-name-as-string-in-python](http://stackoverflow.com/questions/251464/how-to-get-the-function-name-as-string-in-python) |
How to print the function name as a string in Python from inside that function | 1,540,177 | 6 | 2009-10-08T20:21:45Z | 1,540,215 | 7 | 2009-10-08T20:28:04Z | [
"python"
] | ```
def applejuice(q):
print THE FUNCTION NAME!
```
It should result in "applejuice" as a string. | ```
import traceback
def applejuice(q):
stack = traceback.extract_stack()
(filename, line, procname, text) = stack[-1]
print procname
```
I assume this is used for debugging, so you might want to look into the other procedures offered by the [`traceback` module](http://docs.python.org/library/traceback.html)... |
How to print the function name as a string in Python from inside that function | 1,540,177 | 6 | 2009-10-08T20:21:45Z | 1,540,257 | 13 | 2009-10-08T20:33:18Z | [
"python"
] | ```
def applejuice(q):
print THE FUNCTION NAME!
```
It should result in "applejuice" as a string. | This also works:
```
import sys
def applejuice(q):
func_name = sys._getframe().f_code.co_name
print func_name
``` |
Why isn't getopt working if sys.argv is passed fully? | 1,540,365 | 4 | 2009-10-08T20:48:48Z | 1,540,399 | 11 | 2009-10-08T20:53:25Z | [
"python",
"getopt"
] | If I'm using this with `getopt`:
```
import getopt
import sys
opts,args = getopt.getopt(sys.argv,"a:bc")
print opts
print args
```
`opts` will be empty. No tuples will be created. If however, I'll use `sys.argv[1:]`, everything works as expected. I don't understand why that is. Anyone care to explain? | The first element of `sys.argv` (`sys.argv[0]`) is the name of the script currently being executed. Because this script name is (likely) not a valid argument (and probably doesn't begin with a `-` or `--` anyway), `getopt` does not recognize it as an argument. Due to the nature of how `getopt` works, when it sees somet... |
Recurrence sequence in Java / Python / Mathematica | 1,540,519 | 3 | 2009-10-08T21:12:03Z | 1,540,642 | 8 | 2009-10-08T21:36:39Z | [
"java",
"python",
"wolfram-mathematica",
"sequence"
] | **How can you write the following statement in the given languages?**
```
a(0) = 1
a_(n+1) = 1 - 1 / ( a_n + 3)
```
I need to find the smallest value of `n` when `a_n -> 0.732050...`.
**My attempt in Mathematica**
```
a[(x+1)_] = 1 - 1/(a[x_] + 3)
```
The problem is apparently in this `a[(x+1)_]`.
However, I do no... | ### Mathematica
```
a[0] = 1;
a[n_] := a[n] = 1 - 1/(a[n-1] + 3)
```
(Note the [memoization trick](http://stackoverflow.com/questions/129877/how-do-i-write-a-generic-memoize-function/173038#173038).)
Also, a[n] converges (very quickly) to sqrt(3)-1:
```
Solve[x == 1 - 1/(x+3), x]
``` |
Java Equivalent to Python Dictionaries | 1,540,673 | 59 | 2009-10-08T21:44:34Z | 1,540,699 | 59 | 2009-10-08T21:49:58Z | [
"java",
"python",
"hash",
"dictionary"
] | I am a long time user of Python and really like the way that the dictionaries are used. They are very intuitive and easy to use. Is there a good Java equivalent to python's dictionaries? I have heard of people using hashmaps and hashtables. Could someone explain the similarities and differences of using hashtables and ... | Python's `dict` class is an implementation of what the Python documentation informally calls "[mapping types](http://docs.python.org/library/stdtypes.html#mapping-types-dict)". Internally, `dict` is implemented using a hashtable.
Java's [`HashMap`](http://java.sun.com/javase/6/docs/api/java/util/HashMap.html) class is... |
Dumping a multiprocessing.Queue into a list | 1,540,822 | 14 | 2009-10-08T22:17:37Z | 1,541,117 | 18 | 2009-10-08T23:36:18Z | [
"python",
"queue",
"multiprocessing"
] | I wish to dump a `multiprocessing.Queue` into a list. For that task I've written the following function:
```
import Queue
def dump_queue(queue):
"""
Empties all pending items in a queue and returns them in a list.
"""
result = []
# START DEBUG CODE
initial_size = queue.qsize()
print("Queu... | Try this:
```
import Queue
import time
def dump_queue(queue):
"""
Empties all pending items in a queue and returns them in a list.
"""
result = []
for i in iter(queue.get, 'STOP'):
result.append(i)
time.sleep(.1)
return result
import multiprocessing
q = multiprocessing.Queue()
fo... |
Python 'object' type and inheritance | 1,540,975 | 4 | 2009-10-08T22:56:28Z | 1,540,998 | 9 | 2009-10-08T23:04:13Z | [
"python",
"inheritance",
"object"
] | In Python I can define a class 'foo' in the following ways:
```
class foo:
pass
```
or
```
class foo(object):
pass
```
What is the difference? I have tried to use the function issubclass(foo, object) to see if it returns True for both class definitions. It does not.
```
IDLE 2.6.3
>>> class foo:
... | Inheriting from `object` makes a class a "new-style class". There is a discussion of old-style vs. new-style here: [Old style and new style classes in Python](http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python)
As @CrazyJugglerDrummer commented below, in Python 3 all classes are "new-st... |
Bubble Breaker Game Solver better than greedy? | 1,541,101 | 4 | 2009-10-08T23:29:18Z | 1,541,206 | 7 | 2009-10-09T00:01:34Z | [
"python",
"algorithm",
"language-agnostic"
] | For a mental exercise I decided to try and solve the bubble breaker game found on many cell phones as well as an example here:[Bubble Break Game](http://www.kongregate.com/games/Sevas/bubble-breaker-game)
* The random (N,M,C) board consists N rows x M columns with C colors
* The goal is to get the highest score by pic... | According to [this paper](http://erikdemaine.org/clickomania/), determining if you can empty the board (which is related to the problem you want to solve) is NP-Complete. That doesn't mean that you won't be able to find a good algorithm, it just means that you likely won't find an efficient one. |
Difference between GET and FILTER in Django model layer | 1,541,249 | 18 | 2009-10-09T00:21:12Z | 1,541,322 | 32 | 2009-10-09T00:50:56Z | [
"python",
"django"
] | What is the difference, please explain them in laymen's terms with examples. Thanks! | I don't know if you really need an example, it's quite easy:
* if you know it's one object that matches your query, use get. It will fail if it's more than one.
* otherwise use filter, which gives you a list of objects.
To be more precise:
* `MyTable.objects.get(id=x).whatever` gives you the `whatever` property of y... |
Why is subprocess.Popen not waiting until the child process terminates? | 1,541,273 | 5 | 2009-10-09T00:30:31Z | 1,541,355 | 19 | 2009-10-09T01:05:31Z | [
"python",
"mysql"
] | I'm having a problem with Python's subprocess.Popen method.
Here's a test script which demonstrates the problem. It's being run on a Linux box.
```
#!/usr/bin/env python
import subprocess
import time
def run(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
return p
### START MAIN
# copy some ... | `subprocess.Popen`, when instantiated, runs the program. It does not, however, wait for it -- it fires it off in the background as if you'd typed `cmd &` in a shell. So, in the code above, you've essentially defined a race condition -- if the inserts can finish in time, it will appear normal, but if not you get the une... |
Why is subprocess.Popen not waiting until the child process terminates? | 1,541,273 | 5 | 2009-10-09T00:30:31Z | 1,541,709 | 7 | 2009-10-09T03:54:09Z | [
"python",
"mysql"
] | I'm having a problem with Python's subprocess.Popen method.
Here's a test script which demonstrates the problem. It's being run on a Linux box.
```
#!/usr/bin/env python
import subprocess
import time
def run(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
return p
### START MAIN
# copy some ... | If you don't absolutely need to use subprocess and popen, it's usually simpler to use `os.system`. For example, for quick scripts I often do something like this:
```
import os
run = os.system #convenience alias
result = run('mysql -u ve --execute="select * from wherever" test')
```
Unlike popen, `os.system` DOES wait... |
Django SELECT statement, Order by | 1,541,376 | 4 | 2009-10-09T01:15:36Z | 1,541,390 | 7 | 2009-10-09T01:23:17Z | [
"python",
"django"
] | Suppose I have 2 models.
The 2nd model has a one-to-one relationship with the first model.
I'd like to select information from the first model, but ORDER BY the 2nd model. How can I do that?
```
class Content(models.Model):
link = models.TextField(blank=True)
title = models.TextField(blank=True)
is_cha... | I think you can do:
```
Content.objects.filter(...).order_by('score__counter')
```
More generally, when models have a relationship, you can select, order, and filter by fields on the "other" model using the `relationshipName__fieldName` pseudo attribute of the model which you are selecting on. |
Upgrade Python to 2.6 on Mac | 1,541,776 | 14 | 2009-10-09T04:24:03Z | 1,541,850 | 20 | 2009-10-09T04:48:25Z | [
"python",
"osx",
"installation",
"upgrade"
] | I'd like to upgrade the default python installation (2.5.1) supplied with OS X Leopard to the latest version. Please let me know how I can achieve this.
Thanks | When an OS is distributed with some specific Python release and uses it for some OS functionality (as is the case with Mac OS X, as well as many Linux distros &c), you should **not** tamper in any way with the system-supplied Python (as in, "upgrading" it and the like): while Python strives for backwards compatibility ... |
Upgrade Python to 2.6 on Mac | 1,541,776 | 14 | 2009-10-09T04:24:03Z | 1,542,144 | 8 | 2009-10-09T06:35:57Z | [
"python",
"osx",
"installation",
"upgrade"
] | I'd like to upgrade the default python installation (2.5.1) supplied with OS X Leopard to the latest version. Please let me know how I can achieve this.
Thanks | Don't upgrade.
1. Install [ActivePython](http://www.activestate.com/activepython/downloads) (which [co-exists](http://docs.activestate.com/activepython/2.6/faq.html#does-activepython-collide-with-other-python-distributions-on-mac-os-x) with others).
2. Open Terminal
3. Type `python2.6` |
Check for duplicates in a flat list | 1,541,797 | 67 | 2009-10-09T04:30:32Z | 1,541,820 | 30 | 2009-10-09T04:36:37Z | [
"python",
"string",
"list",
"duplicates"
] | example 1:
`['one', 'two', 'one']` should return True.
example 2:
`['one', 'two', 'three']` should return False. | Recommended for *short* lists only:
```
any(thelist.count(x) > 1 for x in thelist)
```
Do **not** use on a long list -- it can take time proportional to the **square** of the number of items in the list!
For longer lists with hashable items (strings, numbers, &c):
```
def anydup(thelist):
seen = set()
for x in ... |
Check for duplicates in a flat list | 1,541,797 | 67 | 2009-10-09T04:30:32Z | 1,541,827 | 157 | 2009-10-09T04:38:45Z | [
"python",
"string",
"list",
"duplicates"
] | example 1:
`['one', 'two', 'one']` should return True.
example 2:
`['one', 'two', 'three']` should return False. | Use `set()` to remove duplicates if all values are *hashable*:
```
>>> your_list = ['one', 'two', 'one']
>>> len(your_list) != len(set(your_list))
True
``` |
How to write this "model" in Django? | 1,542,659 | 2 | 2009-10-09T08:54:04Z | 1,542,697 | 11 | 2009-10-09T09:04:01Z | [
"python",
"django"
] | I am currently using Django Users model.
Very simple. However, I'd like to add one feature: Adding friends!
I would like to create 2 columns in my table:
UID (the ID of the User)
friend\_id (the ID of his friend! ...of course, this ID is also in Django's User model.
The UID-friend\_id combination must be unique! For ... | You should create a model that defines the relationship between two users, and then define two foreign-key fields, each one to a User. You can then add a unique constraint to make sure you don't have duplicates.
There is a article here explaining exactly how to do this: <http://www.packtpub.com/article/building-friend... |
What to do when Django query returns none? It gives me error | 1,542,878 | 4 | 2009-10-09T09:50:41Z | 1,542,934 | 8 | 2009-10-09T10:06:39Z | [
"python",
"django"
] | ```
to_friend = User.objects.filter(username=friend_q)[0:1]
```
If 'friend\_q' is NOT inside the User.username...it will give error.
What is the recommended tactic?
Thank you | If friend\_q is not a user present in the database, to\_friend will be equal to an empty list.
```
>>> from django.contrib.auth.models import User
>>> User.objects.filter(username='does-not-exist')
[]
```
However, it's better to use the get() method to lookup a specific entry:
```
>>> User.objects.get(username='does... |
Google Federated Login (OpenID+Oauth) for Hosted Apps - changing end points? | 1,543,123 | 8 | 2009-10-09T10:58:14Z | 1,650,977 | 7 | 2009-10-30T16:44:30Z | [
"python",
"openid",
"oauth",
"hybridauthprovider"
] | I'm trying to integrate the Google Federated Login with a premier apps account, but I'm having some problems.
When I send the request to: `https://www.google.com/accounts/o8/ud` with all the parameters (see below), I get back both a `request_token` and list of attributes asked for by `Attribute Exchange`. This is perf... | For the record, posterity, and anyone else who might come asunder of this, I'll document the (ridiculous) answer.
Ultimately, the problem was calling:
```
return HttpResponseRedirect(
'https://www.google.com/a/thedomain.com/o8/ud?be=o8'
+ '?'
+ urllib.urlencode(parameters)
)
```
Can you spot it? Yeah, it... |
Python gzip: is there a way to decompress from a string? | 1,543,652 | 20 | 2009-10-09T13:09:12Z | 1,543,665 | 27 | 2009-10-09T13:13:46Z | [
"python",
"gzip"
] | I've read this [SO post](http://stackoverflow.com/questions/1313845/if-i-have-the-contents-of-a-zipfile-in-a-python-string-can-i-decompress-it-witho) around the problem to no avail.
I am trying to decompress a .gz file coming from an URL.
```
url_file_handle=StringIO( gz_data )
gzip_file_handle=gzip.open(url_file_han... | `gzip.open` is a shorthand for opening a file, what you want is `gzip.GzipFile` which you can pass a fileobj
```
open(filename, mode='rb', compresslevel=9)
#Shorthand for GzipFile(filename, mode, compresslevel).
```
vs
```
class GzipFile
__init__(self, filename=None, mode=None, compresslevel=9, fileobj=None)
... |
Python gzip: is there a way to decompress from a string? | 1,543,652 | 20 | 2009-10-09T13:09:12Z | 18,319,515 | 17 | 2013-08-19T17:21:45Z | [
"python",
"gzip"
] | I've read this [SO post](http://stackoverflow.com/questions/1313845/if-i-have-the-contents-of-a-zipfile-in-a-python-string-can-i-decompress-it-witho) around the problem to no avail.
I am trying to decompress a .gz file coming from an URL.
```
url_file_handle=StringIO( gz_data )
gzip_file_handle=gzip.open(url_file_han... | If your data is already in a string, try zlib, which claims to be fully gzip compatible:
```
import zlib
decompressed_data = zlib.decompress(gz_data, 16+zlib.MAX_WBITS)
```
Read more: <http://docs.python.org/library/zlib.html>â |
Comprehensions in Python and Javascript are only very basic? | 1,543,820 | 6 | 2009-10-09T13:39:13Z | 1,543,870 | 12 | 2009-10-09T13:44:43Z | [
"javascript",
"python",
"haskell",
"list-comprehension"
] | Looking at comprehensions in Python and Javascript, so far I can't see some of the main features that I consider most powerful in comprehensions in languages like Haskell.
Do they allow things like multiple generators? Or are they just a basic map-filter form?
If they don't allow multiple generators, I find them quit... | Python allows multiple generators:
```
>>> [(x,y,x*y) for x in range(1,5) for y in range(1,5)]
[(1, 1, 1), (1, 2, 2), (1, 3, 3), (1, 4, 4),
(2, 1, 2), (2, 2, 4), (2, 3, 6), (2, 4, 8),
(3, 1, 3), (3, 2, 6), (3, 3, 9), (3, 4, 12),
(4, 1, 4), (4, 2, 8), (4, 3, 12), (4, 4, 16)]
```
And also restrictions:
```
>>> [(... |
Condense this Python statement without destroying readability | 1,544,350 | 2 | 2009-10-09T14:59:14Z | 1,544,370 | 10 | 2009-10-09T15:01:45Z | [
"python"
] | I'm pretty new to Python still, so I'm trying to figure out how to do this and need some help.
I use return codes to verify that my internal functions return successfully. For example (from internal library functions):
```
result = some_function(arg1,arg2)
if result != OK: return result
```
or (from main script leve... | Could you use exceptions to indicate failure, rather than return codes? Then most of your `if result != OK:` statements would simply go away. |
python numpy savetxt | 1,544,948 | 5 | 2009-10-09T16:56:49Z | 1,545,114 | 12 | 2009-10-09T17:31:52Z | [
"python",
"numpy"
] | Can someone indicate what I am doing wrong here?
```
import numpy as np
a = np.array([1,2,3,4,5],dtype=int)
b = np.array(['a','b','c','d','e'],dtype='|S1')
np.savetxt('test.txt',zip(a,b),fmt="%i %s")
```
The output is:
```
Traceback (most recent call last):
File "loadtxt.py", line 6, in <module>
np.savetxt('... | You need to construct you array differently:
```
z = np.array(zip([1,2,3,4,5], ['a','b','c','d','e']), dtype=[('int', int), ('str', '|S1')])
np.savetxt('test.txt', z, fmt='%i %s')
```
when you're passing a sequence, `savetext` performs [`asarray(sequence)` call](http://projects.scipy.org/numpy/browser/branches/1.1.x/... |
Python one-line "for" expression | 1,545,050 | 8 | 2009-10-09T17:17:05Z | 1,545,056 | 8 | 2009-10-09T17:18:13Z | [
"python",
"lambda"
] | I'm not sure if I need a lambda, or something else. But still, I need the following:
I have an `array = [1,2,3,4,5]`. I need to put this array, for instance, into another array. But write it all in one line.
```
for item in array:
array2.append(item)
```
I know that this is completely possible to iterate through... | ```
for item in array: array2.append (item)
```
Or, in this case:
```
array2 += array
``` |
Python one-line "for" expression | 1,545,050 | 8 | 2009-10-09T17:17:05Z | 1,545,060 | 21 | 2009-10-09T17:19:29Z | [
"python",
"lambda"
] | I'm not sure if I need a lambda, or something else. But still, I need the following:
I have an `array = [1,2,3,4,5]`. I need to put this array, for instance, into another array. But write it all in one line.
```
for item in array:
array2.append(item)
```
I know that this is completely possible to iterate through... | The keyword you're looking for is [list comprehensions](http://www.python.org/dev/peps/pep-0202/):
```
>>> x = [1, 2, 3, 4, 5]
>>> y = [2*a for a in x if a % 2 == 1]
>>> print(y)
[2, 6, 10]
``` |
Django - specify which model manager Django admin should use | 1,545,067 | 24 | 2009-10-09T17:20:21Z | 1,545,338 | 34 | 2009-10-09T18:23:09Z | [
"python",
"django"
] | I've created a custom Manager for a Django model which returns a QuerySet holding a subset of objects.all(). I need this to be the model's default Manager, since I am also creating a custom tag which will retrieve content from any model (specified by an argument), and needs to use the default Manager for the specified ... | You can choose the manager by overriding the `queryset` method in your ModelAdmin subclass.
```
def get_queryset(self, request):
# use our manager, rather than the default one
qs = self.model.objects.get_query_set()
# we need this from the superclass method
ordering = self.ordering or () # otherwise w... |
UTF-8 In Python logging, how? | 1,545,263 | 23 | 2009-10-09T18:06:15Z | 1,545,599 | 13 | 2009-10-09T19:14:49Z | [
"python",
"logging",
"unicode"
] | I'm trying to log a UTF-8 encoded string to a file using Python's logging package. As a toy example:
```
import logging
def logging_test():
handler = logging.FileHandler("/home/ted/logfile.txt", "w",
encoding = "UTF-8")
formatter = logging.Formatter("%(message)s")
handler... | Check that you have the latest Python 2.6 - some Unicode bugs were found and fixed since 2.6 came out. For example, on my Ubuntu Jaunty system, I ran your script copied and pasted, removing only the '/home/ted/' prefix from the log file name. Result (copied and pasted from a terminal window):
```
vinay@eta-jaunty:~/pr... |
UTF-8 In Python logging, how? | 1,545,263 | 23 | 2009-10-09T18:06:15Z | 22,320,208 | 14 | 2014-03-11T08:31:51Z | [
"python",
"logging",
"unicode"
] | I'm trying to log a UTF-8 encoded string to a file using Python's logging package. As a toy example:
```
import logging
def logging_test():
handler = logging.FileHandler("/home/ted/logfile.txt", "w",
encoding = "UTF-8")
formatter = logging.Formatter("%(message)s")
handler... | Having code like:
```
raise Exception(u'Ñ')
```
Caused:
```
File "/usr/lib/python2.7/logging/__init__.py", line 467, in format
s = self._fmt % record.__dict__
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
```
This happens because the format string is a b... |
Math Expression Evaluation | 1,545,403 | 10 | 2009-10-09T18:35:41Z | 1,545,518 | 16 | 2009-10-09T18:59:59Z | [
"python",
"math"
] | What is the best way to implement a python program that will take a string and will output its result according to operator precedence (for example: "4+3\*5" will output 19). I've googled for ways to solve this problem but they were all too complex, and I'm looking for a (relatively) simple one.
clarification: I need ... | If you're "academically interested", you want to learn about how to write a parser with operator precedence.
[Simple Top-Down Parsing in Python](http://effbot.org/zone/simple-top-down-parsing.htm) is a nice article that builds an example parser to do exactly what you want to do: Evaluate mathematical expressions.
I c... |
Force Python to forego native sqlite3 and use the (installed) latest sqlite3 version | 1,545,479 | 26 | 2009-10-09T18:53:31Z | 1,546,162 | 61 | 2009-10-09T21:36:55Z | [
"python",
"sqlite",
"sqlite3"
] | The error message I am trying to get rid of is:
> AttributeError: 'sqlite3.Connection'
> object has no attribute
> 'enable\_load\_extension'
I have 'easy\_install'-ed the latest sqlite3 version and python somehow know it is there since sqlite3.version\_info produces 3.6.13. In this version the Connection should have ... | `sqlite3` support in Python can be a bit confusing. The sqlite database adapter started out as a separate project, [pysqlite2](https://github.com/ghaering/pysqlite), but for Python 2.5 a version of it was incorporated into the Python standard library under the name [sqlite3](http://docs.python.org/library/sqlite3.html)... |
Force Python to forego native sqlite3 and use the (installed) latest sqlite3 version | 1,545,479 | 26 | 2009-10-09T18:53:31Z | 8,761,073 | 12 | 2012-01-06T16:30:22Z | [
"python",
"sqlite",
"sqlite3"
] | The error message I am trying to get rid of is:
> AttributeError: 'sqlite3.Connection'
> object has no attribute
> 'enable\_load\_extension'
I have 'easy\_install'-ed the latest sqlite3 version and python somehow know it is there since sqlite3.version\_info produces 3.6.13. In this version the Connection should have ... | I have python 2.7 on a windows machine and the built-in sqlite3.sqlite\_version was 3.6.x. By performing the following steps I was able to get it to use sqlite 3.7.9.
1. Download and unzip the pre-compiled binary DLL ("sqlite-dll-win32-x86-3070900.zip" on <http://www.sqlite.org/download.html>)
2. (probably should clos... |
Python k-means algorithm | 1,545,606 | 41 | 2009-10-09T19:16:13Z | 1,546,313 | 51 | 2009-10-09T22:10:57Z | [
"python",
"algorithm",
"cluster-analysis",
"k-means"
] | I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates. | [Scipy's clustering](http://docs.scipy.org/doc/scipy/reference/cluster.html) implementations work well, and they include a [k-means](http://docs.scipy.org/doc/scipy/reference/cluster.vq.html) implementation.
There's also [scipy-cluster](http://code.google.com/p/scipy-cluster/), which does agglomerative clustering; ths... |
Python k-means algorithm | 1,545,606 | 41 | 2009-10-09T19:16:13Z | 2,224,488 | 27 | 2010-02-08T20:03:43Z | [
"python",
"algorithm",
"cluster-analysis",
"k-means"
] | I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates. | SciPy's [kmeans2()](http://docs.scipy.org/doc/scipy/reference/cluster.vq.html) has some numerical problems: others have [reported](http://mail.scipy.org/pipermail/scipy-user/2009-February/019777.html) error messages such as "Matrix is not positive definite - Cholesky decomposition cannot be computed" in version 0.6.0, ... |
Python k-means algorithm | 1,545,606 | 41 | 2009-10-09T19:16:13Z | 2,605,234 | 17 | 2010-04-09T05:21:50Z | [
"python",
"algorithm",
"cluster-analysis",
"k-means"
] | I am looking for Python implementation of k-means algorithm with examples to cluster and cache my database of coordinates. | For continuous data, k-means is very easy.
You need a list of your means, and for each data point, find the mean its closest to and average the new data point to it. your means will represent the recent salient clusters of points in the input data.
I do the averaging continuously, so there is no need to have the old ... |
A simple way to remove multiple spaces in a string in Python | 1,546,226 | 119 | 2009-10-09T21:48:37Z | 1,546,244 | 140 | 2009-10-09T21:52:29Z | [
"python",
"regex",
"string"
] | Suppose this is the string:
```
The fox jumped over the log.
```
It would result in:
```
The fox jumped over the log.
```
What is the simplest, 1-2 liner that can do this? Without splitting and going into lists... | ```
>>> import re
>>> re.sub(' +',' ','The quick brown fox')
'The quick brown fox'
``` |
A simple way to remove multiple spaces in a string in Python | 1,546,226 | 119 | 2009-10-09T21:48:37Z | 1,546,245 | 46 | 2009-10-09T21:52:30Z | [
"python",
"regex",
"string"
] | Suppose this is the string:
```
The fox jumped over the log.
```
It would result in:
```
The fox jumped over the log.
```
What is the simplest, 1-2 liner that can do this? Without splitting and going into lists... | ```
import re
s = "The fox jumped over the log."
re.sub("\s\s+" , " ", s)
```
or
```
re.sub("\s\s+", " ", s)
```
since the space before comma is listed as a *pet peeve* in PEP8, as mentioned by moose in the comments. |
A simple way to remove multiple spaces in a string in Python | 1,546,226 | 119 | 2009-10-09T21:48:37Z | 1,546,251 | 228 | 2009-10-09T21:52:56Z | [
"python",
"regex",
"string"
] | Suppose this is the string:
```
The fox jumped over the log.
```
It would result in:
```
The fox jumped over the log.
```
What is the simplest, 1-2 liner that can do this? Without splitting and going into lists... | foo is your string:
```
" ".join(foo.split())
``` |
A simple way to remove multiple spaces in a string in Python | 1,546,226 | 119 | 2009-10-09T21:48:37Z | 1,546,272 | 10 | 2009-10-09T21:58:27Z | [
"python",
"regex",
"string"
] | Suppose this is the string:
```
The fox jumped over the log.
```
It would result in:
```
The fox jumped over the log.
```
What is the simplest, 1-2 liner that can do this? Without splitting and going into lists... | Similar to the previous solutions, but more specific: replace two or more spaces with one:
```
>>> import re
>>> s = "The fox jumped over the log."
>>> re.sub('\s{2,}', ' ', s)
'The fox jumped over the log.'
``` |
A simple way to remove multiple spaces in a string in Python | 1,546,226 | 119 | 2009-10-09T21:48:37Z | 1,546,883 | 24 | 2009-10-10T02:39:51Z | [
"python",
"regex",
"string"
] | Suppose this is the string:
```
The fox jumped over the log.
```
It would result in:
```
The fox jumped over the log.
```
What is the simplest, 1-2 liner that can do this? Without splitting and going into lists... | Have to agree with Paul McGuire's comment above. To me,
```
' '.join(the_string.split())
```
is vastly preferable to whipping out a regex. My measurements (Linux, Python 2.5) show the split-then-join to be almost 5 times faster than doing the "re.sub(...)", and still 3 times faster if you precompile the rege... |
A simple way to remove multiple spaces in a string in Python | 1,546,226 | 119 | 2009-10-09T21:48:37Z | 15,913,564 | 26 | 2013-04-09T22:16:21Z | [
"python",
"regex",
"string"
] | Suppose this is the string:
```
The fox jumped over the log.
```
It would result in:
```
The fox jumped over the log.
```
What is the simplest, 1-2 liner that can do this? Without splitting and going into lists... | Using regexes with "\s" and doing simple string.split()'s will *also* remove other whitespace - like newlines, carriage returns, tabs. Unless this is desired, to **only** do *multiple spaces*, I present these examples.
---
**EDIT:** As I'm wont to do, I slept on this, and besides correcting a typo on the last results... |
Using enums in ctypes.Structure | 1,546,355 | 6 | 2009-10-09T22:25:11Z | 1,546,467 | 7 | 2009-10-09T23:05:34Z | [
"python",
"enums",
"ctypes"
] | I have a struct I'm accessing via ctypes:
```
struct attrl {
char *name;
char *resource;
char *value;
struct attrl *next;
enum batch_op op;
};
```
So far I have Python code like:
```
# struct attropl
class attropl(Structure):
pass
attrl._fields_ = [
("next", POINTER(attropl)),
... | At least for GCC `enum` is just a simple numeric type. It can be 8-, 16-, 32-, 64-bit or whatever (I have tested it with 64-bit values) as well as `signed` or `unsigned`. I guess it cannot exceed `long long int`, but practically you should check the range of your `enum`s and choose something like `c_uint`.
Here is an ... |
python: how to send mail with TO, CC and BCC? | 1,546,367 | 51 | 2009-10-09T22:29:46Z | 1,546,406 | 12 | 2009-10-09T22:41:38Z | [
"python",
"email",
"testing"
] | I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO specific mailboxes, but CC and BCC them as well. It does not look like [smtplib](http://docs.python.org/library/smtplib.htm... | The distinction between TO, CC and BCC occurs only in the text headers. At the SMTP level, everybody is a recipient.
TO - There is a TO: header with this recipient's address
CC - There is a CC: header with this recipient's address
BCC - This recipient isn't mentioned in the headers at all, but is still a recipient.
... |
python: how to send mail with TO, CC and BCC? | 1,546,367 | 51 | 2009-10-09T22:29:46Z | 1,546,410 | 12 | 2009-10-09T22:42:55Z | [
"python",
"email",
"testing"
] | I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO specific mailboxes, but CC and BCC them as well. It does not look like [smtplib](http://docs.python.org/library/smtplib.htm... | You can try MIMEText
```
msg = MIMEText('text')
msg['to'] =
msg['cc'] =
```
then send msg.as\_string()
<http://docs.python.org/library/email-examples.html> |
python: how to send mail with TO, CC and BCC? | 1,546,367 | 51 | 2009-10-09T22:29:46Z | 1,546,435 | 85 | 2009-10-09T22:52:29Z | [
"python",
"email",
"testing"
] | I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO specific mailboxes, but CC and BCC them as well. It does not look like [smtplib](http://docs.python.org/library/smtplib.htm... | Email headers don't matter to the smtp server. Just add the CC and BCC recipients to the toaddrs when you send your email. For CC, add them to the CC header.
```
toaddr = '[email protected]'
cc = ['[email protected]','[email protected]']
bcc = ['[email protected]']
fromaddr = 'gile... |
python: how to send mail with TO, CC and BCC? | 1,546,367 | 51 | 2009-10-09T22:29:46Z | 29,627,094 | 7 | 2015-04-14T12:17:55Z | [
"python",
"email",
"testing"
] | I need for testing purposes to populate few hundred email boxes with various messages, and was going to use smtplib for that. But among other things I need to be able to send messages not only TO specific mailboxes, but CC and BCC them as well. It does not look like [smtplib](http://docs.python.org/library/smtplib.htm... | Don't add the bcc header.
See this: <http://mail.python.org/pipermail/email-sig/2004-September/000151.html>
And this: """Notice that the second argument to sendmail(), the recipients, is passed as a list. You can include any number of addresses in the list to have the message delivered to each of them in turn. Since ... |
Python: Escaping strings for use in XML | 1,546,717 | 23 | 2009-10-10T00:51:10Z | 1,546,738 | 55 | 2009-10-10T01:05:56Z | [
"python",
"xml",
"security"
] | I'm using Python's `xml.dom.minidom` to create an XML document. (Logical structure -> XML string, not the other way around.)
How do I make it escape the strings I provide so they won't be able to mess up the XML? | Something like this?
```
>>> from xml.sax.saxutils import escape
>>> escape("< & >")
'< & >'
``` |
Python: Escaping strings for use in XML | 1,546,717 | 23 | 2009-10-10T00:51:10Z | 1,546,747 | 10 | 2009-10-10T01:09:51Z | [
"python",
"xml",
"security"
] | I'm using Python's `xml.dom.minidom` to create an XML document. (Logical structure -> XML string, not the other way around.)
How do I make it escape the strings I provide so they won't be able to mess up the XML? | Do you mean you do something like this:
```
from xml.dom.minidom import Text, Element
t = Text()
e = Element('p')
t.data = '<bar><a/><baz spam="eggs"> & blabla &entity;</>'
e.appendChild(t)
```
Then you will get nicely escaped XML string:
```
>>> e.toxml()
'<p><bar><a/><baz spam="eggs">... |
How to create a specific if condition templatetag with Django? | 1,546,816 | 3 | 2009-10-10T01:53:39Z | 1,547,306 | 11 | 2009-10-10T07:35:06Z | [
"python",
"django",
"django-templates",
"favorites"
] | My problem is a if condition.
I would like somethings like that but cannot figure out how to do it.
```
{% if restaurant.is_favorite_of(user) %}
<img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" />
{% else %}
<img src="{{MEDIA_URL}}images/favorite_o... | Easiest way is to create a filter.
```
@register.filter
def is_favourite_of(object, user):
return Favourite.objects.is_favourite(user, object)
```
and in the template:
```
{% if restaurant|is_favourite_of:user %}
``` |
Defining private module functions in python | 1,547,145 | 106 | 2009-10-10T05:30:20Z | 1,547,159 | 21 | 2009-10-10T05:39:17Z | [
"python",
"function",
"module",
"private"
] | According to [http://www.faqs.org/docs/diveintopython/fileinfo\_private.html](http://www.faqs.org/docs/diveintopython/fileinfo%5Fprivate.html):
> Like most languages, Python has the
> concept of private elements:
>
> * Private
> functions, which can't be called from
> **outside their module**
However, if I define... | Python allows for private *class* members with the double underscore prefix. This technique doesn't work at a module level so I am thinking this is a mistake in Dive Into Python.
Here is an example of private class functions:
```
class foo():
def bar(self): pass
def __bar(self): pass
f = foo()
f.bar() # th... |
Defining private module functions in python | 1,547,145 | 106 | 2009-10-10T05:30:20Z | 1,547,160 | 141 | 2009-10-10T05:40:54Z | [
"python",
"function",
"module",
"private"
] | According to [http://www.faqs.org/docs/diveintopython/fileinfo\_private.html](http://www.faqs.org/docs/diveintopython/fileinfo%5Fprivate.html):
> Like most languages, Python has the
> concept of private elements:
>
> * Private
> functions, which can't be called from
> **outside their module**
However, if I define... | There may be confusion between ***class privates*** and ***module privates***.
A *module private* starts with **one underscore**
Such a element is not copied along when using the `from <module_name> import *` form of the import command; it is however imported if using the `import <moudule_name>` syntax ([see Ben Wil... |
Defining private module functions in python | 1,547,145 | 106 | 2009-10-10T05:30:20Z | 1,547,163 | 145 | 2009-10-10T05:43:03Z | [
"python",
"function",
"module",
"private"
] | According to [http://www.faqs.org/docs/diveintopython/fileinfo\_private.html](http://www.faqs.org/docs/diveintopython/fileinfo%5Fprivate.html):
> Like most languages, Python has the
> concept of private elements:
>
> * Private
> functions, which can't be called from
> **outside their module**
However, if I define... | In Python, "privacy" depends on "consenting adults'" levels of agreement - you can't *force* it (any more than you can in real life;-). A single leading underscore means you're not **supposed** to access it "from the outside" -- **two** leading underscores (w/o trailing underscores) carry the message even more forceful... |
Defining private module functions in python | 1,547,145 | 106 | 2009-10-10T05:30:20Z | 13,618,522 | 45 | 2012-11-29T03:50:32Z | [
"python",
"function",
"module",
"private"
] | According to [http://www.faqs.org/docs/diveintopython/fileinfo\_private.html](http://www.faqs.org/docs/diveintopython/fileinfo%5Fprivate.html):
> Like most languages, Python has the
> concept of private elements:
>
> * Private
> functions, which can't be called from
> **outside their module**
However, if I define... | This question was not fully answered, since module privacy is not purely conventional, and since using **import** may or may not recognize module privacy, depending on how it is used.
If you define private names in a module, those names **will** be imported into any script that uses the syntax, 'import module\_name'. ... |
A database for python 3? | 1,547,365 | 3 | 2009-10-10T08:09:24Z | 1,547,572 | 7 | 2009-10-10T10:20:12Z | [
"python",
"database",
"python-3.x"
] | I'm coding a small piece of server software for the personal use of several users. Not hundreds, not thousands, but perhaps 3-10 at a time.
Since it's a threaded server, SQLite doesn't work. It complains about threads like this:
> ProgrammingError: SQLite objects created in a thread can only be used in that same thre... | First note that [sqlite is thread safe](http://www.sqlite.org/faq.html#q6)
```
$ python
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
>>> sqlite.threadsafety
1
```
Then just make s... |
Check if a parameter is a Python module? | 1,547,466 | 18 | 2009-10-10T09:18:38Z | 1,547,475 | 37 | 2009-10-10T09:25:46Z | [
"python",
"types"
] | How can I (pythonically) check if a parameter is a Python module? There's no type like module or package.
```
>>> os
<module 'os' from '/usr/lib/python2.6/os.pyc'>
>>> isinstance(os, module)
Traceback (most recent call last):
File "/usr/lib/gedit-2/plugins/pythonconsole/console.py", line 290, in __run
r = eval(... | ```
from types import ModuleType
isinstance(obj, ModuleType)
``` |
Check if a parameter is a Python module? | 1,547,466 | 18 | 2009-10-10T09:18:38Z | 1,547,567 | 20 | 2009-10-10T10:13:58Z | [
"python",
"types"
] | How can I (pythonically) check if a parameter is a Python module? There's no type like module or package.
```
>>> os
<module 'os' from '/usr/lib/python2.6/os.pyc'>
>>> isinstance(os, module)
Traceback (most recent call last):
File "/usr/lib/gedit-2/plugins/pythonconsole/console.py", line 290, in __run
r = eval(... | ```
>>> import inspect, os
>>> inspect.ismodule(os)
True
``` |
How to sort this list in Python? | 1,547,733 | 5 | 2009-10-10T11:37:47Z | 1,547,739 | 27 | 2009-10-10T11:41:33Z | [
"python",
"list"
] | [ {'time':33}, {'time':11}, {'time':66} ]
How to sort by the "time" element, DESC. | Like this:
```
from operator import itemgetter
l = sorted(l, key=itemgetter('time'), reverse=True)
```
Or:
```
l = sorted(l, key=lambda a: a['time'], reverse=True)
```
output:
```
[{'time': 66}, {'time': 33}, {'time': 11}]
```
If you don't want to keep the original order you can use `your_list.sort` which modifie... |
Mini-languages in Python | 1,547,782 | 34 | 2009-10-10T12:06:18Z | 1,547,788 | 16 | 2009-10-10T12:12:23Z | [
"python",
"dsl"
] | I'm after creating a simple mini-language parser in Python, programming close to the problem domain and all that.
Anyway, I was wondering how the people on here would go around doing that - what are the preferred ways of doing this kind of thing in Python?
I'm not going to give specific details of what I'm after beca... | I have limited but positive experience with [PLY](http://www.dabeaz.com/ply/) (Python Lex-Yacc). It combines [Lex and Yacc](http://dinosaur.compilertools.net/) functionality in a single Python class. You may want to check it out.
Fellow Stackoverflow'er [Ned Batchelder](http://stackoverflow.com/users/14343/ned-batchel... |
Mini-languages in Python | 1,547,782 | 34 | 2009-10-10T12:06:18Z | 1,548,368 | 29 | 2009-10-10T16:20:32Z | [
"python",
"dsl"
] | I'm after creating a simple mini-language parser in Python, programming close to the problem domain and all that.
Anyway, I was wondering how the people on here would go around doing that - what are the preferred ways of doing this kind of thing in Python?
I'm not going to give specific details of what I'm after beca... | [Pyparsing](http://pyparsing.wikispaces.com/) is handy for writing "little languages". I gave a [presentation at PyCon'06](http://www.ptmcg.com/geo/python/confs/pyCon2006%5Fpres2.html) on writing a simple adventure game engine, in which the language being parsed and interpreted was the game command set ("inventory", "t... |
Mini-languages in Python | 1,547,782 | 34 | 2009-10-10T12:06:18Z | 1,548,393 | 14 | 2009-10-10T16:29:48Z | [
"python",
"dsl"
] | I'm after creating a simple mini-language parser in Python, programming close to the problem domain and all that.
Anyway, I was wondering how the people on here would go around doing that - what are the preferred ways of doing this kind of thing in Python?
I'm not going to give specific details of what I'm after beca... | I would recommend [`funcparserlib`](http://code.google.com/p/funcparserlib/). It was written especially for parsing little languages and DSLs and it is faster and smaller than `pyparsing` (see stats on its homepage). Minimalists and functional programmers should like `funcparserlib`.
Edit: By the way, I'm the author o... |
How do I parse indents and dedents with pyparsing? | 1,547,944 | 7 | 2009-10-10T13:27:37Z | 1,548,219 | 9 | 2009-10-10T15:24:35Z | [
"python",
"indentation",
"parser-generator",
"pyparsing"
] | Here is a subset of the Python grammar:
```
single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: pass_stmt
pass_stmt: 'pass'
compound_stmt: if_stmt
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['els... | There are a couple of examples on the pyparsing wiki [Examples page](http://pyparsing.wikispaces.com/Examples) that could give you some insights:
* [pythonGrammarParser.py](http://pyparsing.wikispaces.com/file/view/pythonGrammarParser.py)
* [indentedGrammarExample.py](http://pyparsing.wikispaces.com/file/view/indented... |
Python library for syntax highlighting | 1,548,276 | 2 | 2009-10-10T15:48:40Z | 1,548,295 | 8 | 2009-10-10T15:54:19Z | [
"python",
"syntax-highlighting",
"pygments"
] | Which Python library for syntax highlighting is the best one? I'm interested in things like supported languages, ease of use, pythonic design, dependencies, development status, etc. | I think [pygments](http://pygments.org/) is the greatest choice. It supports a large number of languages and it's very mature. |
Python for C++ or Java Programmer | 1,548,620 | 4 | 2009-10-10T17:56:09Z | 1,548,644 | 11 | 2009-10-10T18:04:08Z | [
"python"
] | I have a background in C++ and Java and Objective C programming, but i am finding it hard to learn python, basically where its "Main Function" or from where the program start executing. So is there any tutorial/book which can teach python to people who have background in C++ or Java. Basically something which can show ... | When you run a script through the Python interpreter (or import that script from another script), **it actually executes all the code from beginning to end** -- in *that* sense, **there is no "entry point" to a Python script**.
So to work around this, Python automatically creates a `__name__` variable and fills it wit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.