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 |
|---|---|---|---|---|---|---|---|---|---|
How does Django's ORM manage to fetch Foreign objects when they are accessed | 3,597,762 | 23 | 2010-08-30T03:55:09Z | 3,597,996 | 51 | 2010-08-30T05:06:04Z | [
"python",
"django",
"orm"
] | Been trying to figure this out for a couple of hours now and have gotten nowhere.
```
class other(models.Model):
user = models.ForeignKey(User)
others = other.objects.all()
o = others[0]
```
At this point the ORM has not asked for the o.user object, but if I do ANYTHING that touches that object, it loads it fro... | Django uses a [metaclass](http://docs.python.org/reference/datamodel.html#customizing-class-creation) ([`django.db.models.base.ModelBase`](http://code.djangoproject.com/browser/django/trunk/django/db/models/base.py#L22)) to customize the creation of model classes. For each object defined as a class attribute on the mod... |
Reasoning behind `from ... import ...` syntax in Python | 3,600,352 | 12 | 2010-08-30T12:38:05Z | 3,600,381 | 10 | 2010-08-30T12:41:22Z | [
"python",
"syntax",
"import"
] | I always wondered why the syntax for importing specific objects from a module is `from module import x, y, z` instead of `import x, y, z from module`. I'm not a native speaker, but isn't the latter more correct/natural?
So, what is the reason to put the from first? Is it merely to simplify the grammar (require less lo... | A very wild guess and probably totally non-sense, but I knew that syntax from [Modula-2](http://www.modula2.org/reference/modules.php) (man, that was twenty years ago, I feel old)... maybe Python was inspired by it ? |
Reasoning behind `from ... import ...` syntax in Python | 3,600,352 | 12 | 2010-08-30T12:38:05Z | 3,600,385 | 17 | 2010-08-30T12:41:46Z | [
"python",
"syntax",
"import"
] | I always wondered why the syntax for importing specific objects from a module is `from module import x, y, z` instead of `import x, y, z from module`. I'm not a native speaker, but isn't the latter more correct/natural?
So, what is the reason to put the from first? Is it merely to simplify the grammar (require less lo... | No idea why it was *actually* done that way but it's the way I'd do it, simply because, being an engineering type, it seems more natural to me to start from a general category and drill down to specifics.
It would also mean the parser would have to store less stuff if processing sequentially. With:
```
import x,y,z f... |
How to make it shorter (Pythonic)? | 3,600,834 | 8 | 2010-08-30T13:35:57Z | 3,600,855 | 35 | 2010-08-30T13:39:09Z | [
"python"
] | I have to check a lot of worlds if they are in string... code looks like:
```
if "string_1" in var_string or "string_2" in var_string or "string_3" in var_string or "string_n" in var_string:
do_something()
```
how to make it more readable and more clear? | This is one way:
```
words = ['string_1', 'string_2', ...]
if any(word in var_string for word in words):
do_something()
```
Reference: [`any()`](http://docs.python.org/library/functions.html#any)
**Update:**
For completeness, if you want to execute the function only if *all* words are contained in the string, ... |
How can I get the file size on the Internet knowing only the URL | 3,601,240 | 2 | 2010-08-30T14:25:26Z | 3,601,282 | 10 | 2010-08-30T14:30:39Z | [
"python",
"http",
"file",
"download"
] | I want to get the size of an http://.. file before I download it.
I don't know how to use http request.
Thanks! | The [HTTP `HEAD` method](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) was invented for scenarios like this (wanting to know data about a response without fetching the response itself). Provided the server returns a [Content-Length header](http://en.wikipedia.org/wiki/List_of_HTTP_header_fie... |
How can I get the file size on the Internet knowing only the URL | 3,601,240 | 2 | 2010-08-30T14:25:26Z | 3,601,360 | 7 | 2010-08-30T14:39:10Z | [
"python",
"http",
"file",
"download"
] | I want to get the size of an http://.. file before I download it.
I don't know how to use http request.
Thanks! | ```
import urllib2
f = urllib2.urlopen("http://your-url")
size= f.headers["Content-Length"]
print size
``` |
Python: 'Private' module in a package | 3,602,110 | 17 | 2010-08-30T16:07:43Z | 3,645,219 | 11 | 2010-09-05T06:30:42Z | [
"python",
"python-module"
] | I have a package `mypack` with modules `mod_a` and `mod_b` in it. I intend the the package itself and `mod_a` to be imported freely:
```
import mypack
import mypack.mod_a
```
However, I'd like to keep `mod_b` for the exclusive use of `mypack`. That's because it exists merely to organize the latter's internal code.
M... | The solution I've settled on is to create a sub-package 'private' and place all the modules I wish to hide in there. This way they stay stowed away, leaving `mypack`'s module list cleaner and easier to parse.
To me, this doesn't look unpythonic either. |
Python: 'Private' module in a package | 3,602,110 | 17 | 2010-08-30T16:07:43Z | 9,285,667 | 14 | 2012-02-14T23:17:27Z | [
"python",
"python-module"
] | I have a package `mypack` with modules `mod_a` and `mod_b` in it. I intend the the package itself and `mod_a` to be imported freely:
```
import mypack
import mypack.mod_a
```
However, I'd like to keep `mod_b` for the exclusive use of `mypack`. That's because it exists merely to organize the latter's internal code.
M... | I prefix private modules with an underscore to communicate the intent to the user. In your case, this would be `mypack._mod_b`
This is in the same spirit (but not completely analogous to) the PEP8 recommendation to name C-extension modules with a leading underscore when itâs wrapped by a Python module; i.e., `_socke... |
Prevent creating new attributes outside __init__ | 3,603,502 | 25 | 2010-08-30T19:20:36Z | 3,603,624 | 12 | 2010-08-30T19:38:39Z | [
"python",
"class"
] | I want to be able to create a class (in Python) that once initialized with `__init__`, does not accept new attributes, but accepts modifications of existing attributes. There's several hack-ish ways I can see to do this, for example having a `__setattr__` method such as
```
def __setattr__(self, attribute, value):
... | Actually, you don't want `__setattr__`, you want [`__slots__`](http://docs.python.org/reference/datamodel.html#slots). Add `__slots__ = ('foo', 'bar', 'baz')` to the class body, and Python will make sure that there's only foo, bar and baz on any instance. But read the caveats the documentation lists! |
Prevent creating new attributes outside __init__ | 3,603,502 | 25 | 2010-08-30T19:20:36Z | 3,603,824 | 35 | 2010-08-30T20:04:00Z | [
"python",
"class"
] | I want to be able to create a class (in Python) that once initialized with `__init__`, does not accept new attributes, but accepts modifications of existing attributes. There's several hack-ish ways I can see to do this, for example having a `__setattr__` method such as
```
def __setattr__(self, attribute, value):
... | I wouldn't use `__dict__` directly, but you can add a function to explicitly "freeze" a instance:
```
class FrozenClass(object):
__isfrozen = False
def __setattr__(self, key, value):
if self.__isfrozen and not hasattr(self, key):
raise TypeError( "%r is a frozen class" % self )
obje... |
Prevent creating new attributes outside __init__ | 3,603,502 | 25 | 2010-08-30T19:20:36Z | 29,368,642 | 12 | 2015-03-31T12:26:13Z | [
"python",
"class"
] | I want to be able to create a class (in Python) that once initialized with `__init__`, does not accept new attributes, but accepts modifications of existing attributes. There's several hack-ish ways I can see to do this, for example having a `__setattr__` method such as
```
def __setattr__(self, attribute, value):
... | If someone is interested in doing that with a decorator, here is a working solution:
```
from functools import wraps
def froze_it(cls):
cls.__frozen = False
def frozensetattr(self, key, value):
if self.__frozen and not hasattr(self, key):
print("Class {} is frozen. Cannot set {} = {}"
... |
What does it mean for an object to be picklable (or pickle-able)? | 3,603,581 | 28 | 2010-08-30T19:32:50Z | 3,603,621 | 23 | 2010-08-30T19:38:11Z | [
"python",
"pickle"
] | Python docs mention this word a lot and I want to know what it means! Googling doesn't help much.. | It simply means it can be serialized by the [`pickle`](http://docs.python.org/library/pickle.html) module. For a basic explanation of this, see [What can be pickled and unpickled?](http://docs.python.org/library/pickle.html#what-can-be-pickled-and-unpickled). [The pickle protocol](http://docs.python.org/library/pickle.... |
What does it mean for an object to be picklable (or pickle-able)? | 3,603,581 | 28 | 2010-08-30T19:32:50Z | 3,604,099 | 10 | 2010-08-30T20:44:22Z | [
"python",
"pickle"
] | Python docs mention this word a lot and I want to know what it means! Googling doesn't help much.. | Things that are usually not pickable are, for example, sockets, file(handler)s, database connections, and so on. Everything that's build up (recursively) from basic python types (dicts, lists, primitives, objects, object references, even circular) can be pickled by default.
You can implement custom pickling code that ... |
Regular expression matching anything greater than eight letters in length, in Python | 3,604,105 | 5 | 2010-08-30T20:45:21Z | 3,604,114 | 12 | 2010-08-30T20:47:43Z | [
"python",
"regex"
] | Despite attempts to master grep and related GNU software, I haven't come close to mastering regular expressions. I do like them, but I find them a bit of an eyesore all the same.
I suppose this question isn't difficult for some, but I've spent hours trying to figure out how to search through my favorite book for words... | You don't need regex for this.
```
result = [w for w in vocab if len(w) >= 8]
```
but if regex must be used:
```
rx = re.compile('^.{8,}$')
# ^^^^ {8,} means 8 or more.
result = [w for w in vocab if rx.match(w)]
```
See <http://www.regular-expressions.info/repeat.html> for detail on the `{a,b}` syn... |
Regular expression matching anything greater than eight letters in length, in Python | 3,604,105 | 5 | 2010-08-30T20:45:21Z | 3,604,135 | 9 | 2010-08-30T20:51:16Z | [
"python",
"regex"
] | Despite attempts to master grep and related GNU software, I haven't come close to mastering regular expressions. I do like them, but I find them a bit of an eyesore all the same.
I suppose this question isn't difficult for some, but I've spent hours trying to figure out how to search through my favorite book for words... | \w will match letter and characters, {min,[max]} allows you to define size. An expression like
```
\w{9,}
```
will give all letter/number combinations of 9 characters or more |
"None not in" vs "not None in" | 3,604,222 | 6 | 2010-08-30T21:05:15Z | 3,604,250 | 14 | 2010-08-30T21:09:33Z | [
"python",
"syntax",
"logic"
] | Unless I'm crazy `if None not in x` and `if not None in x` are equivalent. Is there a preferred version? I guess `None not in` is more english-y and therefore more pythonic, but `not None in` is more like other language syntax. Is there a preferred version? | They compile to the same bytecode, so yes they are equivalent.
```
>>> import dis
>>> dis.dis(lambda: None not in x)
1 0 LOAD_CONST 0 (None)
3 LOAD_GLOBAL 1 (x)
6 COMPARE_OP 7 (not in)
9 RETURN_VALUE
>>> dis.dis(lambda: not ... |
"None not in" vs "not None in" | 3,604,222 | 6 | 2010-08-30T21:05:15Z | 3,604,281 | 7 | 2010-08-30T21:14:32Z | [
"python",
"syntax",
"logic"
] | Unless I'm crazy `if None not in x` and `if not None in x` are equivalent. Is there a preferred version? I guess `None not in` is more english-y and therefore more pythonic, but `not None in` is more like other language syntax. Is there a preferred version? | The expression
```
not (None in x)
```
(parens added for clarity) is an ordinary boolean negation. However,
```
None not in x
```
is special syntax added for more readable code (there's no possibility here, nor does it make sense, to use and, or, etc in front of the in). If this special case was added, use it.
Sam... |
Does django with mongodb make migrations a thing of the past? | 3,604,565 | 13 | 2010-08-30T22:01:49Z | 3,612,110 | 13 | 2010-08-31T18:38:47Z | [
"python",
"django",
"mongodb"
] | Since mongo doesn't have a schema, does that mean that we won't have to do migrations when we change the models?
What does the migration process look like with a non-relational db? | I think this is a really good question, but the answers are going to be a little scattered based on the libs you're using and your expectations for a "migration".
Let's take a look at some common migration actions:
* **Add a field:** Mongo makes this very easy. Just add a field and you're done.
* **Delete a field:** ... |
How do I use string formatting to show BOTH leading zeros and precision of 3? | 3,604,587 | 12 | 2010-08-30T22:05:44Z | 3,604,609 | 25 | 2010-08-30T22:09:28Z | [
"python",
"string-formatting"
] | I'm trying to represent a number with leading and trailing zeros so that the total width is 7 including the decimal point. For example, I want to represent "5" as "005.000". It seems that string formatting will let me do one or the other but not both. Here's the output I get in Ipython illustrating my problem:
```
In ... | The first number is the **total** number of digits, including decimal point.
```
>>> '%07.3f' % 5
'005.000'
``` |
Creating a simple XML file using python | 3,605,680 | 61 | 2010-08-31T02:38:23Z | 3,605,831 | 123 | 2010-08-31T03:31:51Z | [
"python",
"xml"
] | What are my options if I want to create a simple XML file in python? (library wise)
The xml I want looks like:
```
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some vlaue2</field2>
</doc>
</root>
``` | These days, the most popular (and very simple) option is the ElementTree API, which has been included in the standard library since Python 2.5.
The available options for that are:
* ElementTree (Basic, pure-Python implementation of ElementTree. Part of the standard library since 2.5)
* cElementTree (Optimized C imple... |
Creating a simple XML file using python | 3,605,680 | 61 | 2010-08-31T02:38:23Z | 5,540,864 | 29 | 2011-04-04T15:36:47Z | [
"python",
"xml"
] | What are my options if I want to create a simple XML file in python? (library wise)
The xml I want looks like:
```
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some vlaue2</field2>
</doc>
</root>
``` | The [lxml library](http://lxml.de/) includes a very convenient syntax for XML generation, called the [E-factory](http://lxml.de/tutorial.html#the-e-factory). Here's how I'd make the example you give:
```
#!/usr/bin/python
import lxml.etree
import lxml.builder
E = lxml.builder.ElementMaker()
ROOT = E.root
DOC = E.... |
Constructing objects in __init__ | 3,605,766 | 2 | 2010-08-31T03:09:01Z | 3,605,821 | 8 | 2010-08-31T03:26:19Z | [
"python",
"constructor"
] | I've seen code that looks something like this:
```
class MyClass:
def __init__(self, someargs):
myObj = OtherClass()
myDict = {}
...code to setup myObj, myDict...
self.myObj = myObj
self.myDict = myDict
```
My first thought when I saw this was: Why not just use self.myObj a... | It's faster *and* more readable to construct the object and then attach it to `self`.
```
class Test1(object):
def __init__(self):
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
self.d = d
class Test2(object):
def __init__(self):
self.d = {}
self.d['a'] = 1
... |
How can I add a test method to a group of Django TestCase-derived classes? | 3,605,936 | 6 | 2010-08-31T03:59:51Z | 3,606,115 | 18 | 2010-08-31T04:50:03Z | [
"python",
"django",
"unit-testing",
"subclassing"
] | I have a group of test cases that all should have exactly the same test done, along the lines of "Does method x return the name of an existing file?"
I thought that the best way to do it would be a base class deriving from TestCase that they all share, and simply add the test to that class. Unfortunately, the testing ... | You could use a mixin by taking advantage that the test runner only runs tests inheriting from `unittest.TestCase` (which Django's `TestCase` inherits from.) For example:
```
class SharedTestMixin(object):
# This class will not be executed by the test runner (it inherits from object, not unittest.TestCase.
# I... |
Cumulative summation of a numpy array by index | 3,606,041 | 7 | 2010-08-31T04:32:13Z | 3,689,356 | 9 | 2010-09-11T01:00:49Z | [
"python",
"numpy",
"sum",
"indices"
] | Assume you have an array of values that will need to be summed together
```
d = [1,1,1,1,1]
```
and a second array specifying which elements need to be summed together
```
i = [0,0,1,2,2]
```
The result will be stored in a new array of size `max(i)+1`. So for example `i=[0,0,0,0,0]` would be equivalent to summing a... | If I understand the question correctly, there is a fast function for this (as long as the data array is 1d)
```
>>> i = np.array([0,0,1,2,2])
>>> d = np.array([0,1,2,3,4])
>>> np.bincount(i, weights=d)
array([ 1., 2., 7.])
```
np.bincount returns an array for all integers range(max(i)), even if some counts are zero |
How can I import a python module function dynamically? | 3,606,202 | 8 | 2010-08-31T05:15:55Z | 3,606,218 | 12 | 2010-08-31T05:19:06Z | [
"python",
"function",
"import",
"module"
] | Assuming def my\_function(): is located in my\_apps.views I would like to import "my\_function" dynamically without using something like exec or eval.
Is there anyway to accomplish this. I'm looking to do something similar to:
my\_function = import\_func("my\_apps.views.my\_function")
my\_function()
... code is exec... | you want
```
my_function = getattr(__import__('my_apps.views'), 'my_function')
```
If you happen to know the name of the function at compile time, you can shorten this to
```
my_function = __import__('my_apps.views').my_function
```
This will load `my_apps.views` and then assign its `my_function` attribute to the l... |
Removing python module installed in develop mode | 3,606,457 | 49 | 2010-08-31T06:13:54Z | 3,613,880 | 11 | 2010-08-31T23:10:08Z | [
"python",
"setuptools"
] | Hi I was trying the python packaging using setuptools and to test I installed the module in develop mode.
i.e
```
python setup.py develop
```
This has added my modules directory to sys.path. Now I want to remove the module is there any way to do this?
Thanks in advance | Edit easy-install.pth in your site-packages directory and remove the line that points to your development version of that package. |
Removing python module installed in develop mode | 3,606,457 | 49 | 2010-08-31T06:13:54Z | 3,623,868 | 150 | 2010-09-02T04:41:05Z | [
"python",
"setuptools"
] | Hi I was trying the python packaging using setuptools and to test I installed the module in develop mode.
i.e
```
python setup.py develop
```
This has added my modules directory to sys.path. Now I want to remove the module is there any way to do this?
Thanks in advance | Use the `--uninstall` or `-u` option to `develop`, i.e:
```
python setup.py develop --uninstall
```
This will remove it from easy-install.pth and delete the .egg-link. The only thing it doesn't do is delete scripts (yet). |
"no matching architecture in universal wrapper" problem in wxPython? | 3,606,964 | 12 | 2010-08-31T07:38:45Z | 3,607,451 | 9 | 2010-08-31T08:50:38Z | [
"python",
"wxpython",
"python-import"
] | I am running Python 2.7 under Mac OS 10.6.4, and I just installed wxPython from the `wxPython2.8-osx-unicode-2.8.11.0-universal-py2.7.dmg` binary. I am getting a weird error on the `import wx` line in my Python scripts. FYI, I can import the wx module just fine from PyCrust. I don't really see what I have done wrong he... | It appears that C extension modules included with the wxPython 2.7 dmg [here](http://www.wxpython.org/download.php) are 32-bit only.
```
$ cd /usr/local/lib/wxPython-unicode-2.8.11.0/lib/python2.7/site-packages/wx-2.8-mac-unicode/wx
$ file *.so
_animate.so: Mach-O universal binary with 2 architectures
_animate.so (f... |
Django pre_save signal: check if instance is created not updated, does kwargs['created'] (still) exist? | 3,607,573 | 15 | 2010-08-31T09:09:47Z | 3,607,652 | 16 | 2010-08-31T09:20:24Z | [
"python",
"django",
"kwargs"
] | I am using Django's pre\_save signal to implement auto\_now\_add. There is a lot of discussion on the internet on why you should or shouldn't implement it yourself. I do not appreciate comments on this. Neither on whether I should be rewriting the save function (I have a lot of models that use auto\_now\_add so using s... | According to the latest Django [documentation](http://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.pre_save), `pre_save` does NOT send a `created` argument. `Post_save` however [does](http://docs.djangoproject.com/en/dev/ref/signals/#post-save). I could not find any reference of the signal sendin... |
Django pre_save signal: check if instance is created not updated, does kwargs['created'] (still) exist? | 3,607,573 | 15 | 2010-08-31T09:09:47Z | 12,132,343 | 19 | 2012-08-26T17:32:50Z | [
"python",
"django",
"kwargs"
] | I am using Django's pre\_save signal to implement auto\_now\_add. There is a lot of discussion on the internet on why you should or shouldn't implement it yourself. I do not appreciate comments on this. Neither on whether I should be rewriting the save function (I have a lot of models that use auto\_now\_add so using s... | Primary key attribute usually assigned by the database when the instance saved first time. So you can use something like `if instance.pk is None` |
Python: How can I find all files with a particular extension? | 3,608,411 | 11 | 2010-08-31T11:13:15Z | 3,608,448 | 20 | 2010-08-31T11:17:14Z | [
"python"
] | I am trying to find all the `.c` files in a directory using Python.
I wrote this, but it is just returning me all files - not just `.c` files.
```
import os
import re
results = []
for folder in gamefolders:
for f in os.listdir(folder):
if re.search('.c', f):
results += [f]
print results
```... | Try "glob":
```
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
``` |
Python: How can I find all files with a particular extension? | 3,608,411 | 11 | 2010-08-31T11:13:15Z | 3,608,468 | 21 | 2010-08-31T11:19:12Z | [
"python"
] | I am trying to find all the `.c` files in a directory using Python.
I wrote this, but it is just returning me all files - not just `.c` files.
```
import os
import re
results = []
for folder in gamefolders:
for f in os.listdir(folder):
if re.search('.c', f):
results += [f]
print results
```... | try changing the inner loop to something like this
```
results += [each for each in os.listdir(folder) if each.endswith('.c')]
``` |
Smart way to find out string encoding? | 3,608,954 | 7 | 2010-08-31T12:23:13Z | 3,608,968 | 15 | 2010-08-31T12:24:48Z | [
"python",
"encoding",
"character-encoding"
] | I wonder whether it is possible to find what is the encoding of string? I know that it may be impossible for some strings (e.g. that do not have non-ASCII characters). Maybe it is possible to obtain a list of encodings that may be correct (possible) for a given string?
I'm looking for some other way than trying to dec... | [Chardet](http://pypi.python.org/pypi/chardet) does a educated guess. Read the FAQ before you use it! |
Python - Timeit within a class | 3,609,148 | 4 | 2010-08-31T12:46:38Z | 3,609,600 | 9 | 2010-08-31T13:46:56Z | [
"python",
"self",
"timeit"
] | I'm having some real trouble with timing a function from within an instance of a class. I'm not sure I'm going about it the right way (never used timeIt before) and I tried a few variations of the second argument importing things, but no luck. Here's a silly example of what I'm doing:
```
import timeit
class TimedCla... | Why do you want the timing inside the class being timed itself? If you take the timing out of the class, you can just pass a reference. I.e.
```
import timeit
class TimedClass():
def __init__(self):
self.x = 13
self.y = 15
def square(self, _x, _y):
print _x**_y
myTimedClass = TimedCl... |
Skip python "import" statements in exuberant ctags | 3,609,433 | 17 | 2010-08-31T13:25:09Z | 3,670,061 | 36 | 2010-09-08T16:52:04Z | [
"python",
"vim",
"exuberant-ctags"
] | if I have two files
file a.py:
```
class A():
pass
```
file b.py:
```
from a import A
b = A()
```
When I use ctags and press Ctrl+] in vim, it redirects me to import statement, not to class definition. In this code all is ok:
file a.py:
```
class A():
pass
```
file b.py:
```
from a import *
b = A()
``` | You can add the following line to your ~/.ctags file.
> --python-kinds=-i
to have ctags skip indexing import statements. To see what else you can enable/disable:
> ctags --list-kinds=python |
how to insert a small image on the corner of a plot with matplotlib? | 3,609,585 | 10 | 2010-08-31T13:44:55Z | 3,610,148 | 15 | 2010-08-31T14:46:34Z | [
"python",
"django",
"image",
"matplotlib"
] | What i want is really simple. I have a small image file called "logo.png" that i want to display on the upper left corner of my plots. But you cant find any example of that in the examples gallery of matplotlib
Im using django, and my code is something like this
```
def get_bars(request)
...
fig = Figure(face... | If you want the image at the corner of your actual figure (rather than the corner of your axis), look into [`figimage`](http://matplotlib.sourceforge.net/api/figure_api.html#matplotlib.figure.Figure.figimage).
Perhaps something like this? (using PIL to read the image):
```
import matplotlib.pyplot as plt
import Image... |
python: cannot concatenate 'str' and 'tuple' objects (it should works!) | 3,609,637 | 8 | 2010-08-31T13:51:17Z | 3,609,669 | 11 | 2010-08-31T13:54:43Z | [
"python",
"string",
"tuples"
] | **I have a code:**
```
print "bug " + data[str.find(data,'%')+2:-1]
temp = data[str.find(data,'%')+2:-1]
time.sleep(1)
print "bug tuple " + tuple(temp.split(', '))
```
And after this my application displays:
> **bug 1, 2, 3**
> Traceback (most recent
> call last): File
> "C:\Python26\Lib\site-packages\pythonwin\pywi... | ```
print tuple(something)
```
may work because print will do an implicit str() on the argument, but and expression like
```
"" + ()
```
does not work. The fact that you can print them individually doesn't make a difference, you can't concatenate a string and a tuple, you have to convert either one of them. I.e.
``... |
Which is the best way to allow configuration options be overridden at the command line in Python? | 3,609,852 | 30 | 2010-08-31T14:12:58Z | 4,324,260 | 8 | 2010-12-01T12:17:47Z | [
"python",
"command-line",
"configuration-files"
] | I have a Python application which needs quite a few (~30) configuration parameters. Up to now, I used the OptionParser class to define default values in the app itself, with the possibility to change individual parameters at the command line when invoking the application.
Now I would like to use 'proper' configuration... | I'm using ConfigParser and argparse with subcommands to handle such tasks. The important line in the code below is:
```
subp.set_defaults(**dict(conffile.items(subn)))
```
This will set the defaults of the subcommand (from argparse) to the values in the section of the config file.
A more complete example is below:
... |
Which is the best way to allow configuration options be overridden at the command line in Python? | 3,609,852 | 30 | 2010-08-31T14:12:58Z | 5,826,167 | 39 | 2011-04-28T23:18:40Z | [
"python",
"command-line",
"configuration-files"
] | I have a Python application which needs quite a few (~30) configuration parameters. Up to now, I used the OptionParser class to define default values in the app itself, with the possibility to change individual parameters at the command line when invoking the application.
Now I would like to use 'proper' configuration... | I just discovered you can do this with `argparse.ArgumentParser.parse_known_args()`. Start by using `parse_known_args()` to parse a configuration file form the commandline, then read it with ConfigParser and set the defaults, and then parse the rest of the options with `parse_args()`. This will allow you to have a defa... |
How to create the histogram of an array with masked values, in Numpy? | 3,610,040 | 11 | 2010-08-31T14:35:35Z | 3,623,917 | 7 | 2010-09-02T04:56:29Z | [
"python",
"arrays",
"numpy",
"histogram"
] | In Numpy 1.4.1, what is the simplest or most efficient way of calculating the histogram of a *masked* array? `numpy.histogram` and `pyplot.hist` do count the masked elements, by default!
The only simple solution I can think of right now involves creating a new array with the non-masked value:
```
histogram(m_arr[~m_a... | Try `hist(m_arr.compressed())`. |
How to create the histogram of an array with masked values, in Numpy? | 3,610,040 | 11 | 2010-08-31T14:35:35Z | 3,630,811 | 12 | 2010-09-02T20:08:56Z | [
"python",
"arrays",
"numpy",
"histogram"
] | In Numpy 1.4.1, what is the simplest or most efficient way of calculating the histogram of a *masked* array? `numpy.histogram` and `pyplot.hist` do count the masked elements, by default!
The only simple solution I can think of right now involves creating a new array with the non-masked value:
```
histogram(m_arr[~m_a... | (Undeleting this as per discussion above...)
I'm not sure whether or not the numpy developers would consider this a bug or expected behavior. I [asked on the mailing list](http://mail.scipy.org/pipermail/numpy-discussion/2010-September/052575.html), so I guess we'll see what they say.
Either way, it's an easy fix. Pa... |
How to create an in-memory zip file with directories without touching the disk? | 3,610,221 | 10 | 2010-08-31T14:55:14Z | 3,616,796 | 20 | 2010-09-01T09:51:48Z | [
"python"
] | In a python web application, I'm packaging up some stuff in a zip-file. I want to do this completely on the fly, in memory, without touching the disk. This goes fine using ZipFile.writestr as long as I'm creating a flat directory structure, but how do I create directories inside the zip?
I'm using python2.4.
<http://... | What 'theomega' said in the comment to my original post, adding a '/' in the filename does the trick. Thanks!
```
from zipfile import ZipFile
from StringIO import StringIO
inMemoryOutputFile = StringIO()
zipFile = ZipFile(inMemoryOutputFile, 'w')
zipFile.writestr('OEBPS/content.xhtml', 'hello world')
zipFile.close(... |
pydev doesn't find python library after installation | 3,610,272 | 23 | 2010-08-31T14:59:54Z | 3,610,311 | 33 | 2010-08-31T15:03:54Z | [
"python",
"eclipse",
"pydev"
] | I'm using Django and PyDev/Eclipse. I just installed django-treebeard with `setup.py install` and it got installed in my site-packages directory `C:\Python26\Lib\site-packages`. I can successfully import it in the python shell with `import treebeard`. However PyDev complains that it cannot resolve it when I try to impo... | Pydev doesn't automatically rescan the site-packages folder. You need to go to `Preferences-> Interpreter -> Python` and click apply to make it scan again. |
pydev doesn't find python library after installation | 3,610,272 | 23 | 2010-08-31T14:59:54Z | 6,144,832 | 12 | 2011-05-26T20:45:19Z | [
"python",
"eclipse",
"pydev"
] | I'm using Django and PyDev/Eclipse. I just installed django-treebeard with `setup.py install` and it got installed in my site-packages directory `C:\Python26\Lib\site-packages`. I can successfully import it in the python shell with `import treebeard`. However PyDev complains that it cannot resolve it when I try to impo... | I also faced the same error when i had installed a new package.i'm using eclipse Helios.
Even after applying and re scanning the folder it was NOT detecting the new packages. So finally i clicked on the "Click here to configure a interpreter not listed" listed and deleted the already selected interpreter and used the a... |
Is it possible to memcache a json result in App Engine? | 3,610,854 | 2 | 2010-08-31T15:59:14Z | 3,610,930 | 7 | 2010-08-31T16:08:07Z | [
"python",
"json",
"google-app-engine"
] | I think my question is already clear enough, but to make it even more clear i will illustrate it with my example.
I'm currently returning many json every request, which I would like to cache in some way. I thought memcache would be great, but I only see that they use memcache for caching queries. | JSON is just text, so yes, you can store it in memcache. |
How to empty a Python list without doing list = []? | 3,611,203 | 3 | 2010-08-31T16:43:30Z | 3,611,262 | 11 | 2010-08-31T16:49:57Z | [
"python",
"types"
] | If the `my_list` variable is global, you can't do:
```
my_list = []
```
that just create a new reference in the local scope.
Also, I found disgusting using the `global` keyword, so how can I empty a list using its methods? | ```
del a[:]
```
or
```
a[:] = []
``` |
Scoping in Python 'for' loops | 3,611,760 | 74 | 2010-08-31T17:52:11Z | 3,611,804 | 22 | 2010-08-31T17:57:22Z | [
"python",
"scope"
] | I'm not asking about Python's scoping rules; I understand generally *how* scoping works in Python for loops. My question is *why* the design decisions were made in this way. For example (no pun intended):
```
for foo in xrange(10):
bar = 2
print(foo, bar)
```
The above will print (9,2).
This strikes me as weird:... | A really useful case for this is when using `enumerate` and you want the total count in the end:
```
for count, x in enumerate(someiterator):
dosomething(count, x)
print "I did something {0} times".format(count)
```
Is this necessary? No. But, it sure is convenient.
Another thing to be aware of: in Python 2, var... |
Scoping in Python 'for' loops | 3,611,760 | 74 | 2010-08-31T17:52:11Z | 3,611,858 | 30 | 2010-08-31T18:04:12Z | [
"python",
"scope"
] | I'm not asking about Python's scoping rules; I understand generally *how* scoping works in Python for loops. My question is *why* the design decisions were made in this way. For example (no pun intended):
```
for foo in xrange(10):
bar = 2
print(foo, bar)
```
The above will print (9,2).
This strikes me as weird:... | Python does not have blocks, as do some other languages (such as C/C++ or Java). Therefore, scoping unit in Python is a function. |
Scoping in Python 'for' loops | 3,611,760 | 74 | 2010-08-31T17:52:11Z | 3,611,987 | 45 | 2010-08-31T18:22:03Z | [
"python",
"scope"
] | I'm not asking about Python's scoping rules; I understand generally *how* scoping works in Python for loops. My question is *why* the design decisions were made in this way. For example (no pun intended):
```
for foo in xrange(10):
bar = 2
print(foo, bar)
```
The above will print (9,2).
This strikes me as weird:... | The likeliest answer is that it just keeps the grammar simple, hasn't been a stumbling block for adoption, and many have been happy with not having to disambiguate the scope to which a name belongs when assigning to it within a loop construct. Variables are not declared within a scope, it is implied by the location of ... |
can't multiply sequence by non-int of type 'float' | 3,612,378 | 9 | 2010-08-31T19:15:48Z | 3,612,407 | 9 | 2010-08-31T19:18:25Z | [
"python",
"floating-point",
"sequence"
] | level: beginner
why do i get error "can't multiply sequence by non-int of type 'float'"?
```
def nestEgVariable(salary, save, growthRates):
SavingsRecord = []
fund = 0
depositPerYear = salary * save * 0.01
for i in growthRates:
fund = fund * (1 + 0.01 * growthRates) + depositPerYear
... | ```
for i in growthRates:
fund = fund * (1 + 0.01 * growthRates) + depositPerYear
```
should be:
```
for i in growthRates:
fund = fund * (1 + 0.01 * i) + depositPerYear
```
You are multiplying 0.01 with the growthRates list object. Multiplying a list by an integer is valid (it's overloaded syntactic suga... |
Wrappers around lambda expressions | 3,613,981 | 3 | 2010-08-31T23:36:45Z | 3,614,018 | 7 | 2010-08-31T23:44:07Z | [
"python",
"lambda"
] | I have functions in python that take two inputs, do some manipulations, and return two outputs. I would like to rearrange the output arguments, so I wrote a wrapper function around the original function that creates a new function with the new output order
```
def rotate(f):
h = lambda x,y: -f(x,y)[1], f(x,y)[0]
... | You need to add parentheses around the lambda expression:
```
h = lambda x,y: (-f(x,y)[1], f(x,y)[0])
```
Otherwise, Python interprets the code as:
```
h = (lambda x,y: -f(x,y)[1]), f(x,y)[0]
```
and `h` is a 2-tuple. |
Why is my code stopping? | 3,614,075 | 2 | 2010-08-31T23:58:50Z | 3,614,205 | 7 | 2010-09-01T00:26:15Z | [
"python",
"regex",
"string-matching"
] | Hey I've encountered an issue where my program stops iterating through the file at the 57802 record for some reason I cannot figure out. I put a heartbeat section in so I would be able to see which line it is on and it helped but now I am stuck as to why it stops here. I thought it was a memory issue but I just ran it ... | What does the input line that gives you trouble look like? I'd try printing that out. I suspect your CPU is pegged while this is running.
Nested regexps, like you have can have [VERY](http://www.regular-expressions.info/catastrophic.html) bad performance when they don't match quickly.
```
((\w+).?)+:
```
Imagine a s... |
change background color highlight for errors detected by pylint with ropevim and ropemode installed | 3,614,312 | 5 | 2010-09-01T00:53:02Z | 11,424,454 | 7 | 2012-07-11T01:49:32Z | [
"python",
"vim",
"pylint"
] | It changes the background to red, I can't read the text to correct the error!
How can I configure a different highlight? Does it have a setting? | I got an red background problem when a begin a string in python with " or '. After configure the spellbad options it seems like good.
```
highlight clear SpellBad
highlight SpellBad term=standout ctermfg=1 term=underline cterm=underline
highlight clear SpellCap
highlight SpellCap term=underline cterm=underline
highlig... |
AttributeError when unpickling an object | 3,614,379 | 11 | 2010-09-01T01:10:29Z | 3,614,457 | 14 | 2010-09-01T01:32:44Z | [
"python",
"pickle"
] | I'm trying to pickle an instance of a class in one module, and unpickle it in another.
Here's where I pickle:
```
import cPickle
def pickleObject():
object = Foo()
savefile = open('path/to/file', 'w')
cPickle.dump(object, savefile, cPickle.HIGHEST_PROTOCOL)
class Foo(object):
(...)
```
and here's ... | `class Foo` must be importable via the same path in the unpickling environment so that the pickled object can be reinstantiated.
I think your issue is that you define `Foo` in the module that you are executing as main (`__name__ == "__main__"`). Pickle will serialize the path (not the class object/definition!!!) to `F... |
Python, import string of Python code as module | 3,614,537 | 13 | 2010-09-01T01:56:17Z | 3,614,555 | 14 | 2010-09-01T02:02:16Z | [
"python",
"metaprogramming"
] | In python you can do something like this to import a module using a string filename, and assign its namespace a variable on the local namespace.
```
x = __import__(str)
```
I'm wondering if there is a related function that will take take a string of Python code, instead of a path to a file with Python code, and retur... | Here's an [example](http://code.activestate.com/recipes/82234-importing-a-dynamically-generated-module/) of dynamically creating module objects using the [imp module](http://docs.python.org/library/imp.html) |
How similar are Python, jQuery, C syntax wise? | 3,615,122 | 4 | 2010-09-01T04:54:40Z | 3,615,482 | 8 | 2010-09-01T06:20:30Z | [
"javascript",
"jquery",
"python",
"c",
"syntax"
] | I'm trying to get a sense of the similarities between languages in syntax. How similar are Python, jQuery and C? I started programming in Actionscript 3 and then moved on to Javascript , then went on and learned Prototype, and then I started using jQuery and found that the syntax is very different. So is jQuery more li... | C is much different from the languages you've asked about. Remember that C isn't an interpreted language and will not be treated as such in your code. In short, you're up for a lot more material to learn --while dealing with C-- in terms of things like memory management and semantics than the other languages.
In regar... |
Should wildcard import be avoided? | 3,615,125 | 22 | 2010-09-01T04:54:58Z | 3,615,206 | 25 | 2010-09-01T05:17:18Z | [
"python",
"pyqt",
"pyqt4",
"pylint",
"python-import"
] | I'm using PyQt and am running into this issue. If my import statements are:
```
from PyQt4.QtCore import *
from PyQt4.QtGui import *
```
then pylint gives hundreds of "Unused import" warnings. I'm hesitant to just turn them off, because there might be other unused imports that are actually useful to see. Another opti... | The answer to your question's title is "yes": I recommend never using `from ... import *`, and I discussed the reasons in another very recent answer. Briefly, qualified names are *good*, barenames are very limited, so the "third option" is optimal (as you'll be using qualified names, not barenames) among those you pres... |
What's the best way to include a PDF in my Sphinx documentation? | 3,615,142 | 8 | 2010-09-01T05:00:51Z | 3,622,149 | 10 | 2010-09-01T21:05:07Z | [
"python",
"documentation",
"python-sphinx"
] | I have a PDF that has some in depth explanation for an example in the Sphinx documentation for a package I have. Is there a way to easily include the PDF in my project (and have it copy over when I build the docs)? I tried linking to it with :doc: but this did not copy it over. | Use the [:download:](http://sphinx.pocoo.org/markup/inline.html#role-download) text role to bring in an arbitrary additional file. So in your case you might do something like this:
```
For an in-depth explanation, please see :download:`A Detailed Example <some_extra_file.pdf>`.
``` |
python count days ignoring weekends | 3,615,375 | 19 | 2010-09-01T05:54:45Z | 3,615,984 | 32 | 2010-09-01T07:48:27Z | [
"python"
] | how can I calculate number of days between two dates ignoring weekends ? | ```
>>> from datetime import date,timedelta
>>> fromdate = date(2010,1,1)
>>> todate = date(2010,3,31)
>>> daygenerator = (fromdate + timedelta(x + 1) for x in xrange((todate - fromdate).days))
>>> sum(1 for day in daygenerator if day.weekday() < 5)
63
```
This [creates a generator using a generator expression](http:/... |
python count days ignoring weekends | 3,615,375 | 19 | 2010-09-01T05:54:45Z | 3,617,358 | 9 | 2010-09-01T11:08:48Z | [
"python"
] | how can I calculate number of days between two dates ignoring weekends ? | The answers given so far will work, but are highly inefficient if the dates are a large distance apart (due to the loop).
This should work:
```
import datetime
start = datetime.date(2010,1,1)
end = datetime.date(2010,3,31)
daydiff = end.weekday() - start.weekday()
days = ((end-start).days - daydiff) / 7 * 5 + min(... |
python count days ignoring weekends | 3,615,375 | 19 | 2010-09-01T05:54:45Z | 26,221,138 | 13 | 2014-10-06T17:02:36Z | [
"python"
] | how can I calculate number of days between two dates ignoring weekends ? | I think the cleanest solution is to use the numpy function `busday_count`
```
import numpy as np
import datetime as dt
start = dt.date( 2014, 1, 1 )
end = dt.date( 2014, 1, 16 )
days = np.busday_count( start, end )
``` |
Iterating over dictionary items(), values(), keys() in Python 3 | 3,616,721 | 29 | 2010-09-01T09:41:48Z | 3,617,008 | 42 | 2010-09-01T10:19:50Z | [
"python",
"python-3.x",
"dictionary",
"iterator"
] | If I understand correctly, in Python 2, `iter(d.keys())` was the same as `d.iterkeys()`. But now, `d.keys()` is a view, which is in between the list and the iterator. What's the difference between a view and an iterator?
In other words, in Python 3, what's the difference between
```
for k in d.keys()
f(k)
```
an... | *I'm not sure if this is quite an answer to your questions but hopefully it explains a bit about the difference between Python 2 and 3 in this regard.*
In Python 2, `iter(d.keys())` and `d.iterkeys()` are not quite equivalent, although they will behave the same. In the first, `keys()` will return a copy of the diction... |
How to properly use relative or absolute imports in Python modules? | 3,616,952 | 24 | 2010-09-01T10:11:38Z | 3,617,928 | 21 | 2010-09-01T12:23:36Z | [
"python",
"module",
"packages",
"python-module",
"python-import"
] | Usage of relative imports in Python has one drawback, you will not be able to run the modules as standalones anymore because you will get an exception: `ValueError: Attempted relative import in non-package`
```
# /test.py: just a sample file importing foo module
import foo
...
# /foo/foo.py:
from . import bar
...
if ... | You could just start 'to run the modules as standalones' in a bit a different way:
Instead of:
```
python foo/bar.py
```
Use:
```
python -mfoo.bar
```
Of course, the `foo/__init__.py` file must be present.
Please also note, that you have a circular dependency between `foo.py` and `bar.py` â this won't work. I g... |
How to properly use relative or absolute imports in Python modules? | 3,616,952 | 24 | 2010-09-01T10:11:38Z | 3,648,126 | 16 | 2010-09-05T22:44:53Z | [
"python",
"module",
"packages",
"python-module",
"python-import"
] | Usage of relative imports in Python has one drawback, you will not be able to run the modules as standalones anymore because you will get an exception: `ValueError: Attempted relative import in non-package`
```
# /test.py: just a sample file importing foo module
import foo
...
# /foo/foo.py:
from . import bar
...
if ... | First, I assume you realize what you've written would lead to a circular import issue, because foo imports bar and viceversa; try adding
```
from foo import bar
```
to test.py, and you'll see it fails. The example must be changed in order to work.
So, what you're asking is really to fallback to absolute import when ... |
Escape string Python for MySQL | 3,617,052 | 43 | 2010-09-01T10:23:59Z | 3,617,097 | 62 | 2010-09-01T10:29:58Z | [
"python",
"mysql",
"escaping"
] | I use Python and MySQLdb to download web pages and store them into database. The problem I have is that I can't save complicated strings in the database because they are not properly escaped.
Is there a function in Python that I can use to escape a string for MySQL? I tried with `'''` (triple simple quotes) and `"""`,... | ```
conn.escape_string()
```
See MySQL C API function mapping: <http://mysql-python.sourceforge.net/MySQLdb.html> |
Escape string Python for MySQL | 3,617,052 | 43 | 2010-09-01T10:23:59Z | 27,575,399 | 28 | 2014-12-19T23:36:35Z | [
"python",
"mysql",
"escaping"
] | I use Python and MySQLdb to download web pages and store them into database. The problem I have is that I can't save complicated strings in the database because they are not properly escaped.
Is there a function in Python that I can use to escape a string for MySQL? I tried with `'''` (triple simple quotes) and `"""`,... | The MySQLdb library will actually do this for you, if you use their implementations to build an SQL query string instead of trying to build your own.
Don't do:
```
sql = "INSERT INTO TABLE_A (COL_A,COL_B) VALUES (%s, %s)" % (val1, val2)
cursor.execute(sql)
```
Do:
```
sql = "INSERT INTO TABLE_A (COL_A,COL_B) VALUES... |
Average timedelta in list | 3,617,170 | 7 | 2010-09-01T10:41:39Z | 3,617,540 | 26 | 2010-09-01T11:32:38Z | [
"python"
] | I want to calculate the avarage timedelta between dates in a list.
Although the following works well, I'm wondering if there's a smarter way?
```
delta = lambda last, next: (next - last).seconds + (next - last).days * 86400
total = sum(delta(items[i-1], items[i]) for i in range(1, len(items)))
average = total / (le... | Btw, if you have a list of timedeltas or datetimes, why do you even do any math yourself?
```
datetimes = [ ... ]
# subtracting datetimes gives timedeltas
timedeltas = [datetimes[i-1]-datetimes[i] for i in range(1, len(datetimes))]
# giving datetime.timedelta(0) as the start value makes sum work on tds
average_time... |
How to empty a Python dict without doing my_dict = {}? | 3,618,612 | 4 | 2010-09-01T13:35:16Z | 3,618,651 | 8 | 2010-09-01T13:39:41Z | [
"python",
"types"
] | If the `my_dict` variable is global, you can't do:
```
my_dict = {}
```
that just create a new reference in the local scope.
Also, I found disgusting using the `global` keyword, so how can I empty a dict using its methods? | Use the `clear()` method?
[**Documentation**](http://docs.python.org/library/stdtypes.html#dict) - (docs.python.org) |
How to query a table, in sqlalchemy | 3,618,690 | 10 | 2010-09-01T13:43:00Z | 3,618,796 | 11 | 2010-09-01T13:54:48Z | [
"python",
"sqlalchemy"
] | I know how to query on a model now. Suppose there is a `Question` model:
```
class Question(Base):
__tablename__ = "questions"
id=Column(...)
user_id=Column(...)
...
```
Now, I can do:
```
question = Session.query(Question).filter_by(user_id=123).one()
```
But, now, I have a table (not a model) `que... | I think it's `Session.query(questions).filter(questions.c.user_id==123).one()` |
Python accelerator | 3,619,063 | 3 | 2010-09-01T14:22:42Z | 3,619,244 | 8 | 2010-09-01T14:40:07Z | [
"php",
"python",
"accelerator"
] | I'm planning to use Python to develop a web application. Anybody has any idea about any accelerator for python? (something like eAccelerator or apc for php) if not, is there any way to cache the pre-compiled python bytecode ?
Any idea about the performance comparison between python and php (assuming db/network latencie... | There's a trick to this.
It's called `mod_wsgi`.
The essence of it works like this.
1. For "static" content (.css, .js, images, etc.) put them in a directory so they're served by Apache, without your Python program knowing they were sent.
2. For "dynamic" content (the main HTML page itself) you use `mod_wsgi` to for... |
Python variable weirdness? | 3,619,368 | 3 | 2010-09-01T14:52:58Z | 3,619,401 | 12 | 2010-09-01T14:55:56Z | [
"python",
"list",
"variables",
"reference",
"tuples"
] | What's going on with my Python variable? `old_pos` seems to be linked to `pos`:
Code:
```
pos = [7, 7]
direction = [1, 1]
old_pos = pos
print 'pos = '+str(pos)
print 'old_pos = '+str(old_pos)
pos[0] += direction[0]
pos[1] += direction[1]
print 'pos = '+str(pos)
print 'old_pos = '+str(old_pos)
```
Output:
``... | When you say `old_pos = pos`, you are not creating a copy of `pos`, but just making another reference to the same list. If you want two lists that behave independently, you'll need to make a copy, like using the `list(pos)` function as you mention, or using the slice notation `pos[:]`. |
Python unit testing: make nose show failed assertions values | 3,619,527 | 11 | 2010-09-01T15:09:16Z | 10,628,930 | 21 | 2012-05-17T01:50:30Z | [
"python",
"nose"
] | is it possible to show the assertion values that failed? It shows the traceback and what kind of exception was throw but it would more practical to know which values failed.
Example:
```
assert result.file == file
AssertionError
``` | You should run nosetests -d this will display the values of the objects that fail the compare in assert. |
Python/Django AttributeError "Object 'players' has no attribute 'fields' | 3,620,198 | 9 | 2010-09-01T16:30:37Z | 3,620,417 | 11 | 2010-09-01T17:00:51Z | [
"python",
"django",
"django-admin"
] | I am setting up the admin page so that I might be able to use it to add data, players in this case. When you go and attempt to register the Players class in admin.py you get the error described in the question title (object 'players' has no attribute 'fields'). Looking through views.py that I pasted a snippet out of be... | Fix was in admin.py, see below.
Before:
```
#foozball admin python file
from foozball.leaguemanager.models import Division, Games, RosterStatus, Teams, Players
from django.contrib import admin
admin.site.register(Teams, Players)
```
After:
# foozball admin python file
```
from foozball.leaguemanager.models impor... |
how to deal with .mdb access files with python | 3,620,539 | 27 | 2010-09-01T17:17:45Z | 3,621,775 | 33 | 2010-09-01T20:10:18Z | [
"python",
"ms-access"
] | Can someone point me in the right direction on how to open a .mdb file in python? I normally like including some code to start off a discussion, but I don't know where to start. I work with mysql a fair bit with python. I was wondering if there is a way to work with .mdb files in a similar way? | Below is some code I wrote for [another SO question](http://stackoverflow.com/questions/3064830/query-crashes-ms-access).
It requires the 3rd-party [pyodbc module](https://github.com/mkleehammer/pyodbc).
This very simple example will connect to a table and export the results to a file.
Feel free to expand upon you... |
Measuring elapsed time with the Time module | 3,620,943 | 103 | 2010-09-01T18:17:56Z | 3,620,972 | 189 | 2010-09-01T18:22:03Z | [
"python",
"time",
"elapsed"
] | With the Time module in python is it possible to measure elapsed time? If so, how do I do that?
I need to do this so that if the cursor has been in a widget for a certain duration an event happens. | ```
start_time = time.time()
# your code
elapsed_time = time.time() - start_time
```
You can also write simple decorator to simplify measurement of execution time of various functions:
```
import time
from functools import wraps
PROF_DATA = {}
def profile(fn):
@wraps(fn)
def with_profiling(*args, **kwargs):... |
Measuring elapsed time with the Time module | 3,620,943 | 103 | 2010-09-01T18:17:56Z | 3,621,018 | 42 | 2010-09-01T18:28:25Z | [
"python",
"time",
"elapsed"
] | With the Time module in python is it possible to measure elapsed time? If so, how do I do that?
I need to do this so that if the cursor has been in a widget for a certain duration an event happens. | `time.time()` will do the job.
```
import time
start = time.time()
# run your code
end = time.time()
elapsed = end - start
```
You may want to look at [this](http://stackoverflow.com/questions/85451/python-time-clock-vs-time-time-accuracy) question, but I don't think it will be necessary. |
Python - Minimum of a List of Instance Variables | 3,621,826 | 4 | 2010-09-01T20:17:09Z | 3,621,834 | 13 | 2010-09-01T20:18:40Z | [
"python",
"list",
"min"
] | I'm new to Python and I really love the `min` function.
```
>>>min([1,3,15])
0
```
But what if I have a list of instances, and they all have a variable named `number`?
```
class Instance():
def __init__(self, number):
self.number = number
i1 = Instance(1)
i2 = Instance(3)
i3 = Instance(15)
iList = [i1,i... | The OOP way would be to implement `__lt__`:
```
class Instance():
def __init__(self, number):
self.number = number
def __lt__(self, other):
return self.number < other.number
# now min(iList) just works
```
Another way is
`imin = min(iList, key=lambda x:x.number)`
Functions like `sor... |
Python - Minimum of a List of Instance Variables | 3,621,826 | 4 | 2010-09-01T20:17:09Z | 3,621,848 | 10 | 2010-09-01T20:19:51Z | [
"python",
"list",
"min"
] | I'm new to Python and I really love the `min` function.
```
>>>min([1,3,15])
0
```
But what if I have a list of instances, and they all have a variable named `number`?
```
class Instance():
def __init__(self, number):
self.number = number
i1 = Instance(1)
i2 = Instance(3)
i3 = Instance(15)
iList = [i1,i... | ```
from operator import attrgetter
min( iList, key = attrgetter( "number" ) )
```
The same `key` argument also works with `sort`, for implementing the decorate-sort-undecorate idiom Pythonically. |
Python programmer: Learning ruby (for rails) | 3,622,611 | 7 | 2010-09-01T22:38:18Z | 3,622,698 | 7 | 2010-09-01T22:55:12Z | [
"python",
"ruby-on-rails",
"ruby"
] | I'm a moderately competent Python programmer, and am considering working on my first web-app; it seems a very large number of FOSS webapp code is written in Ruby (i.e. Rails), and I suspect that might help with my learning curve (i.e. for building a decent, if useless webapp).
There is lots of material for learning Ru... | Michael Hartl's [Ruby on Rails Tutorial](http://railstutorial.org/) is by far the best introduction to Rails I've been able to find online. It's very easy to understand what's going on if you've already got experience in web application development in general. Versions of the tutorial for Rails 2.3.8 and Rails 3 are av... |
Returning a file to a WSGI GET request | 3,622,675 | 3 | 2010-09-01T22:49:35Z | 3,622,786 | 10 | 2010-09-01T23:18:19Z | [
"python",
"forms",
"download",
"get",
"wsgi"
] | I'm new to WSGI on python; but have a windows server that's got isapi\_wsgi installed on it. I also have a script that handles my GET requests all up and running great. The thing is, someone sends me a request, and I need to return a zip file to the requester. The following code is in my GET handler and it works, but d... | Taken directly from [PEP 333](http://www.python.org/dev/peps/pep-0333/#optional-platform-specific-file-handling):
```
if 'wsgi.file_wrapper' in environ:
return environ['wsgi.file_wrapper'](filelike, block_size)
else:
return iter(lambda: filelike.read(block_size), '')
```
Also you probably want the [Content-Di... |
A way to "listen" for changes to a file system from Python on Linux? | 3,622,796 | 2 | 2010-09-01T23:21:08Z | 3,622,817 | 8 | 2010-09-01T23:25:54Z | [
"python",
"linux"
] | I want to be able to detect whenever new files are created or existing files are modified or deleted within a given directory tree (or set of trees). The brute force way to do this would be to just rescan the tree looking for changes, but I'm looking for a more "interrupt driven" solution where the file system tells my... | [pyinotify](https://github.com/seb-m/pyinotify) is IMHO the only way to get system changes without scanning the directory. |
A way to "listen" for changes to a file system from Python on Linux? | 3,622,796 | 2 | 2010-09-01T23:21:08Z | 3,622,824 | 8 | 2010-09-01T23:27:53Z | [
"python",
"linux"
] | I want to be able to detect whenever new files are created or existing files are modified or deleted within a given directory tree (or set of trees). The brute force way to do this would be to just rescan the tree looking for changes, but I'm looking for a more "interrupt driven" solution where the file system tells my... | [`twisted.internet.inotify`](http://twistedmatrix.com/documents/10.1.0/api/twisted.internet.inotify.html)! It's much more useful to have an event loop attached than just free-floating inotify. Using twisted also gives you [`filepath`](http://twistedmatrix.com/documents/10.1.0/api/twisted.python.filepath.html) for free,... |
Converting a 2D numpy array to a structured array | 3,622,850 | 17 | 2010-09-01T23:34:24Z | 5,204,280 | 20 | 2011-03-05T14:08:47Z | [
"python",
"numpy"
] | I'm trying to convert a two-dimensional array into a structured array with named fields. I want each row in the 2D array to be a new record in the structured array. Unfortunately, nothing I've tried is working the way I expect.
I'm starting with:
```
>>> myarray = numpy.array([("Hello",2.5,3),("World",3.6,2)])
>>> pr... | You can "create a record array from a (flat) list of arrays" using [numpy.core.records.fromarrays](http://docs.scipy.org/doc/numpy/reference/generated/numpy.core.records.fromarrays.html) as follows:
```
>>> import numpy as np
>>> myarray = np.array([("Hello",2.5,3),("World",3.6,2)])
>>> print myarray
[['Hello' '2.5' '... |
newbie python csv writer question: why every character separated? | 3,623,303 | 2 | 2010-09-02T01:49:34Z | 3,623,321 | 9 | 2010-09-02T01:52:50Z | [
"python",
"csv"
] | please excuse me for simple question: i tried to write simple csv file using csv module. however, the result is this:
```
Spam |Baked Beans|
/ s e a r c h | | , | | A d v a n c e d | | S e a r c h
/ a b o u t / | | , | | A b o u t
/ n e w s / | | , | | N e w s
/ d o c / | | , | | D o c u m e n t a t i o n
/ d o w n l ... | `writerow`'s argument is a sequence... and a string, which is what you're passing, is a sequence of single characters. To fix your bug, in the 2nd call to `writerow`, pass, instead, `[self.linkvalue, data]` as the argument. |
Python matplotlib: memory not being released when specifying figure size | 3,623,600 | 25 | 2010-09-02T03:08:59Z | 3,623,614 | 35 | 2010-09-02T03:17:04Z | [
"python",
"memory-management",
"matplotlib"
] | I'm using matplotlib to generate many plots of the results of a numerical simulation. The plots are used as frames in a video, and so I'm generating many of them by repeatedly calling a function similar to this one:
```
from pylab import *
def plot_density(filename,i,t,psi_Na):
figure(figsize=(8,6))
imshow(... | From the docstring for `pylab.figure`:
```
In [313]: pylab.figure?
```
> If you are creating many figures, make
> sure you explicitly call "close" on
> the figures you are not using, because
> this will enable pylab to properly
> clean up the memory.
So perhaps try:
```
pylab.close() # closes the current figure... |
Python matplotlib: memory not being released when specifying figure size | 3,623,600 | 25 | 2010-09-02T03:08:59Z | 8,501,805 | 9 | 2011-12-14T09:03:17Z | [
"python",
"memory-management",
"matplotlib"
] | I'm using matplotlib to generate many plots of the results of a numerical simulation. The plots are used as frames in a video, and so I'm generating many of them by repeatedly calling a function similar to this one:
```
from pylab import *
def plot_density(filename,i,t,psi_Na):
figure(figsize=(8,6))
imshow(... | Closing a figure is definitely an option, however, repeated many times, this is time consuming. What I suggest is to have a single persistent figure object (via [static function variable](http://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function), or as additional fun... |
Python: How to custom order a list? | 3,624,323 | 8 | 2010-09-02T06:36:06Z | 3,624,354 | 11 | 2010-09-02T06:41:33Z | [
"python",
"order"
] | Obs: I know lists in python are not order-fixed, but think that this one will be.
And I'm using Python 2.4
I have a list, like (for example) this one:
```
mylist = [ ( u'Article', {"...some_data..."} ) ,
( u'Report' , {"...some_data..."} ) ,
( u'Book' , {"...another_data..."} ) ,
...#con... | You could use a dictionary that would map every first element to its "weight" and then check this dictionary inside a sorting function.
Something like:
```
d = { "Report": 1,
"Article": 2,
"Book": 3 }
result = sorted(mylist, key=lambda x:d[x[0]])
``` |
How to provide additional initialization for a subclass of namedtuple? | 3,624,753 | 29 | 2010-09-02T07:49:30Z | 3,624,799 | 31 | 2010-09-02T07:56:21Z | [
"python",
"inheritance",
"tuples"
] | Suppose I have a `namedtuple` like this:
```
EdgeBase = namedtuple("EdgeBase", "left, right")
```
I want to implement a custom hash-function for this, so I create the following subclass:
```
class Edge(EdgeBase):
def __hash__(self):
return hash(self.left) * hash(self.right)
```
Since the object is immut... | ```
class Edge(EdgeBase):
def __new__(cls, left, right):
self = super(Edge, cls).__new__(cls, left, right)
self._hash = hash(self.left) * hash(self.right)
return self
def __hash__(self):
return self._hash
```
`__new__` is what you want to call here because tuples are immutable.... |
Problems installing lxml on a Mac, it installs but module not found | 3,624,779 | 7 | 2010-09-02T07:53:34Z | 3,625,447 | 9 | 2010-09-02T08:42:49Z | [
"python",
"osx",
"lxml"
] | The code
```
from lxml import etree
```
produces the error
```
ImportError: No module named lxml
```
Running
```
sudo easy_install lxml
```
results in
```
lxml 2.2.7 is already the active version in easy-install.pth
Removing lxml-2.2.7-py2.5-macosx-10.3-i386.egg from site-packages and rerunning sudo easy_instal... | You appear to be trying to `easy_install` lxml into the Apple-supplied Python 2.5 for OS X 10.5 but using an egg that was likely built with a python.org Python 2.5. If you have both installed on your system, keep in mind that you need to have a separate `easy_install` (setuptools or Distribute) for each Python. Apple s... |
Python Windows service autostarts too early | 3,626,766 | 2 | 2010-09-02T11:47:17Z | 3,627,323 | 8 | 2010-09-02T13:01:20Z | [
"python",
"windows-services"
] | I am running a Python script as a Windows service, but it seems to be failing whenever I set it to auto-start. I believe this may be because the service uses network resources that are not yet mounted when the service starts. Is there a way I can get it to wait until startup is complete before running? | Configure your Windows Service so that [it has the `Workstation` Service as a dependency](http://support.microsoft.com/kb/193888).
This means Windows won't attempt to start your service until the appropriate resources are available. |
SQLAlchemy: avoiding repetition in declarative style class definition | 3,626,787 | 10 | 2010-09-02T11:49:34Z | 3,630,248 | 9 | 2010-09-02T18:56:00Z | [
"python",
"sqlalchemy"
] | I'm using SQLAlchemy, and many classes in my object model have the same two attributes: id and (integer & primary key), and name (a string). I'm trying to avoid declaring them in every class like so:
```
class C1(declarative_base()):
id = Column(Integer, primary_key = True)
name = Column(String)
#...
clas... | You could factor out your common attributes into a [mixin class](http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/mixins.html), and multiply inherit it alongside `declarative_base()`:
```
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
class IdName... |
Python: How exactly can you take a string, split it, reverse it and join it back together again? | 3,627,270 | 14 | 2010-09-02T12:54:53Z | 3,627,316 | 27 | 2010-09-02T13:00:55Z | [
"python",
"string",
"join",
"split",
"reverse"
] | How exactly can you take a string, split it, reverse it and join it back together again without the brackets, commas, etc. using python? | ```
>>> tmp = "a,b,cde"
>>> tmp2 = tmp.split(',')
>>> tmp2.reverse()
>>> "".join(tmp2)
'cdeba'
```
or simpler:
```
>>> tmp = "a,b,cde"
>>> ''.join(tmp.split(',')[::-1])
'cdeba'
```
The important parts here are the [split function](http://docs.python.org/library/stdtypes.html#str.split) and the [join function](http:/... |
Case insensitive 'in' - Python | 3,627,784 | 71 | 2010-09-02T13:56:30Z | 3,627,815 | 91 | 2010-09-02T13:59:07Z | [
"python",
"list",
"case-insensitive"
] | I love using the expression
```
if 'MICHAEL89' in USERNAMES:
...
```
where `USERNAMES` is a list
---
Is there any way to match items with case insensitivity or do I need to use a custom method? Just wondering if there is need to write extra code for this.
Thanks to everyone! | ```
if 'MICHAEL89' in (name.upper() for name in USERNAMES):
...
```
Alternatively:
```
if 'MICHAEL89' in map(str.upper, USERNAMES):
...
```
Or, yes, you can make a custom method. |
Case insensitive 'in' - Python | 3,627,784 | 71 | 2010-09-02T13:56:30Z | 3,628,254 | 12 | 2010-09-02T14:45:08Z | [
"python",
"list",
"case-insensitive"
] | I love using the expression
```
if 'MICHAEL89' in USERNAMES:
...
```
where `USERNAMES` is a list
---
Is there any way to match items with case insensitivity or do I need to use a custom method? Just wondering if there is need to write extra code for this.
Thanks to everyone! | I would make a *wrapper* so you can be non-invasive. Minimally, for example...:
```
class CaseInsensitively(object):
def __init__(self, s):
self.__s = s.lower()
def __hash__(self):
return hash(self.__s)
def __eq__(self, other):
# ensure proper comparison between instances of this cl... |
Case insensitive 'in' - Python | 3,627,784 | 71 | 2010-09-02T13:56:30Z | 3,628,659 | 8 | 2010-09-02T15:31:05Z | [
"python",
"list",
"case-insensitive"
] | I love using the expression
```
if 'MICHAEL89' in USERNAMES:
...
```
where `USERNAMES` is a list
---
Is there any way to match items with case insensitivity or do I need to use a custom method? Just wondering if there is need to write extra code for this.
Thanks to everyone! | Usually (in oop at least) you shape your object to behave the way you want. `name in USERNAMES` is not case insensitive, so `USERNAMES` needs to change:
```
class NameList(object):
def __init__(self, names):
self.names = names
def __contains__(self, name): # implements `in`
return name.lower()... |
Best output type and encoding practices for __repr__() functions? | 3,627,793 | 56 | 2010-09-02T13:57:16Z | 3,627,835 | 35 | 2010-09-02T14:01:23Z | [
"python",
"encoding",
"ascii",
"repr"
] | Lately, I've had lots of trouble with `__repr__()`, `format()`, and encodings. **Should the output of `__repr__()` be encoded or be a unicode string?** Is there a best encoding for the result of `__repr__()` in Python? What I want to output does have non-ASCII characters.
I use Python 2.x, and want to write code that ... | In Python2, `__repr__` (and `__str__`) must return a string object, not a
unicode object. In Python3, the situation is reversed, `__repr__` and `__str__`
must return unicode objects, not byte (née string) objects:
```
class Foo(object):
def __repr__(self):
return u'\N{WHITE SMILING FACE}'
class Bar(obje... |
How can I move file into Recycle Bin / trash on different platforms using PyQt4? | 3,628,517 | 17 | 2010-09-02T15:14:33Z | 4,773,369 | 35 | 2011-01-23T10:37:34Z | [
"python",
"qt4",
"cross-platform",
"pyqt4",
"recycle-bin"
] | I would like to add the next feature to my cross-platform PyQt4 application: when user selects some file and select "remove" action on it that file will be moved to Recycle Bin folder instead of being permantly removed. I think I can find Windows-specific solution using Win32 API or something similar, but I'd like to k... | It's a good thing you're using Python, I created a library to do just that a while ago:
<http://www.hardcoded.net/articles/send-files-to-trash-on-all-platforms.htm>
On PyPI: [Send2Trash](http://pypi.python.org/pypi/Send2Trash) |
Would twisted be a good choice for building a multi-threaded server? | 3,629,088 | 6 | 2010-09-02T16:22:35Z | 3,629,249 | 7 | 2010-09-02T16:43:51Z | [
"python",
"multithreading",
"twisted"
] | I need to pull from hundreds of pop3 email accounts, and i want to build a robust server to do this.
Would twisted be a good choice for this type of project?
Right now a simple prototype would be to pull from a single pop3 account, then it would pull from many but it would be a serialized process.
I want to create a... | Twisted is an event-driven networking framework written in Python. It builds heavily on asynchronous and non-blocking features and is best conceived to develop networking applications that utilizes these. It has thread support for use cases where you can not provide for asynchronous non-blocking I/O. This is based on t... |
Python "if X == Y and Z" syntax | 3,629,586 | 10 | 2010-09-02T17:27:28Z | 3,629,597 | 29 | 2010-09-02T17:28:35Z | [
"python",
"if-statement"
] | Does this:
```
if key == "name" and item:
```
mean the same as this:
```
if key == "name" and if key == "item":
```
If so, I'm totally confused about [example 5.14 in Dive Into Python](http://diveintopython.net/object_oriented_framework/special_class_methods.html). How can key be equal to both "name" and item? On t... | `if key == "name" and item:` means `if (key == "name") and (item evaluates to True)`.
Keep in mind that `(item evaluates to True)` is possible in several ways. For example `if (key == "name") and []` will evaluate to `False`. |
logging remove / inspect / modify handlers configured by fileConfig() | 3,630,774 | 22 | 2010-09-02T20:05:04Z | 3,630,800 | 24 | 2010-09-02T20:07:16Z | [
"python",
"logging"
] | How can I remove / inspect / modify handlers configured for my loggers using the fileConfig() function?
For removing there is Logger.removeHandler(hdlr) method, but how do I get the handler in first place if it was configured from file? | `logger.handlers` contains a list with all handlers of a logger. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.