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 |
|---|---|---|---|---|---|---|---|---|---|
Python: namedtuple._replace() doesn't work as descrbed in the documentation | 2,166,147 | 19 | 2010-01-30T00:03:53Z | 2,166,160 | 10 | 2010-01-30T00:07:24Z | [
"python",
"namedtuple"
] | I was having trouble implementing `namedtuple._replace()`, so I copied the code right off of the documentation:
```
Point = namedtuple('Point', 'x,y')
p = Point(x=11, y=22)
p._replace(x=33)
print p
```
and I got:
```
Point(x=11, y=22)
```
instead of:
```
Point(x=33, y=22)
```
as is shown in the doc.
I'm using... | A tuple is immutable. `_replace()` returns a new tuple with your modifications:
```
p = p._replace(x=33)
``` |
Python: namedtuple._replace() doesn't work as descrbed in the documentation | 2,166,147 | 19 | 2010-01-30T00:03:53Z | 2,166,161 | 50 | 2010-01-30T00:07:43Z | [
"python",
"namedtuple"
] | I was having trouble implementing `namedtuple._replace()`, so I copied the code right off of the documentation:
```
Point = namedtuple('Point', 'x,y')
p = Point(x=11, y=22)
p._replace(x=33)
print p
```
and I got:
```
Point(x=11, y=22)
```
instead of:
```
Point(x=33, y=22)
```
as is shown in the doc.
I'm using... | Yes it does, it works exactly as documented.
`._replace` *returns* a new namedtuple, it does not modify the original, so you need to write this:
```
p = p._replace(x=33)
```
See here: [somenamedtuple.\_replace(kwargs)](http://docs.python.org/dev/library/collections.html#collections.somenamedtuple._replace) for more ... |
Casting from list of lists of strings to list of lists of ints in python | 2,166,577 | 4 | 2010-01-30T02:26:39Z | 2,166,583 | 8 | 2010-01-30T02:30:20Z | [
"python"
] | I'm reading some numbers from a data source that represent xy coordinates that I'll be using for a TSP-esque problem. I'm new to python, so I'm trying to make the most of lists. After reading and parsing through the data, I'm left with a list of string lists that looks like this:
> [['565.0', '575.0'], ['1215.0',
> '2... | ```
x = [['565.0', '575.0'], ['1215.0', '245.0'], ['1740.0', '245.0']]
x = [[int(float(j)) for j in i] for i in x]
``` |
Python: how to check if an object is an instance of a namedtuple? | 2,166,818 | 9 | 2010-01-30T04:12:43Z | 2,166,841 | 14 | 2010-01-30T04:21:18Z | [
"python",
"introspection",
"namedtuple"
] | How do I check if an object is an instance of a [Named tuple](http://docs.python.org/dev/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields)? | Calling the *function* `collections.namedtuple` gives you a new type that's a subclass of `tuple` (and no other classes) with a member named `_fields` that's a tuple whose items are all strings. So you could check for each and every one of these things:
```
def isnamedtupleinstance(x):
t = type(x)
b = t.__base... |
Getting next element while cycling through a list | 2,167,868 | 21 | 2010-01-30T12:33:37Z | 2,167,962 | 34 | 2010-01-30T13:17:33Z | [
"python",
"list",
"iteration",
"next"
] | ```
li = [0, 1, 2, 3]
running = True
while running:
for elem in li:
thiselem = elem
nextelem = li[li.index(elem)+1]
```
When this reaches the last element, an `IndexError` is raised (as is the case for any list, tuple, dictionary, or string that is iterated). I actually want at that point for `nex... | After thinking this through carefully, I think this is the best way. It lets you step off in the middle easily without using `break`, which I think is important, and it requires minimal computation, so I think it's the fastest. It also doesn't require that `li` be a list or tuple. It could be any iterator.
```
from it... |
Converting a String to List in Python | 2,168,123 | 8 | 2010-01-30T14:13:31Z | 2,168,137 | 29 | 2010-01-30T14:16:10Z | [
"python",
"django",
"string"
] | I'm trying to create a list from arguments I receive in a url.
e.g I have:
```
user.com/?users=0,1,2
```
Now when I receive it in the request it comes as a string. I want to make a list out of "0,1,2" [0,1,2] | Use the `split` method. Example:
```
>>> "0,1,2".split(",")
['0', '1', '2']
```
Or even,
```
>>> [int(x) for x in "0,1,2".split(",")]
[0, 1, 2]
``` |
Can access AppEngine SDK sites via local ip-address when localhost works just fine and a MacOSX | 2,168,409 | 10 | 2010-01-30T15:47:05Z | 21,776,775 | 8 | 2014-02-14T10:26:46Z | [
"python",
"google-app-engine",
"facebook",
"osx"
] | Can access AppEngine SDK sites via local ip-address when localhost works just fine and a MacOSX using the GoogleAppEngineLauncher.
I'm trying to setup facebook development site (using a dyndns.org hostname pointing at my firewall which redirects the call to my mac book).
It seems like GoogleAppEngineLauncher defaults... | As per the latest [documentation](https://developers.google.com/appengine/docs/python/tools/devserver?csw=1#Python_Command-line_arguments) `-a` wont work anymore.
This is possible by passing `--host` argument with `dev_appserver.py` command
`dev_appserver --host=<your_ip_address> <your_app>`
`--host=
The host addres... |
random.sample() returning the same random sequence every time? | 2,168,648 | 7 | 2010-01-30T17:07:38Z | 2,168,682 | 11 | 2010-01-30T17:22:00Z | [
"python",
"random"
] | I'm using python's random.sample(population, k) function to generate a set of random values from a list to create new permutations of that list. The issue is that each time it runs through a loop, it's generating the *exact same* random sequence. Why is this? I even used random.seed(i) so that the i variable (changing ... | I'm not sure what you mean by "generating the *exact same* random sequence". Since you only give us a snippet that can't be run on its own, it's quite possible that there are bugs in other parts of your code that you choose not to show us -- I've tried adding the absolutely minimal amount of code needed to make your sn... |
Python: creating class instance without calling initializer | 2,168,964 | 15 | 2010-01-30T18:41:37Z | 2,169,191 | 18 | 2010-01-30T19:46:52Z | [
"python",
"class",
"constructor",
"initialization"
] | Is there any way to avoid calling `__init__` on a class while initializing it, such as from a class method?
I am trying to create a case and punctuation insensitive string class in Python used for efficient comparison purposes but am having trouble creating a new instance without calling `__init__`.
```
>>> class Str... | When feasible, letting `__init__` get called (and make the call innocuous by suitable arguments) is preferable. However, should that require too much of a contortion, you do have an alternative, as long as you avoid the disastrous choice of using old-style classes (there is **no** good reason to use old-style classes i... |
How to add cookie to existing cookielib CookieJar instance in Python? | 2,169,281 | 14 | 2010-01-30T20:12:26Z | 2,169,298 | 34 | 2010-01-30T20:20:52Z | [
"python",
"cookies",
"mechanize",
"cookiejar",
"cookielib"
] | I have a CookieJar that's being used with mechanize that I want to add a cookie to. How can I go about doing this? make\_cookie() and set\_cookie() weren't clear enough for me.
```
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
``` | Managed to figure this out
```
import mechanize
import cookielib
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
ck = cookielib.Cookie(version=0, name='Name', value='1', port=None, port_specified=False, domain='www.example.com', domain_specified=False, domain_initial_dot=False, path='/', pa... |
Use numpy to mask an image with a pattern? | 2,169,605 | 12 | 2010-01-30T21:57:22Z | 2,170,057 | 12 | 2010-01-31T00:17:15Z | [
"python",
"image-processing",
"numpy"
] | I'm using numpy to build pixel arrays. An 800x600 image is an 3-dimensional array of uint8, 800x600x3. I also have a similar array with a fixed pattern (a checkerboard, see [here](http://stackoverflow.com/questions/2169478/how-to-make-a-checkerboard-in-numpy)). I have another array, 800x600 of mask values. Where the ma... | ```
idx=(mask==0)
image[idx]=chex[idx]
```
Note that `image` has shape (800,600,3), while `idx` has shape (800,600). [The rules](http://docs.scipy.org/numpy/docs/numpy-docs/reference/arrays.indexing.rst/#arrays-indexing) for indexing state
> if the selection tuple is smaller than
> n, then as many : objects as needed... |
Using list comprehension in Python to do something similar to zip()? | 2,169,623 | 5 | 2010-01-30T22:03:43Z | 2,169,626 | 24 | 2010-01-30T22:05:44Z | [
"python",
"list",
"list-comprehension"
] | I'm a Python newbie and one of the things I am trying to do is wrap my head around list comprehension. I can see that it's a pretty powerful feature that's worth learning.
```
cities = ['Chicago', 'Detroit', 'Atlanta']
airports = ['ORD', 'DTW', 'ATL']
print zip(cities,airports)
[('Chicago', 'ORD'), ('Detroit', 'DTW')... | Something like this:
```
[[c, a] for c, a in zip(cities, airports)]
```
Alternately, the `list` constructor can convert tuples to lists:
```
[list(x) for x in zip(cities, airports)]
```
Or, the `map` function is slightly less verbose in this case:
```
map(list, zip(cities, airports))
``` |
List multiplication | 2,169,838 | 5 | 2010-01-30T23:03:37Z | 2,169,850 | 7 | 2010-01-30T23:07:01Z | [
"python",
"list",
"cartesian-product"
] | I have a list L = [a, b, c] and I want to generate a list of tuples :
```
[(a,a), (a,b), (a,c), (b,a), (b,b), (b,c)...]
```
I tried doing L \* L but it didn't work. Can someone tell me how to get this in python. | Take a look at the `itertools` module, which provides a `product` member.
```
L =[1,2,3]
import itertools
res = list(itertools.product(L,L))
print(res)
```
Gives:
```
[(1,1),(1,2),(1,3),(2,1), .... and so on]
``` |
List multiplication | 2,169,838 | 5 | 2010-01-30T23:03:37Z | 2,169,853 | 13 | 2010-01-30T23:07:27Z | [
"python",
"list",
"cartesian-product"
] | I have a list L = [a, b, c] and I want to generate a list of tuples :
```
[(a,a), (a,b), (a,c), (b,a), (b,b), (b,c)...]
```
I tried doing L \* L but it didn't work. Can someone tell me how to get this in python. | The [`itertools`](http://docs.python.org/library/itertools.html) module contains a number of helpful functions for this sort of thing. It looks like you may be looking for [`product`](http://docs.python.org/library/itertools.html#itertools.product):
```
>>> import itertools
>>> L = [1,2,3]
>>> itertools.product(L,L)
<... |
List multiplication | 2,169,838 | 5 | 2010-01-30T23:03:37Z | 2,169,854 | 22 | 2010-01-30T23:07:31Z | [
"python",
"list",
"cartesian-product"
] | I have a list L = [a, b, c] and I want to generate a list of tuples :
```
[(a,a), (a,b), (a,c), (b,a), (b,b), (b,c)...]
```
I tried doing L \* L but it didn't work. Can someone tell me how to get this in python. | You can do it with a list comprehension:
```
[ (x,y) for x in L for y in L]
```
**edit**
You can also use itertools.product as others have suggested, but only if you are using 2.6 onwards. The list comprehension will work will all versions of Python from 2.0. If you do use itertools.product bear in mind that it retu... |
Iterate over model instance field names and values in template | 2,170,228 | 123 | 2010-01-31T01:48:11Z | 2,170,243 | 115 | 2010-01-31T01:54:53Z | [
"python",
"django",
"django-templates"
] | I'm trying to create a basic template to display the selected instance's field values, along with their names. Think of it as just a standard output of the values of that instance in table format, with the field name (verbose\_name specifically if specified on the field) in the first column and the value of that field ... | `model._meta.get_all_field_names()` will give you all the model's field names, then you can use `model._meta.get_field()` to work your way to the verbose name, and `getattr(model_instance, 'field_name')` to get the value from the model.
NOTE: `model._meta.get_all_field_names()` is deprecated in django 1.9. Instead use... |
Iterate over model instance field names and values in template | 2,170,228 | 123 | 2010-01-31T01:48:11Z | 2,226,150 | 11 | 2010-02-09T01:29:03Z | [
"python",
"django",
"django-templates"
] | I'm trying to create a basic template to display the selected instance's field values, along with their names. Think of it as just a standard output of the values of that instance in table format, with the field name (verbose\_name specifically if specified on the field) in the first column and the value of that field ... | Here's another approach using a model method. This version resolves picklist/choice fields, skips empty fields, and lets you exclude specific fields.
```
def get_all_fields(self):
"""Returns a list of all field names on the instance."""
fields = []
for f in self._meta.fields:
fname = f.name ... |
Iterate over model instance field names and values in template | 2,170,228 | 123 | 2010-01-31T01:48:11Z | 2,311,015 | 52 | 2010-02-22T13:11:04Z | [
"python",
"django",
"django-templates"
] | I'm trying to create a basic template to display the selected instance's field values, along with their names. Think of it as just a standard output of the values of that instance in table format, with the field name (verbose\_name specifically if specified on the field) in the first column and the value of that field ... | You can use Django's **to-python** queryset serializer.
Just put the following code in your view:
```
from django.core import serializers
data = serializers.serialize( "python", SomeModel.objects.all() )
```
And then in the template:
```
{% for instance in data %}
{% for field, value in instance.fields.items %}... |
Iterate over model instance field names and values in template | 2,170,228 | 123 | 2010-01-31T01:48:11Z | 3,431,104 | 56 | 2010-08-07T16:13:17Z | [
"python",
"django",
"django-templates"
] | I'm trying to create a basic template to display the selected instance's field values, along with their names. Think of it as just a standard output of the values of that instance in table format, with the field name (verbose\_name specifically if specified on the field) in the first column and the value of that field ... | Finally found a good solution to this on [the dev mailing list](http://groups.google.com/group/django-developers/browse_thread/thread/44cd834438cfda77/557f53697658ab04?lnk=gst&q=template%20model#557f53697658ab04):
In the view add:
```
from django.forms.models import model_to_dict
def show(request, object_id):
ob... |
Iterate over model instance field names and values in template | 2,170,228 | 123 | 2010-01-31T01:48:11Z | 7,769,930 | 7 | 2011-10-14T15:29:09Z | [
"python",
"django",
"django-templates"
] | I'm trying to create a basic template to display the selected instance's field values, along with their names. Think of it as just a standard output of the values of that instance in table format, with the field name (verbose\_name specifically if specified on the field) in the first column and the value of that field ... | There should really be a built-in way to do this. I wrote this utility `build_pretty_data_view` that takes a model object and form instance (a form based on your model) and returns a `SortedDict`.
Benefits to this solution include:
* It preserves order using Django's built-in `SortedDict`.
* When tries to get the lab... |
Iterate over model instance field names and values in template | 2,170,228 | 123 | 2010-01-31T01:48:11Z | 9,942,455 | 9 | 2012-03-30T11:55:40Z | [
"python",
"django",
"django-templates"
] | I'm trying to create a basic template to display the selected instance's field values, along with their names. Think of it as just a standard output of the values of that instance in table format, with the field name (verbose\_name specifically if specified on the field) in the first column and the value of that field ... | Ok, I know this is a bit late, but since I stumbled upon this before finding the correct answer so might someone else.
From the [django docs](https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values):
```
# This list contains a Blog object.
>>> Blog.objects.filter(name__start... |
Iterate over model instance field names and values in template | 2,170,228 | 123 | 2010-01-31T01:48:11Z | 30,278,233 | 15 | 2015-05-16T16:41:36Z | [
"python",
"django",
"django-templates"
] | I'm trying to create a basic template to display the selected instance's field values, along with their names. Think of it as just a standard output of the values of that instance in table format, with the field name (verbose\_name specifically if specified on the field) in the first column and the value of that field ... | In light of Django 1.8's release (and the formalization of the [Model \_meta API](https://docs.djangoproject.com/en/1.8/ref/models/meta/), I figured I would update this with a more recent answer.
Assuming the same model:
```
class Client(Model):
name = CharField(max_length=150)
email = EmailField(max_length=1... |
Can existing virtualenv be upgraded gracefully? | 2,170,252 | 53 | 2010-01-31T01:58:45Z | 2,171,079 | 38 | 2010-01-31T08:48:00Z | [
"python",
"virtualenv"
] | I have a virtualenv created for Python 2.5 and want to "upgrade" it to Python 2.6.
Here is how it was originally set up:
```
virtualenv --no-site-packages -p python2.5 myenv
```
I now run virtualenv in the same directory to upgrade:
```
virtualenv --no-site-packages -p python2.6 myenv
...
Not overwriting existing p... | You can use the Python 2.6 virtualenv to "revirtual" the existing directory. You will have to reinstall all the modules you installed though. I often have a virtual directory for developing a module, and virtualenv the same directory with many versions of Python, and it works just fine. :) |
access ElementTree node parent node | 2,170,610 | 32 | 2010-01-31T05:02:47Z | 2,170,994 | 24 | 2010-01-31T08:04:25Z | [
"python",
"elementtree"
] | I am using the builtin Python ElementTree module. It is straightforward to access children, but what about parent nor sibling nodes? - can this be done efficiently without traversing the entire tree? | There's no direct support in the form of a `parent` attribute, but you can perhaps use the patterns described [here](http://effbot.org/zone/element.htm#accessing-parents) to achieve the desired effect. The following one-liner is suggested (from the linked-to post) to create a child-to-parent mapping for a whole tree:
... |
access ElementTree node parent node | 2,170,610 | 32 | 2010-01-31T05:02:47Z | 20,132,342 | 11 | 2013-11-21T21:31:37Z | [
"python",
"elementtree"
] | I am using the builtin Python ElementTree module. It is straightforward to access children, but what about parent nor sibling nodes? - can this be done efficiently without traversing the entire tree? | [Vinay's answer](http://stackoverflow.com/a/2170994/1556416) should still work, but for Python 2.7+ and 3.2+ the following is recommended:
```
parent_map = {c:p for p in tree.iter() for c in p}
```
`getiterator()` is deprecated in favor of `iter()`, and it's nice to use the new `dict` list comprehension constructor.
... |
Why (dictionary.keys()).sort() is not working in python? | 2,170,632 | 2 | 2010-01-31T05:13:49Z | 2,170,638 | 7 | 2010-01-31T05:16:37Z | [
"python",
"sorting"
] | I'm new to Python and can't understand why a thing like this does not work.
I can't find the issue raised elsewhere either.
```
toto = {'a':1, 'c':2 , 'b':3}
toto.keys().sort() #does not work (yields none)
(toto.keys()).sort() #does not work (yields none)
eval('toto.keys()').sort() #does not work (... | `sort()` sorts the list *in place*. It returns `None` to prevent you from thinking that it's leaving the original list alone and returning a sorted copy of it. |
Why (dictionary.keys()).sort() is not working in python? | 2,170,632 | 2 | 2010-01-31T05:13:49Z | 2,170,643 | 7 | 2010-01-31T05:18:09Z | [
"python",
"sorting"
] | I'm new to Python and can't understand why a thing like this does not work.
I can't find the issue raised elsewhere either.
```
toto = {'a':1, 'c':2 , 'b':3}
toto.keys().sort() #does not work (yields none)
(toto.keys()).sort() #does not work (yields none)
eval('toto.keys()').sort() #does not work (... | ```
sorted(toto.keys())
```
Should do what you want. The sort method you're using sorts in place and returns None. |
Get first list index containing sub string in Python | 2,170,900 | 13 | 2010-01-31T07:23:13Z | 2,170,915 | 18 | 2010-01-31T07:29:09Z | [
"python",
"list"
] | For lists, the method list.index(x) returns the index in the list of the first item whose value is x. But if I want to look inside the list items, and not just at the whole items, how do I make the most Pythoninc method for this?
For example, with
```
l = ['the cat ate the mouse','the tiger ate the chicken','the hors... | A non-slicky method:
```
def index_containing_substring(the_list, substring):
for i, s in enumerate(the_list):
if substring in s:
return i
return -1
``` |
Python - efficient method to remove all non-letters and replace them with underscores | 2,171,095 | 10 | 2010-01-31T08:53:09Z | 2,171,100 | 16 | 2010-01-31T08:56:24Z | [
"python",
"string",
"performance"
] | ```
def format_title(title):
''.join(map(lambda x: x if (x.isupper() or x.islower()) else '_', title.strip()))
```
Anything faster? | ```
import re
title = re.sub("[\W\d]", "_", title.strip())
```
should be faster.
If you want to replace a succession of adjacent non-letters with a single underscore, use
```
title = re.sub("[\W\d]+", "_", title.strip())
```
instead which is even faster.
I just ran a time comparison:
```
C:\>python -m timeit -n 1... |
Python - efficient method to remove all non-letters and replace them with underscores | 2,171,095 | 10 | 2010-01-31T08:53:09Z | 2,171,119 | 20 | 2010-01-31T09:03:27Z | [
"python",
"string",
"performance"
] | ```
def format_title(title):
''.join(map(lambda x: x if (x.isupper() or x.islower()) else '_', title.strip()))
```
Anything faster? | The faster way to do it is to use `str.translate()`
This is ~50 times faster than your way
```
# You only need to do this once
>>> title_trans=''.join(chr(c) if chr(c).isupper() or chr(c).islower() else '_' for c in range(256))
>>> "abcde1234!@%^".translate(title_trans)
'abcde________'
# Using map+lambda
$ python -m... |
Python regex for matching bb code | 2,172,046 | 2 | 2010-01-31T14:36:16Z | 2,172,057 | 7 | 2010-01-31T14:40:13Z | [
"python",
"regex"
] | I'm writing a very simple bbcode parse. If i want to replace `hello i'm a [b]bold[/b] text`, i have success with replacing this regex
`r'\[b\](.*)\[\/b\]'`
with this
`<strong>\g<1></strong>`
to get `hello, i'm a <strong>bold</strong> text`.
If I have two or more tags of the same type, it fails. eg:
`i'm [b]bold[/... | You shouldn't use regular expressions to parse non-regular languages (like matching tags). Look into a parser instead.
Edit - a quick Google search takes me [here](http://www.willmcgugan.com/blog/tech/2007/3/10/bbcode-python-module/). |
Why I can't extend bool in Python? | 2,172,189 | 21 | 2010-01-31T15:22:39Z | 2,172,195 | 9 | 2010-01-31T15:25:07Z | [
"python",
"boolean",
"restriction"
] | ```
>>> class BOOL(bool):
... print "why?"
...
why?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
type 'bool' is not an acceptable base type
```
**I thought Python trusted the programmer.** | Here is a post that explains the reasoning behind the decision: <http://mail.python.org/pipermail/python-dev/2004-February/042537.html>
The idea is that `bool` has a specific purpose - to be `True` or to be `False`, and adding to that would only serve to complicate your code elsewhere. |
Why I can't extend bool in Python? | 2,172,189 | 21 | 2010-01-31T15:22:39Z | 2,172,204 | 33 | 2010-01-31T15:27:10Z | [
"python",
"boolean",
"restriction"
] | ```
>>> class BOOL(bool):
... print "why?"
...
why?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
type 'bool' is not an acceptable base type
```
**I thought Python trusted the programmer.** | Guido's take on it:
> I thought about this last
> night, and realized that you shouldn't
> be allowed to subclass bool at all! A
> subclass would only be useful when it
> has instances, but the mere existance
> of an instance of a subclass of bool
> would break the invariant that True
> and False are the only instance... |
Why I can't extend bool in Python? | 2,172,189 | 21 | 2010-01-31T15:22:39Z | 2,172,697 | 9 | 2010-01-31T18:03:42Z | [
"python",
"boolean",
"restriction"
] | ```
>>> class BOOL(bool):
... print "why?"
...
why?
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
type 'bool' is not an acceptable base type
```
**I thought Python trusted the programmer.** | Since the OP mentions in a comment:
> I want `1 and 2` to return an instance
> of my class.
I think it's important to point out that this is entirely impossible: Python does not let you *alter* built-in types (and, in particular, their special methods). Literal `1` will always be an instance of built-in type `int`, a... |
Why is my simple python gtk+cairo program running so slowly/stutteringly? | 2,172,525 | 9 | 2010-01-31T17:04:13Z | 2,173,992 | 10 | 2010-02-01T00:16:56Z | [
"python",
"animation",
"gtk",
"pygtk",
"cairo"
] | My program draws circles moving on the window. I think I must be missing some basic gtk/cairo concept because it seems to be running too slowly/stutteringly for what I am doing. Any ideas? Thanks for any help!
```
#!/usr/bin/python
import gtk
import gtk.gdk as gdk
import math
import random
import gobject
# The numbe... | One of the problems is that you are drawing the same basic object again and again. I'm not sure about GTK+ buffering behavior, but also keep in mind that basic function calls incur a cost in Python. I've added a frame counter to your program, and I with your code, I got around 30fps max.
There are several things you c... |
How to do a JOIN in SQLAlchemy on 3 tables, where one of them is mapping between other two? | 2,173,031 | 9 | 2010-01-31T19:36:18Z | 2,173,083 | 9 | 2010-01-31T19:55:49Z | [
"python",
"sql",
"sqlalchemy"
] | Suppose I have the following tables:
* `Articles` with fields `article_id`, `title`
* `Tags` with fields `tag_id`, `name`
* `ArticleTags` with fields `article_id`, `tag_id`
And I wish to find all articles that have a given tag. How do I create this complicated join in SQLAlchemy?
In SQL it would look like:
```
SELE... | Assuming that you set the ForeignKey constraints correctly and created mappers:
```
q = Session.query(Articles).filter(Articles.article_id == ArticleTags.article_id).\
filter(ArticleTags.tag_id == Tags.tag_id).\
filter(Tags.name == 'tag_name')
```
If you have setup a Many-to-Many relation it's even more simpl... |
How to create nested lists in python? | 2,173,087 | 6 | 2010-01-31T19:58:25Z | 2,173,119 | 9 | 2010-01-31T20:06:55Z | [
"python",
"list",
"arrays",
"matrix",
"nested-lists"
] | I know you can create easily nested lists in python like this:
```
[[1,2],[3,4]]
```
But how to create a 3x3x3 matrix of zeroes?
```
[[[0] * 3 for i in range(0, 3)] for j in range (0,3)]
```
or
```
[[[0]*3]*3]*3
```
Doesn't seem right. There is no way to create it just passing a list of dimensions to a method? Ex... | In case a matrix is actually what you are looking for, consider the numpy package.
<http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html#numpy.zeros>
This will give you a 3x3x3 array of zeros:
```
numpy.zeros((3,3,3))
```
You also benefit from the convenience features of a module built for scientifi... |
how to sort 2d array by row in python? | 2,173,797 | 12 | 2010-01-31T23:11:51Z | 2,173,843 | 18 | 2010-01-31T23:23:40Z | [
"python"
] | i have 2d array,dimension 3x10,and i want to sort by values in 2nd row,from lowest to highest value,any useful tip? | Python, per se, has no "2d array" -- it has (1d) lists as built-ins, and (1d) arrays in standard library module [array](http://docs.python.org/library/array.html?highlight=array#module-array). There are third-party libraries such as `numpy` which do provide Python-usable multi-dimensional arrays, but of course you'd be... |
how to sort 2d array by row in python? | 2,173,797 | 12 | 2010-01-31T23:11:51Z | 2,173,873 | 21 | 2010-01-31T23:30:31Z | [
"python"
] | i have 2d array,dimension 3x10,and i want to sort by values in 2nd row,from lowest to highest value,any useful tip? | How does your "2D array" look like?
For example:
```
>>> a = [
[12, 18, 6, 3],
[ 4, 3, 1, 2],
[15, 8, 9, 6]
]
>>> a.sort(key=lambda x: x[1])
>>> a
[[4, 3, 1, 2],
[15, 8, 9, 6],
[12, 18, 6, 3]]
```
But I guess you want something like this:
```
>>> a = [
[12, 18, 6, 3],
[ 4, 3, 1... |
Why is this genexp performing worse than a list comprehension? | 2,173,845 | 6 | 2010-01-31T23:23:57Z | 2,173,869 | 14 | 2010-01-31T23:29:29Z | [
"python",
"list-comprehension",
"generator-expression"
] | I was trying to find the quickest way to count the number of items in a list matching a specific filter.
In this case, finding how many odd numbers there are in a list.
While doing this, I was surprised by the results of comparing a list comprehension vs the equivalent generator expression:
```
python -m timeit -s "L... | When essentially unlimited memory is available (which will invariably be the case in tiny benchmarks, although often not in real-world problems!-), lists will tend to outperform generators because they can get allocated just once, in one "big bunch" (no memory fragmentation, etc), while generators require (internally) ... |
recursive nested expression in Python | 2,174,015 | 3 | 2010-02-01T00:27:04Z | 2,174,029 | 11 | 2010-02-01T00:31:35Z | [
"python",
"regex",
"nested",
"expression"
] | I am using Python 2.6.4.
I have a series of select statements in a text file and I need to extract the field names from each select query. This would be easy if some of the fields didn't use nested functions like to\_char() etc.
Given select statement fields that could have several nested parenthese like "ltrim(rtrim... | Regular expressions are not suitable for parsing "nested" structures. Try, instead, a full-fledged parsing kit such as [pyparsing](http://pyparsing.wikispaces.com/) -- examples of using pyparsing specifically to parse SQL can be found [here](http://michelhollands.net/blog/2007/10/24/using-pyparsing/) and [here](http://... |
Python rounding issue | 2,174,081 | 9 | 2010-02-01T00:51:23Z | 2,174,120 | 9 | 2010-02-01T01:06:28Z | [
"python"
] | I have come across a very strange issue in python. (Using python 2.4.x)
In windows:
```
>>> a = 2292.5
>>> print '%.0f' % a
2293
```
But in Solaris:
```
>>> a = 2292.5
>>> print '%.0f' % a
2292
```
But this is the same in both windows and solaris:
```
>>> a = 1.5
>>> print '%.0f' % a
2
```
Can someone explain th... | The function ultimately in charge of performing that formatting is `PyOS_snprintf`
(see [the sources](http://svn.python.org/projects/python/trunk/Python/mysnprintf.c)). As you surmise, that's unfortunately system-dependent, i.e., it relies on `vsprintf`, `vsnprintf` or other similar functions that are ultimately suppli... |
Detect most likely words from text without spaces / combined words | 2,174,093 | 10 | 2010-02-01T00:55:56Z | 2,176,059 | 9 | 2010-02-01T10:45:51Z | [
"python",
"split",
"word"
] | Is there a good library can detect and split words from a combined string?
Example:
```
"cdimage" -> ["cd", "image"]
"filesaveas" -> ["file", "save", "as"]
``` | Here's a dynamic programming solution (implemented as a memoized function). Given a dictionary of words with their frequencies, it splits the input text at the positions that give the overall most likely phrase. You'll have to find a real wordlist, but I included some made-up frequencies for a simple test.
```
WORD_FR... |
Why do we need tuples in Python (or any immutable data type)? | 2,174,124 | 102 | 2010-02-01T01:08:15Z | 2,174,151 | 13 | 2010-02-01T01:16:52Z | [
"python",
"tuples"
] | I've read several python tutorials (Dive Into Python, for one), and the language reference on Python.org - I don't see why the language needs tuples.
Tuples have no methods compared to a list or set, and if I must convert a tuple to a set or list to be able to sort them, what's the point of using a tuple in the first ... | Sometimes we like to use objects as dictionary keys
For what it's worth, tuples recently (2.6+) grew `index()` and `count()` methods |
Why do we need tuples in Python (or any immutable data type)? | 2,174,124 | 102 | 2010-02-01T01:08:15Z | 2,174,170 | 98 | 2010-02-01T01:23:20Z | [
"python",
"tuples"
] | I've read several python tutorials (Dive Into Python, for one), and the language reference on Python.org - I don't see why the language needs tuples.
Tuples have no methods compared to a list or set, and if I must convert a tuple to a set or list to be able to sort them, what's the point of using a tuple in the first ... | 1. immutable objects can allow substantial optimization; this is presumably why strings are also immutable in Java, developed quite separately but about the same time as Python, and just about everything is immutable in truly-functional languages.
2. in Python in particular, only immutables can be hashable (and, theref... |
Why do we need tuples in Python (or any immutable data type)? | 2,174,124 | 102 | 2010-02-01T01:08:15Z | 2,174,172 | 18 | 2010-02-01T01:23:45Z | [
"python",
"tuples"
] | I've read several python tutorials (Dive Into Python, for one), and the language reference on Python.org - I don't see why the language needs tuples.
Tuples have no methods compared to a list or set, and if I must convert a tuple to a set or list to be able to sort them, what's the point of using a tuple in the first ... | > if I must convert a tuple to a set or list to be able to sort them, what's the point of using a tuple in the first place?
In this particular case, there probably isn't a point. This is a non-issue, because this isn't one of the cases where you'd consider using a tuple.
As you point out, tuples are immutable. The re... |
Why do we need tuples in Python (or any immutable data type)? | 2,174,124 | 102 | 2010-02-01T01:08:15Z | 2,174,236 | 31 | 2010-02-01T01:50:23Z | [
"python",
"tuples"
] | I've read several python tutorials (Dive Into Python, for one), and the language reference on Python.org - I don't see why the language needs tuples.
Tuples have no methods compared to a list or set, and if I must convert a tuple to a set or list to be able to sort them, what's the point of using a tuple in the first ... | None of the answers above point out the real issue of tuples vs lists, which many new to Python seem to not fully understand.
Tuples and lists serve different purposes. Lists store homogenous data. You can and should have a list like this:
```
["Bob", "Joe", "John", "Sam"]
```
The reason that is a correct use of lis... |
Why do we need tuples in Python (or any immutable data type)? | 2,174,124 | 102 | 2010-02-01T01:08:15Z | 2,174,283 | 7 | 2010-02-01T02:06:06Z | [
"python",
"tuples"
] | I've read several python tutorials (Dive Into Python, for one), and the language reference on Python.org - I don't see why the language needs tuples.
Tuples have no methods compared to a list or set, and if I must convert a tuple to a set or list to be able to sort them, what's the point of using a tuple in the first ... | I've always found having two completely separate types for the same basic data structure (arrays) to be an awkward design, but not a real problem in practice. (Every language has its warts, Python included, but this isn't an important one.)
> Why does anyone care if a variable lives at a different place in memory than... |
Migrating from Javadoc to Python Documentation | 2,175,040 | 6 | 2010-02-01T06:26:41Z | 2,175,074 | 9 | 2010-02-01T06:37:25Z | [
"python",
"documentation",
"python-sphinx"
] | So I've gotten somewhat used to Javadoc style documentation. Looking through various examples of Python code, I'm finding that, at first blush, the documentation *seems* to be missing a lot of information.
The good: vary rarely do you see self-evident bits of documentation. Docstrings are usually a paragraph or less o... | The [reStructuredText](http://docutils.sourceforge.net/rst.html) format was designed in response to the need for Python documentation that could be embedded in docstrings, so the best thing is to **learn reST and format your docstrings with that format**. You might find, as I did, that you then go on to format just abo... |
sscanf in Python | 2,175,080 | 42 | 2010-02-01T06:38:38Z | 2,175,096 | 22 | 2010-02-01T06:41:49Z | [
"python",
"parsing",
"split",
"sscanf",
"procfs"
] | I'm looking for an equivalent to `sscanf()` in Python. I want to parse `/proc/net/*` files, in C I could do something like this:
```
int matches = sscanf(
buffer,
"%*d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %*X %*X:%*X %*X:%*X %*X %*d %*d %ld %*512s\n",
local_addr, &local_port, rem_addr, &rem_por... | You can split on a range of characters using the `re` module.
```
>>> import re
>>> r = re.compile('[ \t\n\r:]+')
>>> r.split("abc:def ghi")
['abc', 'def', 'ghi']
``` |
sscanf in Python | 2,175,080 | 42 | 2010-02-01T06:38:38Z | 2,175,135 | 22 | 2010-02-01T06:51:50Z | [
"python",
"parsing",
"split",
"sscanf",
"procfs"
] | I'm looking for an equivalent to `sscanf()` in Python. I want to parse `/proc/net/*` files, in C I could do something like this:
```
int matches = sscanf(
buffer,
"%*d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %*X %*X:%*X %*X:%*X %*X %*d %*d %ld %*512s\n",
local_addr, &local_port, rem_addr, &rem_por... | Python doesn't have an `sscanf` equivalent built-in, and most of the time it actually makes a whole lot more sense to parse the input by working with the string directly, using regexps, or using a parsing tool.
Probably mostly useful for translating C, people have implemented `sscanf`, such as in this module: <http://... |
sscanf in Python | 2,175,080 | 42 | 2010-02-01T06:38:38Z | 2,180,718 | 12 | 2010-02-01T23:02:59Z | [
"python",
"parsing",
"split",
"sscanf",
"procfs"
] | I'm looking for an equivalent to `sscanf()` in Python. I want to parse `/proc/net/*` files, in C I could do something like this:
```
int matches = sscanf(
buffer,
"%*d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %*X %*X:%*X %*X:%*X %*X %*d %*d %ld %*512s\n",
local_addr, &local_port, rem_addr, &rem_por... | You can parse with module `re` using [named groups](http://docs.python.org/library/re.html#regular-expression-syntax). It won't parse the substrings to their actual datatypes (e.g. `int`) but it's very convenient when parsing strings.
Given this sample line from `/proc/net/tcp`:
```
line=" 0: 00000000:0203 00000000... |
sscanf in Python | 2,175,080 | 42 | 2010-02-01T06:38:38Z | 11,085,456 | 33 | 2012-06-18T14:55:37Z | [
"python",
"parsing",
"split",
"sscanf",
"procfs"
] | I'm looking for an equivalent to `sscanf()` in Python. I want to parse `/proc/net/*` files, in C I could do something like this:
```
int matches = sscanf(
buffer,
"%*d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %*X %*X:%*X %*X:%*X %*X %*d %*d %ld %*512s\n",
local_addr, &local_port, rem_addr, &rem_por... | When I'm in a C mood, I usually use zip and list comprehensions for scanf-like behavior. Like this:
```
input = '1 3.0 false hello'
(a, b, c, d) = [t(s) for t,s in zip((int,float,bool,str),input.split())]
print (a, b, c, d)
```
Note that for more complex format strings, you do need to use regular expressions:
```
im... |
sscanf in Python | 2,175,080 | 42 | 2010-02-01T06:38:38Z | 12,852,181 | 21 | 2012-10-12T04:18:49Z | [
"python",
"parsing",
"split",
"sscanf",
"procfs"
] | I'm looking for an equivalent to `sscanf()` in Python. I want to parse `/proc/net/*` files, in C I could do something like this:
```
int matches = sscanf(
buffer,
"%*d: %64[0-9A-Fa-f]:%X %64[0-9A-Fa-f]:%X %*X %*X:%*X %*X:%*X %*X %*d %*d %ld %*512s\n",
local_addr, &local_port, rem_addr, &rem_por... | There is also the [`parse`](http://pypi.python.org/pypi/parse) module.
`parse()` is designed to be the opposite of `format()` (the newer string formatting function in Python 2.6 and higher). |
Selecting distinct column values in SQLAlchemy/Elixir | 2,175,355 | 22 | 2010-02-01T08:05:09Z | 2,175,393 | 43 | 2010-02-01T08:17:32Z | [
"python",
"sql",
"sqlalchemy",
"python-elixir"
] | In a little script I'm writing using SQLAlchemy and Elixir, I need to get all the distinct values for a particular column. In ordinary SQL it'd be a simple matter of
```
SELECT DISTINCT `column` FROM `table`;
```
and I know I could just run that query "manually," but I'd rather stick to the SQLAlchemy declarative syn... | You can query column properties of mapped classes and the Query class has a generative `distinct()` method:
```
for value in Session.query(Table.column).distinct():
pass
``` |
What are the downsides of using Python instead of Objective-C? | 2,175,573 | 14 | 2010-02-01T09:01:26Z | 2,175,805 | 18 | 2010-02-01T09:53:42Z | [
"python",
"cocoa",
"osx",
"pyobjc"
] | I know some Python and I'm really impressed by the language's ease of use. From what I've seen of Objective-C it looks a lot less pretty, but it seems to be the *lingua franca* for Mac OS X development (which means it has better documentation).
I'm thinking about starting Mac development - will using PyObjC+Python mak... | This really says it all:
> As the maintainer of PyObjC for nearly
> 15 years, I will say it bluntly. Use
> Objective-C. You will need to know
> Objective-C to really understand Cocoa
> anyway and PyObjC is just going to add
> a layer of bugs & issues that are
> alien to 99% of Cocoa programmers.
a comment in an answe... |
What are the downsides of using Python instead of Objective-C? | 2,175,573 | 14 | 2010-02-01T09:01:26Z | 2,175,930 | 36 | 2010-02-01T10:21:28Z | [
"python",
"cocoa",
"osx",
"pyobjc"
] | I know some Python and I'm really impressed by the language's ease of use. From what I've seen of Objective-C it looks a lot less pretty, but it seems to be the *lingua franca* for Mac OS X development (which means it has better documentation).
I'm thinking about starting Mac development - will using PyObjC+Python mak... | Yes.
For one thing, as you note, all the documentation is written for Objective-C, which is a very different language.
One difference is method name. In Objective-C, when you send a message to (Python would say âcall a method ofâ) an object, the method name (selector) and arguments are mixed:
```
NSURL *URL = /*... |
Can Django ORM do an ORDER BY on a specific value of a column? | 2,176,346 | 13 | 2010-02-01T11:37:39Z | 2,176,471 | 17 | 2010-02-01T12:08:41Z | [
"python",
"mysql",
"django",
"orm"
] | I have a table 'tickets' with the following columns
* id - primary key - auto increment
* title - varchar(256)
* status - smallint(6) - Can have any value between 1 and 5, handled by Django
When I'll do a `SELECT *` I want the rows with `status = 4` at the top, the other records will follow them. It can be achieved b... | ```
q = Ticket.objects.extra(select={'is_top': "status = 4"})
q = q.extra(order_by = ['-is_top'])
``` |
Hiding axis text in matplotlib plots | 2,176,424 | 137 | 2010-02-01T11:56:52Z | 2,176,591 | 204 | 2010-02-01T12:34:02Z | [
"python",
"matplotlib",
"plot"
] | I'm trying to plot a figure without tickmarks or numbers on either of the axes (I use axes in the traditional sense, not the matplotlib nomenclature!). An issue I have come across is where matplotlib adjusts the x(y)ticklabels by subtracting a value N, then adds N at the end of the axis.
This may be vague, but the fol... | Instead of hiding each element, you can hide the whole axis:
```
frame1.axes.get_xaxis().set_visible(False)
frame1.axes.get_yaxis().set_visible(False)
```
Or, you can set the ticks to an empty list:
```
frame1.axes.get_xaxis().set_ticks([])
frame1.axes.get_yaxis().set_ticks([])
```
In this second option, you can st... |
Hiding axis text in matplotlib plots | 2,176,424 | 137 | 2010-02-01T11:56:52Z | 16,758,931 | 94 | 2013-05-26T11:48:34Z | [
"python",
"matplotlib",
"plot"
] | I'm trying to plot a figure without tickmarks or numbers on either of the axes (I use axes in the traditional sense, not the matplotlib nomenclature!). An issue I have come across is where matplotlib adjusts the x(y)ticklabels by subtracting a value N, then adds N at the end of the axis.
This may be vague, but the fol... | If you want to hide just the axis text keeping the grid lines:
```
frame1.axes.xaxis.set_ticklabels([])
frame1.axes.yaxis.set_ticklabels([])
```
Doing `set_visible(False)` or `set_ticks([])` will also hide the grid lines. |
Hiding axis text in matplotlib plots | 2,176,424 | 137 | 2010-02-01T11:56:52Z | 28,198,278 | 22 | 2015-01-28T17:11:18Z | [
"python",
"matplotlib",
"plot"
] | I'm trying to plot a figure without tickmarks or numbers on either of the axes (I use axes in the traditional sense, not the matplotlib nomenclature!). An issue I have come across is where matplotlib adjusts the x(y)ticklabels by subtracting a value N, then adds N at the end of the axis.
This may be vague, but the fol... | Somewhat of an old thread but, this seems to be a faster method using the latest version of matplotlib:
set the major formatter for the x-axis
```
ax.xaxis.set_major_formatter(plt.NullFormatter())
``` |
How do I convert a string to a buffer in Python 3.1? | 2,176,511 | 9 | 2010-02-01T12:17:21Z | 2,177,392 | 10 | 2010-02-01T14:38:16Z | [
"python",
"python-3.x"
] | I am attempting to pipe something to a `subprocess` using the following line:
```
p.communicate("insert into egg values ('egg');");
TypeError: must be bytes or buffer, not str
```
How can I convert the string to a buffer? | The correct answer is:
```
p.communicate(b"insert into egg values ('egg');");
```
Note the leading b, telling you that it's a string of bytes, not a string of unicode characters. Also, if you are reading this from a file:
```
value = open('thefile', 'rt').read()
p.communicate(value);
```
The change that to:
```
va... |
Individually labeled bars for bar graphs in matplotlib / Python | 2,177,504 | 11 | 2010-02-01T14:55:14Z | 2,177,537 | 24 | 2010-02-01T15:00:58Z | [
"python",
"label",
"plot",
"matplotlib",
"histogram"
] | I am trying to create bar graphs of letter frequency in Python. I thought the best way to accomplish this would be matplotlib, but I have been unable to decipher the documentation. Is it possible to label the bars of a matplotlib.pyplot.hist plot with one letter per bar, instead of a numerical axis? I think it must be,... | Sure is! You just need to reset the tick labels.
EDIT with answer and picture (can be done similarly with `hist`):
```
x = scipy.arange(4)
y = scipy.array([4,7,6,5])
f = pylab.figure()
ax = f.add_axes([0.1, 0.1, 0.8, 0.8])
ax.bar(x, y, align='center')
ax.set_xticks(x)
ax.set_xticklabels(['Aye', 'Bee', 'Cee', 'Dee'])
... |
Python: How do I disallow imports of a class from a module? | 2,177,817 | 2 | 2010-02-01T15:37:08Z | 2,177,890 | 9 | 2010-02-01T15:46:36Z | [
"python",
"import",
"python-module",
"python-import"
] | I tried:
```
__all__ = ['SpamPublicClass']
```
But, of course that's just for:
```
from spammodule import *
```
Is there a way to block importing of a class. I'm worried about confusion on the API level of my code that somebody will write:
```
from spammodule import SimilarSpamClass
```
and it'll cause debugging ... | The convention is to use a \_ as a prefix:
```
class PublicClass(object):
pass
class _PrivateClass(object):
pass
```
The following:
```
from module import *
```
Will not import the \_PrivateClass.
But this will not prevent them from importing it. They could still import it explicitly.
```
from module imp... |
In python, sorting on date field, field may sometimes be null | 2,178,931 | 16 | 2010-02-01T18:09:17Z | 2,178,976 | 9 | 2010-02-01T18:16:10Z | [
"python",
"sorting"
] | I am having a hard time coming up with a slick way to handle this sort. I have data coming back from a database read. I want to sort on the accoutingdate. However, accoutingdate may sometimes be null. I am currently doing the following:
```
results = sorted(results, key=operator.itemgetter('accountingdate'), reverse=T... | You could use a custom sorting function that treats `None` specially:
```
def nonecmp(a, b):
if a is None and b is None:
return 0
if a is None:
return -1
if b is None:
return 1
return cmp(a, b)
results = sorted(results, cmp=nonecmp, ...)
```
This treats `None` as being smaller than all datetime o... |
In python, sorting on date field, field may sometimes be null | 2,178,931 | 16 | 2010-02-01T18:09:17Z | 2,179,053 | 23 | 2010-02-01T18:26:52Z | [
"python",
"sorting"
] | I am having a hard time coming up with a slick way to handle this sort. I have data coming back from a database read. I want to sort on the accoutingdate. However, accoutingdate may sometimes be null. I am currently doing the following:
```
results = sorted(results, key=operator.itemgetter('accountingdate'), reverse=T... | Using a `key=` function is definitely right, you just have to decide how you want to treat the `None` values -- pick a `datetime` value that you want to treat as the equivalent of `None` for sorting purposes. E.g.:
```
import datetime
mindate = datetime.date(datetime.MINYEAR, 1, 1)
def getaccountingdate(x):
return ... |
Enable Unicode "globally" in Python | 2,179,253 | 2 | 2010-02-01T18:57:42Z | 2,179,350 | 8 | 2010-02-01T19:11:59Z | [
"python",
"unicode"
] | is it possible to avoid having to put this in every page?
```
# -*- coding: utf-8 -*-
```
I'd really like Python to default to this. Thanks in advance! | In Python 3, the default encoding is UTF-8, so you won't need to set it explicitly anymore. There isn't a way to 'globally' set the default source encoding, though, and history has shown that such global options are generally a bad idea. (For instance, the -U and -Q options to Python, and sys.setdefaultencoding() back ... |
Python method to boost function | 2,179,345 | 5 | 2010-02-01T19:11:19Z | 2,181,710 | 10 | 2010-02-02T03:27:30Z | [
"c++",
"python",
"boost",
"boost-python"
] | I have a method exported to Python using boost python that takes a boost::function as an argument.
From what I have read boost::python should support boost::function without much fuss, but when I try to call the function with a python method it gives me this error
```
Boost.Python.ArgumentError: Python argument types... | Got an answer on the python mailing list, and after a bit of reworking and more research I got exactly what I wanted :)
I did see that post before mithrandi but I did not like the idea of having to declare the functions like that. With some fancy wrappers and a bit of python magic this can work and look good at the sa... |
Misleading(?) TypeError when passing keyword arguments to function defined with positional arguments | 2,179,703 | 7 | 2010-02-01T20:10:31Z | 2,179,795 | 13 | 2010-02-01T20:24:08Z | [
"python",
"arguments"
] | In cPython 2.4:
```
def f(a,b,c,d):
pass
>>> f(b=1,c=1,d=1)
TypeError: f() takes exactly 4 non-keyword arguments (0 given)
```
but:
```
>>> f(a=1,b=1,c=1)
TypeError: f() takes exactly 4 non-keyword arguments (3 given)
```
Clearly, I don't **really really** understand Python's function-argument processing mecha... | When you say
```
def f(a,b,c,d):
```
you are telling python that `f` takes 4 *positional* arguments. Every time you call `f` it must be given exactly 4 arguments, and the first value will be assigned to `a`, the second to `b`, etc.
You are allowed to call `f` with something like
`f(1,2,3,4)` or `f(a=1,b=2,c=3,d=4)`... |
Python: use mysqldb to import a MySQL table as a dictionary? | 2,180,226 | 20 | 2010-02-01T21:31:18Z | 2,180,257 | 46 | 2010-02-01T21:37:06Z | [
"python",
"mysql"
] | Anyone know how I can use mysqldb to turn a MySQL table, with lots of rows, into a list of dictionary objects in Python?
I mean turning a set of MySQL rows, with columns 'a', 'b', and 'c', into a Python object that that looks like this:
```
data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 }, { 'a':'Q', 'b':(1, 4), 'c':5.0 }, ... | MySQLdb has a separate cursor class for this, the DictCursor. You can pass the cursor class you want to use to MySQLdb.connect():
```
import MySQLdb.cursors
MySQLdb.connect(host='...', cursorclass=MySQLdb.cursors.DictCursor)
``` |
Does the Jinja2 templating language have the concept of 'here' (current directory)? | 2,180,247 | 14 | 2010-02-01T21:34:10Z | 2,180,584 | 26 | 2010-02-01T22:38:46Z | [
"python",
"jinja2"
] | Does Jinja2 support template-relative paths e.g. `%(here)s/other/template.html`, to include other templates relative to the current template's place in the filesystem? | I do not believe so. Typically you include or extend other templates by specifying their paths relative to the root of whatever template loader and environment you're using.
So let's say your templates are all in `/path/to/templates` and you've set up Jinja like so:
```
import jinja2
template_dir = '/path/to/template... |
Does the Jinja2 templating language have the concept of 'here' (current directory)? | 2,180,247 | 14 | 2010-02-01T21:34:10Z | 9,763,688 | 9 | 2012-03-19T00:42:56Z | [
"python",
"jinja2"
] | Does Jinja2 support template-relative paths e.g. `%(here)s/other/template.html`, to include other templates relative to the current template's place in the filesystem? | Just to add to Will McCutchen's answer,
You can have multiple directories in your loader. It then searches in each of the directories (in order) until it finds the template.
for example, if you wanted to have "sidebar.html" instead of "/includes/sidebar.html" then have:
```
loader=jinja2.FileSystemLoader(
[o... |
Range of python's random.random() from the standard library | 2,180,299 | 13 | 2010-02-01T21:45:26Z | 2,180,314 | 10 | 2010-02-01T21:48:09Z | [
"python",
"random"
] | Does python's random.random() ever return 1.0 or does it only return up until 0.9999..? | Python's [`random.random`](http://docs.python.org/library/random.html) function returns numbers that are less than, but not equal to, `1`.
However, it can return `0`. |
Range of python's random.random() from the standard library | 2,180,299 | 13 | 2010-02-01T21:45:26Z | 2,180,324 | 18 | 2010-02-01T21:49:26Z | [
"python",
"random"
] | Does python's random.random() ever return 1.0 or does it only return up until 0.9999..? | Docs are here: <http://docs.python.org/library/random.html>
> ...random(), which
> generates a random float uniformly in
> the semi-open range [0.0, 1.0).
So, the return value will be greater than or equal to 0, and less than 1.0. |
Range of python's random.random() from the standard library | 2,180,299 | 13 | 2010-02-01T21:45:26Z | 2,180,332 | 31 | 2010-02-01T21:50:41Z | [
"python",
"random"
] | Does python's random.random() ever return 1.0 or does it only return up until 0.9999..? | ```
>>> help(random.random)
Help on built-in function random:
random(...)
random() -> x in the interval [0, 1).
```
That means 1 is excluded. |
Range of python's random.random() from the standard library | 2,180,299 | 13 | 2010-02-01T21:45:26Z | 18,429,518 | 11 | 2013-08-25T13:32:50Z | [
"python",
"random"
] | Does python's random.random() ever return 1.0 or does it only return up until 0.9999..? | The other answers already clarified that 1 is not included in the range, but out of curiosity, I decided to look at the source to see precisely how it is calculated.
The CPython source can be found [here](http://hg.python.org/cpython/file/8eac75276e5b/Modules/_randommodule.c)
```
/* random_random is the function name... |
Using Django database layer outside of Django? | 2,180,415 | 39 | 2010-02-01T22:05:31Z | 2,180,431 | 39 | 2010-02-01T22:08:14Z | [
"python",
"mysql",
"django"
] | I've got a nice database I've created in Django, and I'd like to interface with through some python scripts *outside* of my website stuff, so I'm curious if it's possible to use the Django database API outside of a Django site, and if so does anyone have any info on how it can be done? Google hasn't yielded many hits f... | You just need to configure the Django settings before you do any calls, including importing your models. Something like this:
```
from django.conf import settings
settings.configure(
DATABASE_ENGINE = 'postgresql_psycopg2',
DATABASE_NAME = 'db_name',
DATABASE_USER = 'db_user',
DATABASE_PASSWORD = 'db_p... |
Using Django database layer outside of Django? | 2,180,415 | 39 | 2010-02-01T22:05:31Z | 2,180,485 | 13 | 2010-02-01T22:19:03Z | [
"python",
"mysql",
"django"
] | I've got a nice database I've created in Django, and I'd like to interface with through some python scripts *outside* of my website stuff, so I'm curious if it's possible to use the Django database API outside of a Django site, and if so does anyone have any info on how it can be done? Google hasn't yielded many hits f... | **Update** setup\_environ is to be removed in django 1.6
If you're able to import your settings.py file, then [take a look](http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/) at handy setup\_environ command.
```
from django.core.management import setup_environ
from mysite import settings
setup_envi... |
Using Django database layer outside of Django? | 2,180,415 | 39 | 2010-02-01T22:05:31Z | 26,633,359 | 9 | 2014-10-29T14:45:03Z | [
"python",
"mysql",
"django"
] | I've got a nice database I've created in Django, and I'd like to interface with through some python scripts *outside* of my website stuff, so I'm curious if it's possible to use the Django database API outside of a Django site, and if so does anyone have any info on how it can be done? Google hasn't yielded many hits f... | For django 1.7, I used the following to get up and running.
**settings.py:**
```
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'name',
'USER': 'usr',
'PASSWORD': 'sec... |
Is it OK to raise a built-in exception, but with a different message, in Python? | 2,180,577 | 16 | 2010-02-01T22:36:15Z | 2,180,803 | 17 | 2010-02-01T23:20:23Z | [
"python",
"exception",
"raise",
"built-in"
] | Is it OK to raise a [built-in exception](http://docs.python.org/library/exceptions.html) with a custom text? or to raise a [built-in warning](http://docs.python.org/library/warnings.html#warning-categories) also with custom text?
The documentation reads:
> exception ValueError: Raised when a built-in operation or fun... | There's nothing operationally wrong with doing something like:
```
raise ValueError("invalid input encoding")
```
In fact, I do that quite often when I'm writing the first pass of some code. The main problem with doing it that way is that clients of your code have a hard time being precise in their exception handling... |
Really weird issue with shelve (python) | 2,180,946 | 5 | 2010-02-01T23:52:23Z | 2,181,095 | 10 | 2010-02-02T00:28:08Z | [
"python",
"shelve"
] | I create a file called `foo_module.py` containing the following code:
```
import shelve, whichdb, os
from foo_package.g import g
g.shelf = shelve.open("foo_path")
g.shelf.close()
print whichdb.whichdb("foo_path") # => dbhash
os.remove("foo_path")
```
Next to that file I create a directory called `foo_package` th... | I think you've hit a minor bug in 2.6.4's code related to the cleanup at end of program. If you run `python -v` you can see exactly at what point of the cleanup the error comes:
```
# cleanup[1] foo_package.g
Exception TypeError: "'NoneType' object is not callable" in ignored
```
Python sets references to `None` dur... |
Really weird issue with shelve (python) | 2,180,946 | 5 | 2010-02-01T23:52:23Z | 2,978,282 | 8 | 2010-06-04T22:50:27Z | [
"python",
"shelve"
] | I create a file called `foo_module.py` containing the following code:
```
import shelve, whichdb, os
from foo_package.g import g
g.shelf = shelve.open("foo_path")
g.shelf.close()
print whichdb.whichdb("foo_path") # => dbhash
os.remove("foo_path")
```
Next to that file I create a directory called `foo_package` th... | After days of hair loss, I finally had success using an atexit function:
```
import atexit
...
cache = shelve.open(path)
atexit.register(cache.close)
```
It's most appropriate to register right after opening. This works with multiple concurrent shelves.
(python 2.6.5 on lucid) |
How do I extend the Django Group model? | 2,181,039 | 18 | 2010-02-02T00:17:16Z | 2,182,418 | 12 | 2010-02-02T07:16:54Z | [
"python",
"django",
"django-models"
] | Is there a way to extend the built-in Django Group object to add additional attributes similar to the way you can extend a user object? With a user object, you can do the following:
```
class UserProfile(models.Model):
user = models.OneToOneField(User)
```
and add the following to the settings.py file
```
AUTH_P... | You can create a model that subclasses Group, add your own fields, and use a Model Manager to return any custom querysets you need. Here's a truncated example showing I extended Group to represent Families associated with a school:
```
from django.contrib.auth.models import Group, User
class FamilyManager(models.Mana... |
How do I extend the Django Group model? | 2,181,039 | 18 | 2010-02-02T00:17:16Z | 7,669,063 | 24 | 2011-10-05T23:52:00Z | [
"python",
"django",
"django-models"
] | Is there a way to extend the built-in Django Group object to add additional attributes similar to the way you can extend a user object? With a user object, you can do the following:
```
class UserProfile(models.Model):
user = models.OneToOneField(User)
```
and add the following to the settings.py file
```
AUTH_P... | If you simply subclass the Group object then by default it will create a new database table and the admin site won't pick up any new fields.
You need to inject new fields into the existing Group:
```
if not hasattr(Group, 'parent'):
field = models.ForeignKey(Group, blank=True, null=True, related_name='children')
... |
How to access url hash/fragment from a Django Request object | 2,181,186 | 18 | 2010-02-02T00:47:37Z | 2,181,192 | 29 | 2010-02-02T00:50:46Z | [
"python",
"django",
"hash",
"django-urls",
"fragment-identifier"
] | As in the title: how can I access the url hash/fragment (the part following the dash `#`) from a Django view and so, I suppose, from a Django Request object?
I've not found enough information on the documentation here available: <http://docs.djangoproject.com/en/dev/ref/request-response/>
P.S.
Suppose that the fragme... | This is not sent to the server, by definition. From [URI References: Fragment Identifiers on URIs](http://www.w3.org/DesignIssues/Fragment.html) :
> "The HTTP engine cannot make any assumptions about it. The server is not even given it." |
Multiprocessing and niceness value | 2,181,209 | 9 | 2010-02-02T00:54:25Z | 2,181,704 | 12 | 2010-02-02T03:26:10Z | [
"python",
"multiprocessing"
] | Does anyone know of an easy way to set the niceness value of a Process or Pool when it is created in multiprocessing? | ```
os.nice(increment)
Add increment to the processâs ânicenessâ. Return the new niceness. Availability: Unix.
```
From <http://docs.python.org/library/os.html#os.nice>.
Is there a reason you can't call this in the child process? |
Using the Image.point() method in PIL to manipulate pixel data | 2,181,292 | 17 | 2010-02-02T01:12:33Z | 2,181,365 | 14 | 2010-02-02T01:33:43Z | [
"python",
"image",
"image-processing",
"image-manipulation",
"python-imaging-library"
] | I am using the [Python Imaging Library](http://www.pythonware.com/products/pil/) to colorize a black and white image with a lookup table that defines the color relationships. The lookup table is simply a 256-element list of RGB tuples:
```
>>> len(colors)
256
>>> colors[0]
(255, 237, 237)
>>> colors[127]
(50, 196, 33)... | > Is Image.point() the right tool for
> this job?
Yes indeed, `Image.point()` is perfect for this job
> What format/structure does
> Image.point() expect the table?
You should flatten the list so instead of `[(12, 140, 10), (10, 100, 200), ...]` use:
```
[12, 140, 10, 10, 100, 200, ...]
```
Here is a quick example... |
How do I reply to an email using the Python imaplib and include the original message? | 2,182,196 | 13 | 2010-02-02T06:10:02Z | 2,189,630 | 14 | 2010-02-03T04:09:59Z | [
"python",
"django",
"email",
"mime",
"imaplib"
] | I'm currently using [`imaplib`](http://docs.python.org/library/imaplib.html) to fetch email messages from a server and process the contents and attachments.
I'd like to reply to the messages with a status/error message and links to the resulting generated content on my site if they can be processed. This should includ... | The original MIME tree structure of the incoming message is as follows (using `email.iterators._structure(msg)`):
```
multipart/mixed
text/html (message)
application/octet-stream (attachment 1)
application/octet-stream (attachment 2)
```
Replying via GMail results in the following structure... |
How can I pack several decorators into one? | 2,182,858 | 10 | 2010-02-02T09:04:37Z | 2,182,876 | 11 | 2010-02-02T09:08:10Z | [
"python",
"decorator"
] | I have several decorators on each function, is there a way to pack them in to one instead?
```
@fun1
@fun2
@fun3
def do_stuf():
pass
```
change to:
```
@all_funs #runs fun1 fun2 and fun3, how should all_funs look like?
def do_stuf():
pass
``` | A decorator is in principle only syntactic sugar for this:
```
def do_stuf():
pass
do_stuf = fun1(do_stuf)
```
So in your all\_fun, all you should need to do is to wrap the function in the same kind of chain of decorators:
```
def all_funs(funky):
return fun1(fun2(fun3(fun4(funky)))
```
Things get a little... |
How can I pack several decorators into one? | 2,182,858 | 10 | 2010-02-02T09:04:37Z | 2,183,445 | 7 | 2010-02-02T11:02:09Z | [
"python",
"decorator"
] | I have several decorators on each function, is there a way to pack them in to one instead?
```
@fun1
@fun2
@fun3
def do_stuf():
pass
```
change to:
```
@all_funs #runs fun1 fun2 and fun3, how should all_funs look like?
def do_stuf():
pass
``` | It's also possible to write a generic decorator that supports decorator chaining:
```
def fun1(f):
print "fun1"
return f
def fun2(f):
print "fun2"
return f
def fun3(f):
print "fun3"
return f
def chained(*dec_funs):
def _inner_chain(f):
for dec in reversed(dec_funs):
f... |
importing a module in nested packages | 2,183,205 | 12 | 2010-02-02T10:11:31Z | 2,183,325 | 9 | 2010-02-02T10:34:09Z | [
"python",
"import",
"package"
] | This is a python newbie question:
I have the following directory structure:
```
test
-- test_file.py
a
-- b
-- module.py
```
where `test`, `a` and `b` are folders. Both `test` and `a` are on the same level.
module.py has a class called `shape`, and I want to instantiate an instance of it in test\_file.py. How ... | What you want is a relative import like:
`from ..a.b import module`
The problem with this is that it doesn't work if you are calling test\_file.py as your main module. As stated [here](http://docs.python.org/tutorial/modules.html):
> Note that both explicit and implicit relative imports are based on the name of the ... |
importing a module in nested packages | 2,183,205 | 12 | 2010-02-02T10:11:31Z | 2,183,484 | 8 | 2010-02-02T11:10:02Z | [
"python",
"import",
"package"
] | This is a python newbie question:
I have the following directory structure:
```
test
-- test_file.py
a
-- b
-- module.py
```
where `test`, `a` and `b` are folders. Both `test` and `a` are on the same level.
module.py has a class called `shape`, and I want to instantiate an instance of it in test\_file.py. How ... | 1. The directory `a` needs to be a package. Add an `__init__.py` file to make it a package, which is a step up from being a simple directory.
2. The directory `b` also needs to be a subpackage of `a`. Add an `__init__.py` file.
3. The directory `test` should probably also be a package. Hard to say if this is necessary ... |
How to add a custom loglevel to Python's logging facility | 2,183,233 | 42 | 2010-02-02T10:16:03Z | 2,183,293 | 7 | 2010-02-02T10:27:50Z | [
"python",
"logging"
] | I'd like to have loglevel TRACE (5) for my application, as I don't think that `debug()` is sufficient. Additionally `log(5, msg)` isn't what I want. How can I add a custom loglevel to a Python logger?
I've a `mylogger.py` with the following content:
```
import logging
@property
def log(obj):
myLogger = logging.g... | I think you'll have to subclass the `Logger` class and add a method called `trace` which basically calls `Logger.log` with a level lower than `DEBUG`. I haven't tried this but this is what the [docs indicate](http://docs.python.org/library/logging.html#loggers). |
How to add a custom loglevel to Python's logging facility | 2,183,233 | 42 | 2010-02-02T10:16:03Z | 2,819,062 | 8 | 2010-05-12T13:13:41Z | [
"python",
"logging"
] | I'd like to have loglevel TRACE (5) for my application, as I don't think that `debug()` is sufficient. Additionally `log(5, msg)` isn't what I want. How can I add a custom loglevel to a Python logger?
I've a `mylogger.py` with the following content:
```
import logging
@property
def log(obj):
myLogger = logging.g... | I find it easier to create a new attribute for the logger object that passes the log() function. I think the logger module provides the addLevelName() and the log() for this very reason. Thus no subclasses or new method needed.
```
import logging
@property
def log(obj):
logging.addLevelName(5, 'TRACE')
myLogg... |
How to add a custom loglevel to Python's logging facility | 2,183,233 | 42 | 2010-02-02T10:16:03Z | 11,784,984 | 40 | 2012-08-02T20:08:51Z | [
"python",
"logging"
] | I'd like to have loglevel TRACE (5) for my application, as I don't think that `debug()` is sufficient. Additionally `log(5, msg)` isn't what I want. How can I add a custom loglevel to a Python logger?
I've a `mylogger.py` with the following content:
```
import logging
@property
def log(obj):
myLogger = logging.g... | I took the "avoid seeing lambda" answer and had to modify where the log\_at\_my\_log\_level was being added. I too saw the problem that Paul did "I don't think this works. Don't you need logger as the first arg in log\_at\_my\_log\_level?" This worked for me
```
import logging
DEBUG_LEVELV_NUM = 9
logging.addLevelNam... |
How to add a custom loglevel to Python's logging facility | 2,183,233 | 42 | 2010-02-02T10:16:03Z | 13,638,084 | 76 | 2012-11-30T02:17:06Z | [
"python",
"logging"
] | I'd like to have loglevel TRACE (5) for my application, as I don't think that `debug()` is sufficient. Additionally `log(5, msg)` isn't what I want. How can I add a custom loglevel to a Python logger?
I've a `mylogger.py` with the following content:
```
import logging
@property
def log(obj):
myLogger = logging.g... | @Eric S.
Eric S.'s answer is excellent, but I learned by experimentation that this will always cause messages logged at the new debug level to be printed -- regardless of what the log level is set to. So if you make a new level number of 9, if you call setLevel(50), the lower level messages will erroneously be printed... |
How to add a custom loglevel to Python's logging facility | 2,183,233 | 42 | 2010-02-02T10:16:03Z | 16,955,098 | 14 | 2013-06-06T06:27:25Z | [
"python",
"logging"
] | I'd like to have loglevel TRACE (5) for my application, as I don't think that `debug()` is sufficient. Additionally `log(5, msg)` isn't what I want. How can I add a custom loglevel to a Python logger?
I've a `mylogger.py` with the following content:
```
import logging
@property
def log(obj):
myLogger = logging.g... | Who started the bad practice of using internal methods (`self._log`) and why is each answer based on that?! The pythonic solution would be to use `self.log` instead so you don't have to mess with any internal stuff:
```
import logging
SUBDEBUG = 5
logging.addLevelName(SUBDEBUG, 'SUBDEBUG')
def subdebug(self, message... |
How to add a custom loglevel to Python's logging facility | 2,183,233 | 42 | 2010-02-02T10:16:03Z | 22,586,200 | 13 | 2014-03-23T02:07:19Z | [
"python",
"logging"
] | I'd like to have loglevel TRACE (5) for my application, as I don't think that `debug()` is sufficient. Additionally `log(5, msg)` isn't what I want. How can I add a custom loglevel to a Python logger?
I've a `mylogger.py` with the following content:
```
import logging
@property
def log(obj):
myLogger = logging.g... | This question is rather old, but I just dealt with the same topic and found a way similiar to those already mentioned which appears a little cleaner to me. This was tested on 3.4, so I'm not sure whether the methods used exist in older versions:
```
from logging import getLoggerClass, addLevelName, setLoggerClass, NOT... |
EventHandler, event, delegate based programming in Python any example would appreciate? | 2,184,263 | 10 | 2010-02-02T13:19:07Z | 2,184,282 | 15 | 2010-02-02T13:23:25Z | [
"python",
"events",
"delegates",
"function-pointers",
"event-handling"
] | Basically I'm a C# developer,
I know the way C# does, EventHandler, delegate, even...
but whats the best way to implement it on Python. | I think you should be able to use a function:
```
def do_work_and_notify(on_done):
// do work
on_done()
def send_email_on_completion():
email_send('joe@example.com', 'you are done')
do_work_and_notify(send_email_on_completion)
```
Functions (and even methods) in python are first-class objects that can b... |
Python Leave Loop Early | 2,184,287 | 18 | 2010-02-02T13:23:46Z | 2,184,291 | 30 | 2010-02-02T13:25:04Z | [
"python",
"loops"
] | How do I leave a loop early in python?
```
for a in b:
if criteria in list1:
print "oh no"
#Force loop i.e. force next iteration without going on
someList.append(a)
```
Also, in java you can `break` out of a loop, is there an equivalent in Python? | `continue` and `break` is what you want. Python works identically to Java/C++ in this regard. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.