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 |
|---|---|---|---|---|---|---|---|---|---|
Execute an installed Python package as a script? | 4,050,120 | 20 | 2010-10-29T08:11:47Z | 9,407,178 | 21 | 2012-02-23T04:29:25Z | [
"python"
] | Is there a way to enable a package to be executed as a script? For example:
```
[~]# easy_install /path/to/foo.egg
...
[~]# python -m foo --name World
Hello World
```
I've tried creating a `__main__.py` file inside my package but it's not being executed (I'm using Python 2.6). The following error is raised:
```
foo ... | This is a regression in Python 2.6. See [issue2571](http://bugs.python.org/issue2751):
> The ability to execute packages was never intended, since doing so
> breaks imports in a variety of subtle ways. It was actually a bug in
> 2.5 that it was permitted at all, so 2.6 not only disabled it again, but also added a test... |
Strange PEP8 recommandation on comparing Boolean values to True or False | 4,050,335 | 10 | 2010-10-29T08:47:30Z | 4,050,625 | 11 | 2010-10-29T09:33:33Z | [
"python",
"pep8"
] | At the end of python [PEP8](http://www.python.org/dev/peps/pep-0008/) I'm reading:
* Don't compare boolean values to True or False using `==`
```
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
```
I have no problem with that recommandation when the boolean is `True`, but it sou... | I believe you're reading it wrong. Try not to think of `greeting` as a noun so much as a verb ("I am greeting" instead of "This is a greeting").
You can see the clue in the preamble to PEP8:
> One of Guido's key insights is that code is read much more often than it is written. The guidelines provided here are intende... |
Python: OverflowError: math range error | 4,050,907 | 13 | 2010-10-29T10:15:15Z | 4,050,933 | 12 | 2010-10-29T10:19:27Z | [
"python",
"math",
"overflow"
] | I get a Overflow error when i try this calculation, but i cant figure out why.
```
1-math.exp(-4*1000000*-0.0641515994108)
``` | The number you're asking math.exp to calculate has, in decimal, over 110,000 digits. That's slightly outside of the range of a double, so it causes an overflow. |
Phylo BioPython building trees | 4,051,414 | 6 | 2010-10-29T11:36:36Z | 4,076,180 | 7 | 2010-11-02T09:01:58Z | [
"python",
"numpy",
"graphviz",
"biopython"
] | I trying to build a tree with BioPython, Phylo module.
What I've done so far is this image: 
each name has a four digit number followed by - and a number: this number refer to the number of times that sequence is represented. That means 1578 - 22, that node should repre... | I finally got this working. The basic premise is that you're going to use the `labels/nodelist` to build your `node_sizes`. This way they correlate properly. I'm sure I'm missing some important options to make the tree look 100% but it appears the node sizes are showing up properly.
```
#basically a stripped down rewr... |
help.....serial port programming | 4,051,869 | 3 | 2010-10-29T12:34:25Z | 4,051,925 | 7 | 2010-10-29T12:40:14Z | [
"python",
"linux",
"serial-port"
] | I want to communicate with my serial port in python. I installed pyserial, and uspp for linux. Still, when I run the following code:
```
import serial
ser = serial.Serial('/dev/pts/1', 19200, timeout=1)
print ser.portstr #check which port was really used
ser.write("hello") #write a string
ser.close() #
```
it giv... | `/dev/tyUSB1` looks like a typo. Device nodes are normally called `/dev/ttyXXX` |
Auto-Completion In wxPython wxComboBox | 4,051,988 | 8 | 2010-10-29T12:47:41Z | 4,052,328 | 7 | 2010-10-29T13:32:42Z | [
"python",
"combobox",
"autocomplete",
"wxpython",
"autosuggest"
] | I've been trying to make a ComboBox which would suggest options as you type, much like an IDE's code suggestions/code-sense, or googles suggestions when you type in a search.
The suggestions would be the items from the ComboBox dropdown, which contained the substring typed in the text box of the ComboBox.
I've tried ... | Few years ago I made a control like this by subclassing TextCtrl. It supports HTML formating for suggestions. [Here you go.](http://bitbucket.org/raz/wxautocompletectrl)
There is also the [Combo Box that Suggests Options](http://wiki.wxpython.org/Combo%20Box%20that%20Suggests%20Options) |
How to add random delays between the queries sent to Google to avoid getting blocked in python | 4,054,254 | 5 | 2010-10-29T17:10:49Z | 4,054,340 | 26 | 2010-10-29T17:22:12Z | [
"python",
"delay"
] | I have written a program which sends more than 15 queries to Google in each iteration, total iterations is about 50. For testing I have to run this program several times. However, by doing that, after several times, Google blocks me. is there any ways so I can fool google maybe by adding delays between each iteration? ... | First, Google probably are blocking you because they don't like it when you take too many of their resources. The best way to fix this is to slow it down, not delay randomly. Stick a 1 second wait after every request and you'll probably stop having problems.
That said:
```
from random import randint
from time import ... |
Python/Tkinter: Mouse drag a window without borders, eg. overridedirect(1) | 4,055,267 | 3 | 2010-10-29T19:35:22Z | 4,055,612 | 7 | 2010-10-29T20:25:05Z | [
"python",
"windows",
"user-interface",
"window",
"tkinter"
] | Any suggestions on how one might create event bindings that would allow a user to mouse drag a window without borders, eg. a window created with overridedirect(1)?
Use case: We would like to create a floating toolbar/palette window (without borders) that our users can drag around on their desktop.
Here's where I'm at... | Yes, Tkinter exposes enough functionality to do this, and no, there are no easier/higher-level ways to achive what you want to do. You pretty much have the right idea.
here's an example:
```
import Tkinter as tk
import tkFileDialog
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.... |
Assigning a value to an element of a slice in Python | 4,055,515 | 5 | 2010-10-29T20:10:28Z | 4,055,544 | 7 | 2010-10-29T20:13:44Z | [
"python",
"list",
"variable-assignment",
"slice"
] | This is a simple question about how Python handles data and variables. I've done a lot of experimenting and have Python mostly figured out, except this keeps tripping me up:
[edit: I separated and rearranged the examples for clarity]
**Example 1:**
```
>>> a = [[1], 2]
>>> a[0:1]
[[1]]
>>> a[0:1] = [[5]]
>>> a
[[5],... | a[0:1] is returning a new array which contains a reference to the array [1], thus you end up modifying the inner array via a reference call.
The reason the first case doesn't modify the [1] array is that you're assigning the copied outer array a new inner array value.
Bottom line - a[0:1] returns a copy of the data, ... |
Unit testing with django-celery? | 4,055,860 | 69 | 2010-10-29T20:57:31Z | 4,559,662 | 14 | 2010-12-30T02:52:08Z | [
"python",
"django",
"unit-testing",
"celery"
] | I am trying to come up with a testing methodology for our [django-celery](http://celeryq.org/docs/django-celery/index.html#celery-integration-for-django) project. I have read the notes in the [documentation](http://celeryq.org/docs/django-celery/cookbook/unit-testing.html#unit-testing), but it didn't give me a good ide... | Here's an excerpt from my testing base class that stubs out the `apply_async` method and records to the calls to it (which includes `Task.delay`.) It's a little gross, but it's managed to fit my needs over the past few months I've been using it.
```
from django.test import TestCase
from celery.task.base import Task
# ... |
Unit testing with django-celery? | 4,055,860 | 69 | 2010-10-29T20:57:31Z | 5,863,526 | 37 | 2011-05-02T23:19:53Z | [
"python",
"django",
"unit-testing",
"celery"
] | I am trying to come up with a testing methodology for our [django-celery](http://celeryq.org/docs/django-celery/index.html#celery-integration-for-django) project. I have read the notes in the [documentation](http://celeryq.org/docs/django-celery/cookbook/unit-testing.html#unit-testing), but it didn't give me a good ide... | Try setting:
```
BROKER_BACKEND = 'memory'
```
(Thanks to [asksol](http://stackoverflow.com/users/5577/asksol)'s comment.) |
Unit testing with django-celery? | 4,055,860 | 69 | 2010-10-29T20:57:31Z | 13,945,884 | 53 | 2012-12-19T05:08:11Z | [
"python",
"django",
"unit-testing",
"celery"
] | I am trying to come up with a testing methodology for our [django-celery](http://celeryq.org/docs/django-celery/index.html#celery-integration-for-django) project. I have read the notes in the [documentation](http://celeryq.org/docs/django-celery/cookbook/unit-testing.html#unit-testing), but it didn't give me a good ide... | I like to use the override\_settings decorator on tests which need celery results to complete.
```
from django.test import TestCase
from django.test.utils import override_settings
from myapp.tasks import mytask
class AddTestCase(TestCase):
@override_settings(CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
... |
Extracting data from a URL result with special formating | 4,056,375 | 3 | 2010-10-29T22:31:03Z | 4,056,588 | 12 | 2010-10-29T23:51:48Z | [
"python",
"parsing",
"url"
] | I have a URL:
<http://somewhere.com/relatedqueries?limit=2&query=seedterm>
where modifying the inputs, limit and query, will generate wanted data. Limit is the max number of term possible and query is the seed term.
The URL provides text result formated in this way:
oo.visualization.Query.setResponse({version:'0.... | It sounds like you can break this problem up into several subproblems.
# Subproblems
There are a handful of problems that need to be solved before composing the completed script:
1. **Forming the request URL:** Creating a configured request URL from a template
2. **Retrieving data:** Actually making the request
3. *... |
What is the easiest way to make an optional C extension for a python package? | 4,056,657 | 8 | 2010-10-30T00:11:01Z | 5,735,618 | 8 | 2011-04-20T19:28:57Z | [
"python",
"setuptools",
"cython",
"python-c-extension"
] | I've created a C extension that I'd like to enable in my Python package (using setuptools) only if a command line option is passed in. What is the easiest way to do this?
I can't seem to find any straightforward ways of going about this. | There's actually a distribute/setuptools feature called "Features" that can be used for this.
It's explicitly designed to have setup.py do different things based on `--with-xxx` and `--without-xxx` command line options.
* This [blog post](https://www.domenkozar.com/2010/07/07/hidden-gem-in-python-packaging-world/) giv... |
When should I use escape and safe in Django's template system? | 4,056,883 | 3 | 2010-10-30T01:40:10Z | 4,057,112 | 9 | 2010-10-30T03:26:37Z | [
"python",
"django",
"templates",
"escaping"
] | If I have a box where people put comments, and then I display that comment like this...should I escape?
```
{{ c.title }}
``` | Actually, it depends. Django's templating engine does escaping automatically, so you don't really need to escape.
If you add template filter "safe" like `{{c.title|safe}}` then you do need to worry about things like html injection, because "safe" marks the string as such and it means that it won't be escaped.
There i... |
CherryPy Logging: How do I configure and use the global and application level loggers? | 4,056,958 | 5 | 2010-10-30T02:12:54Z | 4,059,919 | 10 | 2010-10-30T17:50:31Z | [
"python",
"logging",
"cherrypy"
] | I'm having trouble with logging. I'm running CherryPy 3.2 and I've been reading through the docs [here](http://www.cherrypy.org/wiki/ConfigAPI), but haven't found any examples of how to configure a local log file for output and how to write to it.
Raspberry.py:
```
import socket
import sys
import cherrypy
app_roots ... | Simplifying a bit:
```
import os
import socket
import sys
import cherrypy
app_roots = {
# Sean's laptop dev environment.
"mylaptop": "/home/src/local-mydomain.com/py",
# Hosted dev environment.
"mydomain.com" : "/home/dev/src/py"
}
host... |
How do I programmatically set the docstring? | 4,056,983 | 27 | 2010-10-30T02:22:01Z | 4,057,029 | 8 | 2010-10-30T02:47:44Z | [
"python",
"docstring"
] | I have a wrapper function that returns a function. Is there a way to programmatically set the docstring of the returned function? If I could write to `__doc__` I'd do the following:
```
def wrapper(a):
def add_something(b):
return a + b
add_something.__doc__ = 'Adds ' + str(a) + ' to `b`'
return add... | I would pass the docstring into the factory function and use `type` to manually construct the class.
```
def make_testcase(filename, myfunc, docstring):
def test_something(self):
data = loadmat(filename)
result = myfunc(data)
self.assertTrue(result > 0)
clsdict = {'test_something': tes... |
How do I programmatically set the docstring? | 4,056,983 | 27 | 2010-10-30T02:22:01Z | 4,835,557 | 33 | 2011-01-29T06:41:15Z | [
"python",
"docstring"
] | I have a wrapper function that returns a function. Is there a way to programmatically set the docstring of the returned function? If I could write to `__doc__` I'd do the following:
```
def wrapper(a):
def add_something(b):
return a + b
add_something.__doc__ = 'Adds ' + str(a) + ' to `b`'
return add... | An `instancemethod` gets its docstring from its `__func__`. Change the docstring of `__func__` instead. (The `__doc__` attribute of functions are are writeable.)
```
>>> class Foo(object):
... def bar(self):
... pass
...
>>> Foo.bar.__func__.__doc__ = "A super docstring"
>>> help(Foo.bar)
Help on method ba... |
WTforms: Error "field not present" | 4,058,308 | 5 | 2010-10-30T10:42:24Z | 4,127,185 | 7 | 2010-11-08T19:19:59Z | [
"python",
"forms",
"flask",
"wtforms",
"flask-wtforms"
] | Hi I have a form class which looks like below:-
```
class UserCreateForm(wtf.Form):
name=wtf.TextField('Name',validators=[validators.Required(),username_check])
email=wtf.TextField('Email')
userimage=wtf.FileField(u'Upload Image',validators=[checkfile])
```
The custom validator function " checkfile" looks... | Solved this finally , had to replace `field.data` in the validator with `field.file` and then access its attributes using `field.file.filename`. |
How to handle JSON request in bottle? | 4,058,335 | 8 | 2010-10-30T10:50:26Z | 8,387,069 | 14 | 2011-12-05T14:46:57Z | [
"python",
"json",
"bottle"
] | I need to get data from JSON, transfered by ajax from client. Basically I used something like this:
```
@route('/ajax')
def serve_ajax():
return main.parse_request(json.dumps(dict(request.GET)))
```
Where main.parse\_request is a function, that contains some logics to deal with variables in JSON (it is a main pro... | Now since bottle **0.10**, the `request.json` is ready for use :)
Document is [here](http://bottlepy.org/docs/0.10/api.html?highlight=json#bottle.BaseRequest.json). |
How to handle JSON request in bottle? | 4,058,335 | 8 | 2010-10-30T10:50:26Z | 13,882,537 | 12 | 2012-12-14T16:22:46Z | [
"python",
"json",
"bottle"
] | I need to get data from JSON, transfered by ajax from client. Basically I used something like this:
```
@route('/ajax')
def serve_ajax():
return main.parse_request(json.dumps(dict(request.GET)))
```
Where main.parse\_request is a function, that contains some logics to deal with variables in JSON (it is a main pro... | **request.json** is limited by [MEMFILE\_MAX](http://bottlepy.org/docs/dev/api.html?highlight=memfile#bottle.BaseRequest.MEMFILE_MAX).
Another way works if request data is larger than MEMFILE\_MAX
```
json.load(request.body)
``` |
Split list of names into alphabetic dictionary, in Python | 4,058,967 | 3 | 2010-10-30T13:50:15Z | 4,059,017 | 7 | 2010-10-30T14:03:37Z | [
"python",
"list",
"dictionary"
] | List.
```
['Chrome', 'Chromium', 'Google', 'Python']
```
Result.
```
{'C': ['Chrome', 'Chromium'], 'G': ['Google'], 'P': ['Python']}
```
I can make it work like this.
```
alphabet = dict()
for name in ['Chrome', 'Chromium', 'Google', 'Python']:
character = name[:1].upper()
if not character in alphabet:
alp... | Anything wrong with this? I agree with Antoine, the oneliner solution is rather cryptic.
```
import collections
alphabet = collections.defaultdict(list)
for word in words:
alphabet[word[0].upper()].append(word)
``` |
Generate all possible strings from a list of token | 4,059,550 | 5 | 2010-10-30T16:21:41Z | 4,059,588 | 13 | 2010-10-30T16:28:19Z | [
"python",
"bash",
"language-agnostic"
] | Hi
I have a list of tokens, like:
```
hel
lo
bye
```
and i want to generate all the possible combinations of such strings, like:
```
hello
lohel
helbye
byehel
lobye
byelo
```
Language is not important, any advice?
I found <http://stackoverflow.com/questions/3846123/generating-permutations-using-bash>, but this mak... | Your example can be written in Python as
```
from itertools import combinations
print list(combinations(["hel", "lo", "bye"], 2))
```
To combine the output to strings again:
```
print ["".join(a) for a in combinations(["hel", "lo", "bye"], 2)]
```
If you interested in the actual implementation of this function, hav... |
zeromq persistence patterns | 4,059,706 | 9 | 2010-10-30T16:58:26Z | 4,374,385 | 7 | 2010-12-07T07:49:46Z | [
"python",
"persistent",
"zeromq"
] | Who has to manages the persistent in the ZeroMQ?
When we use the ZeroMQ clients in Python language, what are the plug-ins/modules available to manage the persistent?
I would like to know the patterns to use the ZeroMQ. | As far as i know, Zeromq does not have any persistence. It is out of scope for it and needs to be handled by the end user. Just like serializing the message.
In C#, i have used db4o to add persistence. Typically i persist the object in its raw state, then serialize it and send it to ZMQ socket. Btw, this was for PUB/SU... |
How to reliably open a file in the same directory as a Python script | 4,060,221 | 57 | 2010-10-30T19:05:52Z | 4,060,259 | 68 | 2010-10-30T19:13:30Z | [
"python",
"directory"
] | I used to open files that were in the same directory as the currently running Python script by simply using a command like
```
open("Some file.txt", "r")
```
However, I discovered that when the script was run in Windows by double-clicking it, it would try to open the file from the wrong directory.
Since then I've us... | I always use:
```
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
```
The `join()` call prepends the current working directory, but the documentation says that if some path is absolute, all other paths left of it are dropped. Therefore, `getcwd()` is dropped when `dirname(__... |
How to reliably open a file in the same directory as a Python script | 4,060,221 | 57 | 2010-10-30T19:05:52Z | 5,475,156 | 9 | 2011-03-29T15:38:53Z | [
"python",
"directory"
] | I used to open files that were in the same directory as the currently running Python script by simply using a command like
```
open("Some file.txt", "r")
```
However, I discovered that when the script was run in Windows by double-clicking it, it would try to open the file from the wrong directory.
Since then I've us... | To quote from the Python documentation:
> As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read... |
TypeError: 'int' object is unsubscriptable | 4,060,572 | 8 | 2010-10-30T20:35:56Z | 4,060,579 | 13 | 2010-10-30T20:38:26Z | [
"python"
] | In python I get this error:
```
TypeError: 'int' object is unsubscriptable
```
This happens at the line:
```
sectorcalc[i][2]= ((today[2]/yesterday[2])-1)
```
I couldn't find a good definition of unsubscriptable for python anywhere.
```
for quote in sector[singlestock]:
i+=1
if i < len(sector):
... | **The "[2]" in today[2] is called subscript.**
> This usage is possible only if "today"
> is a sequence type. Native sequence
> types - List, string, tuple etc
Since you are getting an error - 'int' object is unsubscriptable. It means that "today" is not a sequence but an int type object.
**You will need to find / d... |
Finding points on a rectangle at a given angle | 4,061,576 | 11 | 2010-10-31T02:28:36Z | 4,062,485 | 24 | 2010-10-31T09:08:21Z | [
"python",
"math",
"graphics",
"geometry"
] | I'm trying to draw a gradient in a rectangle object, with a given angle (Theta), where the ends of the gradient are touching the perimeter of the rectangle.

I thought that using tangent would work, but I'm having trouble getting the kinks out. Is there an easy algorithm th... | Let's call **a** and **b** your rectangle sides, and **(x0,y0)** the coordinates of your rectangle center.
You have four regions to consider:

```
Region from to Where
=============================================================... |
trouble getting pylint to find inherited methods in pylons/SA models | 4,061,720 | 12 | 2010-10-31T03:28:01Z | 4,231,480 | 9 | 2010-11-20T06:15:36Z | [
"python",
"sqlalchemy",
"pylons",
"pylint"
] | I have a Pylons app that I'm using SqlAlchemy declarative models for. In order to make the code a bit cleaner I add a .query onto the SA Base and inherit all my models from that.
So in my app.model.meta I have
```
Base = declarative_base()
metadata = Base.metadata
Session = scoped_session(sessionmaker())
Base.query ... | Best I could find for this is to pass pylint a list of classes to ignore this check on. It'll still do other checks for these classes, you'll just have to maintain a list of these somewhere:
`pylint --ignored-classes=MyModel1,MyModel2 myfile.py`
I know it's not ideal, but there's something about the way that sqlalche... |
How Do I Suppress or Disable Warnings in reSTructuredText? | 4,061,773 | 6 | 2010-10-31T03:48:38Z | 4,061,798 | 9 | 2010-10-31T04:00:44Z | [
"python",
"restructuredtext",
"docutils"
] | I'm working on a CMS in Python that uses reStructuredText (via docutils) to format content. Alot of my content is imported from other sources and usually comes in the form of unformatted text documents. reST works great for this because it makes everything look pretty sane by default.
One problem I am having, however,... | ```
def reST2HTML( str ):
parts = core.publish_parts(
source = str,
writer_name = 'html',
settings_overrides={'report_level':'quiet'},
)
return parts['body_pre_docinfo'] + parts['fragment']
``` |
How do I access part of a list in Jinja2 | 4,062,226 | 17 | 2010-10-31T07:33:36Z | 4,100,795 | 11 | 2010-11-04T20:04:45Z | [
"python",
"templates",
"jinja2"
] | I'm trying to use the jinja2 templating langauge to return the last n(say, 5) posts in my posts list:
```
{% for recent in site.posts|reverse|slice(5) %}
{% for post in recent %}
<li> <a href="/{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}
{% endfor %}
```
This is returning the whole list tho... | this is a bit simpler I think without the use of the *slice* filter:
```
{% for post in site.posts | reverse | list[0:4] %}
<li>» <a href="/{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}
```
another way is to use the [loop controls extension](http://jinja.pocoo.org/docs/dev/extensions/#loop-controls):... |
How do I access part of a list in Jinja2 | 4,062,226 | 17 | 2010-10-31T07:33:36Z | 16,154,389 | 9 | 2013-04-22T18:45:03Z | [
"python",
"templates",
"jinja2"
] | I'm trying to use the jinja2 templating langauge to return the last n(say, 5) posts in my posts list:
```
{% for recent in site.posts|reverse|slice(5) %}
{% for post in recent %}
<li> <a href="/{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}
{% endfor %}
```
This is returning the whole list tho... | I had the same problem too. It's a simple answer. This retrieves the last five items in site.posts:
```
{% for recent in site.posts[-5:] %}
{% for post in recent %}
<li> <a href="/{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}
{% endfor %}
``` |
OpenCL for Python | 4,063,690 | 11 | 2010-10-31T15:21:55Z | 4,063,779 | 11 | 2010-10-31T15:47:58Z | [
"python",
"opencl"
] | I'm looking for a good OpenCL wrapper\library for Python, with good documentation. I tried to search some... but couldn't find one good enough. | The most popular and best documented option seems to be [PyOpenCL](http://mathema.tician.de/software/pyopencl). It claims to be a complete wrapper for OpenCL and the documentation looks good. |
Is there such a thing for Django as there is Heroku for Ruby on Rails | 4,064,029 | 16 | 2010-10-31T16:50:06Z | 5,125,546 | 16 | 2011-02-26T06:58:23Z | [
"python",
"django",
"heroku"
] | Is there a cloud based development for Django, such as there is cloud based development and hosting environment for Ruby / [heroku](http://heroku.com/) | **[ep.io](http://www.ep.io/)** provides WSGI hosting Heroku style. It's from [Andrew Godwin](http://www.aeracode.org/) of [South](http://south.aeracode.org/) fame. From their website:
> This is ep.io, the hosted WSGI hosting and deployment solution. We take your Django, Flask, Pylons or other WSGI code, run all the an... |
Is there such a thing for Django as there is Heroku for Ruby on Rails | 4,064,029 | 16 | 2010-10-31T16:50:06Z | 6,970,323 | 15 | 2011-08-07T02:25:49Z | [
"python",
"django",
"heroku"
] | Is there a cloud based development for Django, such as there is cloud based development and hosting environment for Ruby / [heroku](http://heroku.com/) | [Heroku itself is now for Django](http://news.heroku.com/news_releases/heroku-announces-major-new-version-celadon-cedar-includes-new-process-model-full-nodejs-). It supports Django with the new Cedar "run anything" release.
I now use Heroku for a few django projects. Setup, including adding a postgres DB and deploymen... |
2d array of lists in python | 4,064,277 | 4 | 2010-10-31T17:48:58Z | 4,064,327 | 9 | 2010-10-31T17:59:09Z | [
"python",
"arrays",
"matrix",
"2d"
] | I am trying to create a 2d matrix so that each cell contains a list of strings.
Matrix dimensions are known before the creation and I need to have access to any element from the beginning (not populating a matrix dynamically). => I think some kind of preallocation of space is needed.
For example, I would like to have ... | Just as you wrote it:
```
>>> matrix = [["str1", "str2"], ["str3"], ["str4", "str5"]]
>>> matrix
[['str1', 'str2'], ['str3'], ['str4', 'str5']]
>>> matrix[0][1]
'str2'
>>> matrix[0][1] += "someText"
>>> matrix
[['str1', 'str2someText'], ['str3'], ['str4', 'str5']]
>>> matrix[0].extend(["str6"])
>>> matrix[0]
['str1', ... |
What's the advantage of stack-less Python's microthread than Lua's coroutine in state machine implementation for game? | 4,064,594 | 4 | 2010-10-31T18:58:42Z | 4,096,850 | 9 | 2010-11-04T12:55:04Z | [
"python",
"lua",
"coroutine",
"stackless",
"python-stackless"
] | Any advantage on stack-less python implentation than Lua's coroutine?
What's the difference of them? | stackless python and tasklets (I haven't done any programming with stackless python, but I have read some of the details about how it is implemented):
Pros:
1. Lightweight most of the time.
2. Has scheduler to manage which tasklet get resume next after the current one yields.
3. Support for Preemptive Scheduling. (i.... |
Django model inheritance: create sub-instance of existing instance (downcast)? | 4,064,808 | 33 | 2010-10-31T19:46:18Z | 4,065,189 | 46 | 2010-10-31T21:19:33Z | [
"python",
"django",
"inheritance"
] | I'm trying to integrate a 3rd party Django app that made the unfortunate decision to inherit from `django.contrib.auth.models.User`, which is a big no-no for pluggable apps. Quoting [Malcolm Tredinnick](http://groups.google.com/group/django-users/msg/baa3afd55b14ad68):
> More importantly, though, just as in Python you... | This should work:
```
extended_user = ExtendedUser(user_ptr_id=auth_user.pk)
extended_user.__dict__.update(auth_user.__dict__)
extended_user.save()
```
Here you're basically just copying over the values from the auth\_user version into the extended\_user one, and re-saving it. Not very elegant, but it works. |
Python statement uses excessive amounts of RAM | 4,064,818 | 2 | 2010-10-31T19:48:01Z | 4,064,829 | 12 | 2010-10-31T19:52:15Z | [
"python",
"memory-management"
] | This simple statement:
```
zip(xrange(0, 11614321), xrange(0, 11627964))
```
...is eating most of my RAM. (>150 MiB!) Why?
**Edit:** Ah, re-reading the docs, I see `zip` returns a list, not an iterable. Anything like `zip` that returns an iterable?
---
The larger picture: I'm iterating over two large arrays of fil... | Use [izip](http://docs.python.org/library/itertools.html#itertools.izip) from itertools |
Using gevent with python xmlrpclib | 4,065,079 | 4 | 2010-10-31T21:00:05Z | 4,066,535 | 8 | 2010-11-01T03:50:47Z | [
"python",
"gevent",
"xmlrpclib"
] | Is it possible to use python's standard libs xmlrpclib with gevent? Currently i'm tried to use monkey.patch\_all(), but without success.
```
from gevent import monkey
monkey.patch_all()
import gevent
import time
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
import urllib2
def fetch(url):
... | The socket is patched fine, but there are other problems with your code.
First, this
```
def fetch(url):
g = gevent.spawn(urllib2.urlopen, url)
return g.get().read()
```
is the same as
```
def fetch(url):
return urllib2.urlopen(url).read()
```
You're spawning a new greenlet here but then blocking the c... |
Safe dereferencing in Python | 4,065,085 | 6 | 2010-10-31T21:00:34Z | 4,065,309 | 9 | 2010-10-31T21:47:00Z | [
"python",
"groovy",
null,
"nullpointerexception"
] | Groovy has a nice operator for safe dereferencing, which helps to avoid NullPointerExceptions:
```
variable?.method()
```
The `method` will only be called, if `variable` is not `null`.
Is there a way to do the same in Python? Or do I have to write `if variable: variable.method()`? | 1. No, there isn't.
2. But to check for `None`, you don't write `if x:`, you write `if x is None:`. This is an important distinction - `x` evaluates to `False` for quite a few values that are propably perfectly valid (most notably 0-equivalent numbers and empty collections), whereas `x is None` **only** evaluates to `T... |
How to programmatically merge text files with potential conflicts (ala git or svn, etc)? | 4,065,541 | 8 | 2010-10-31T22:42:57Z | 4,065,636 | 8 | 2010-10-31T23:06:45Z | [
"python",
"command-line",
"text",
"merge",
"diff"
] | As part of a larger project, I want the ability to take two bodies of text and hand them to a merge algorithm which returns either an auto-merged result (in cases where the changes are not conflicting) or throws an error and (potentially) produces a single text document with the conflicting changes highlighted.
Basica... | You're probably searching for merge algorithms like 3-way merging, which you can find in many open source projects, e.g. in the bazaar VCS ([merge3.py source](http://bazaar.launchpad.net/~bzr-pqm/bzr/bzr.dev/annotate/head%3A/bzrlib/merge3.py#L232)). |
reading a file in python | 4,065,594 | 4 | 2010-10-31T22:56:02Z | 4,065,602 | 14 | 2010-10-31T22:58:55Z | [
"python",
"string",
"csv"
] | I am new to python been using it for graphics but never done it for other problems. My question is how to read this file which is tab or space delimited and has headers in python, i know how to do comma delimted file but not done this on?
ID YR MO DA YrM MoM DaM
100 2010 2 20 2010 8 2010 30
110 2010 4 30 2010 9 20... | Does the same technique for csv modules does not work?
```
import csv
reader = csv.reader(open("filename"), delimiter="\t")
```
*Delimiter can be "\s" or "\t".*
You can also use DictReader this way:
```
f = open(filename, '')
try:
reader = csv.DictReader(f)
for row in reader:
print row
finally:
... |
Python/Numpy: Convert list of bools to unsigned int | 4,065,737 | 12 | 2010-10-31T23:28:06Z | 4,066,807 | 10 | 2010-11-01T05:25:32Z | [
"python",
"list",
"numpy",
"scipy"
] | 1. What is the fastest (or most "Pythonic") way to convert
```
x = [False, False, True, True]
```
into `12`? (If there is such a way.)
2. What if `x` were instead a `numpy.array` of bools? Is there a special command for that?
I have a large m-by-n array of booleans, where each n-element row represents a ... | Taking various ideas from various other answers, here's another way to do it:
```
sum(1<<i for i, b in enumerate(x) if b)
```
It is quite fast in my tests - right up with the numpy method for large number of bits even though it overflows like crazy. I used liori's testing module for testing. Steve's method, with the ... |
compilation error. AttributeError: 'module' object has no attribute 'init' | 4,065,800 | 5 | 2010-10-31T23:44:14Z | 4,065,823 | 11 | 2010-10-31T23:50:37Z | [
"python",
"compiler-errors"
] | Here is my small program,
```
import pygame
pygame.init()
```
Here is my compilation command.
> python myprogram.py
Compilation error,
```
File "game.py", line 1, in
import pygame
File "/home/ubuntu/Documents/pygame.py", line 2, in
pygame.init()
AttributeError: 'module' object has no attribute 'init'... | Delete the "pygame.py" file in your Documents folder, it is shadowing the real pygame you've installed.
It looks like you first saved your small test program as "pygame.py", then renamed it to "game.py". |
Proper data structure to represent a Sudoku puzzle? | 4,066,075 | 3 | 2010-11-01T01:16:01Z | 4,066,090 | 7 | 2010-11-01T01:20:36Z | [
"python",
"data-structures",
"graph",
"sudoku"
] | What would be a smart data structure to use to represent a Sudoku puzzle? I.e. a 9X9 square where each "cell" contains either a number or a blank.
Special considerations include:
* Ability to compare across row, column, and in 3X3 "group
* Ease of implementation (specifically in Python)
* Efficiency (not paramount)
... | Actually, I built such a beast, both a solver and a generator, and I used a 2D array. It worked fine.
You just had to understand the indexes and where they were and that wasn't too difficult to master.
The relative relationships between cells in a row doesn't change depending on the column, same goes for cells in a c... |
Resizing pictures in PIL in Tkinter | 4,066,202 | 4 | 2010-11-01T01:54:01Z | 4,066,264 | 11 | 2010-11-01T02:10:58Z | [
"python",
"windows-7",
"tkinter",
"python-imaging-library"
] | I'm currently using PIL to display images in Tkinter. I'd like to temporarily resize these images so that they can be viewed more easily. How can I go about this?
Snippet:
```
self.pw.pic = ImageTk.PhotoImage(Image.open(self.pic_file))
self.pw.pic_label = TK.Label(self.pw , image=self.pw.pic,borderwidth=0)
s... | Here's what I do and it works pretty well...
```
image = Image.open(Image_Location)
image = image.resize((250, 250), Image.ANTIALIAS) #The (250, 250) is (height, width)
self.pw.pic = ImageTk.PhotoImage(image)
```
There you go :)
EDIT:
Here is my import statement:
```
from Tkinter import *
import tkFont
import Imag... |
How can I find the authoritative DNS server for a domain using dnspython? | 4,066,614 | 8 | 2010-11-01T04:19:52Z | 4,066,624 | 12 | 2010-11-01T04:23:08Z | [
"python",
"dns",
"dnspython"
] | As part of a tool I'm writing I want to have a diagnostic that will tell the user whether they have configured their domain's DNS correctly for a particular service. I want to query the authoritative DNS server for their domain so that I can bypass any cached results. | Here's my attempt at this. It uses the system's standard DNS server for looking up the root server for the top-level domain and for resolving the names of the various DNS servers along the chain, which I think is appropriate because those names would presumably change very infrequently.
```
import dns
import dns.name
... |
Should I be using SQLObject, SQLAlchemy, or SQLAlchemy + Elixir? | 4,066,803 | 10 | 2010-11-01T05:24:53Z | 4,086,760 | 10 | 2010-11-03T11:53:48Z | [
"python",
"sqlalchemy",
"sqlobject",
"python-elixir"
] | I've been using SQLObject for a long while, but noticed that SQLAlchemy has become a lot more popular in the last couple years: <http://www.google.com/trends?q=sqlobject,+sqlalchemy>
Are there compelling reasons to switch to SQLAlchemy? How is its performance relative to SQLObject? Its usability? And what is the added... | I used SqlObject extensively as part of TurboGears 0.9, but switched to SqlAlchemy + elixir as a drop in replacement for SqlObject even before TurboGears did.
Note that even without elixir, SqlAlchemy has it's own declarative style class definitions:
<http://docs.sqlalchemy.org/en/rel_1_0/orm/extensions/declarative/in... |
Scrolling multiple Tkinter listboxes together | 4,066,974 | 5 | 2010-11-01T06:17:25Z | 4,068,275 | 7 | 2010-11-01T10:59:45Z | [
"python",
"listbox",
"scrollbar",
"tkinter",
"mousewheel"
] | I have multiple Tkinter listboxes that I have scrolling together using a single scrollbar, but I'd ALSO like them to scroll together for mousewheel activity over any of the listboxes.
How to do this?
My current code is based on the last pattern discussed here: <http://effbot.org/tkinterbook/listbox.htm> It works fine... | Solve the problem pretty much the same way as you did to connect the two widgets to a single scrollbar: create custom bindings for the mousewheel and have those bindings affect both listboxes rather than just one.
The only real trick is knowing that you get different events for the mousewheel depending on the platform... |
Python - checking on a thread / remove from list | 4,067,786 | 7 | 2010-11-01T09:34:02Z | 4,067,973 | 13 | 2010-11-01T10:07:21Z | [
"python",
"multithreading",
"list"
] | I have a thread which extends Thread. The code looks a little like this;
```
class MyThread(Thread):
def run(self):
# Do stuff
my_threads = []
while has_jobs() and len(my_threads) < 5:
new_thread = MyThread(next_job_details())
new_thread.run()
my_threads.append(new_thread)
for my_thread in my... | As TokenMacGuy says, you should use [`thread.isAlive()`](http://docs.python.org/library/threading.html#threading.Thread.is_alive) to check if a thread is still running. To remove no longer running threads from your list you can use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehe... |
Getting mail attachment to python file object | 4,067,937 | 13 | 2010-11-01T10:03:18Z | 4,114,952 | 32 | 2010-11-06T20:10:18Z | [
"python",
"email"
] | I have got an email multipart message object, and I want to convert the attachment in that email message into python file object. Is this possible? If it is possible, what method or class in Python I should look into to do such task? | I don't really understand what you mean by "email multipart message object". Do you mean an object belonging to the [`email.message.Message`](http://docs.python.org/library/email.message.html#email.message.Message) class?
If that is what you mean, it's straightforward. On a multipart message, the `get_payload` method ... |
Why is python slower compared to Ruby even with this very simple "test"? | 4,068,122 | 2 | 2010-11-01T10:30:46Z | 4,068,222 | 16 | 2010-11-01T10:50:45Z | [
"python",
"ruby",
"testing",
"performance"
] | See <http://stackoverflow.com/questions/4046514/is-there-something-wrong-with-this-python-code-why-does-it-run-so-slow-compared> for my previous attempt at understanding the differences between python and ruby.
As pointed out by igouy the reasoning I came up with for python being slower could be something else than du... | First off, note that the Python version you show is incorrect: you're running this code in Python 2.7, not 3.1 (it's not even valid Python3 code). (FYI, Python 3 is usually slower than 2.)
That said, there's a critical problem in the Python test: you're writing it as global code. You need to write it as a function. It... |
What's the difference of numpy.ndarray.T and numpy.ndarray.transpose() when self.ndim < 2 | 4,068,177 | 7 | 2010-11-01T10:40:33Z | 4,720,628 | 9 | 2011-01-18T05:01:20Z | [
"python",
"numpy"
] | The document [numpy.ndarray.T](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.T.html#numpy-ndarray-t) says
> ndarray.T â Same as self.transpose(), except that self is returned if self.ndim < 2.
Also, ndarray.transpose(\*axes) says
> For a 1-D array, this has no effect.
Doesn't this mean the sam... | Regardless of rank, the `.T` attribute and the `.transpose()` method are the sameâthey both return the transpose of the array.
In the case of a rank 1 array, the `.T` and `.transpose()` don't do anythingâthey both return the array. |
Python: NameError: global name 'foobar' is not defined | 4,068,785 | 22 | 2010-11-01T12:19:43Z | 4,068,795 | 43 | 2010-11-01T12:21:37Z | [
"python",
"namespaces",
"nameerror"
] | I have written the following class:
```
class myClass(object):
def __init__(self):
pass
def foo(self, arg1, arg2):
pp = foobar(self, arg1, arg2)
if pp:
return 42
else
return -666
def foobar(self, arg1, arg2):
if arg1 == arg2:
re... | Python doesn't scope code to the local class automatically; you need to tell it to.
```
pp = self.foobar(arg1, arg2)
```
<http://docs.python.org/tutorial/classes.html> |
How does Python evaluate this expression? | 4,069,366 | 2 | 2010-11-01T13:39:27Z | 4,069,404 | 8 | 2010-11-01T13:44:02Z | [
"python",
"syntax"
] | How does Python evaluate the following expression? `anim1` gets executed after `anim2`. How does a simple + operator that?
```
anim1 = Animation(duration=1, center=(100,100) type='delta')
anim2 = Animation(duration=1, rotation=45 type='delta')
anim = anim1 + anim2
``` | This will call `anim1.__add__(anim2)`.
In order to understand what is happening under the hood you have to inspect the definition of `__add__` method from Animation class. |
Postgres: INSERT if does not exist already | 4,069,718 | 136 | 2010-11-01T14:24:53Z | 4,069,756 | 16 | 2010-11-01T14:28:27Z | [
"python",
"postgresql",
"sql-insert"
] | I'm using Python to write to a postgres database:
```
sql_string = "INSERT INTO hundred (name,name_slug,status) VALUES ("
sql_string += hundred + ", '" + hundred_slug + "', " + status + ");"
cursor.execute(sql_string)
```
But because some of my rows are identical, I get the following error:
```
psycopg2.IntegrityErr... | Unfortunately, `PostgreSQL` supports neither `MERGE` nor `ON DUPLICATE KEY UPDATE`, so you'll have to do it in two statements:
```
UPDATE invoices
SET billed = 'TRUE'
WHERE invoices = '12345'
INSERT
INTO invoices (invoiceid, billed)
SELECT '12345', 'TRUE'
WHERE '12345' NOT IN
(
SELECT in... |
Postgres: INSERT if does not exist already | 4,069,718 | 136 | 2010-11-01T14:24:53Z | 4,070,385 | 36 | 2010-11-01T15:36:30Z | [
"python",
"postgresql",
"sql-insert"
] | I'm using Python to write to a postgres database:
```
sql_string = "INSERT INTO hundred (name,name_slug,status) VALUES ("
sql_string += hundred + ", '" + hundred_slug + "', " + status + ");"
cursor.execute(sql_string)
```
But because some of my rows are identical, I get the following error:
```
psycopg2.IntegrityErr... | One approach would be to create a non-constrained (no unique indexes) table to insert all your data into and do a select distinct from that to do your insert into your hundred table.
So high level would be. I assume all three columns are distinct in my example so for step3 change the NOT EXITS join to only join on the... |
Postgres: INSERT if does not exist already | 4,069,718 | 136 | 2010-11-01T14:24:53Z | 9,939,942 | 8 | 2012-03-30T09:02:24Z | [
"python",
"postgresql",
"sql-insert"
] | I'm using Python to write to a postgres database:
```
sql_string = "INSERT INTO hundred (name,name_slug,status) VALUES ("
sql_string += hundred + ", '" + hundred_slug + "', " + status + ");"
cursor.execute(sql_string)
```
But because some of my rows are identical, I get the following error:
```
psycopg2.IntegrityErr... | You can make use of VALUES - available in Postgres:
```
INSERT INTO person (name)
SELECT name FROM person
UNION
VALUES ('Bob')
EXCEPT
SELECT name FROM person;
``` |
Postgres: INSERT if does not exist already | 4,069,718 | 136 | 2010-11-01T14:24:53Z | 13,342,031 | 207 | 2012-11-12T10:27:16Z | [
"python",
"postgresql",
"sql-insert"
] | I'm using Python to write to a postgres database:
```
sql_string = "INSERT INTO hundred (name,name_slug,status) VALUES ("
sql_string += hundred + ", '" + hundred_slug + "', " + status + ");"
cursor.execute(sql_string)
```
But because some of my rows are identical, I get the following error:
```
psycopg2.IntegrityErr... | > How can I write an 'INSERT unless this row already exists' SQL statement?
There is a nice way of doing conditional INSERT in PostgreSQL:
```
INSERT INTO example_table
(id, name)
SELECT 1, 'John'
WHERE
NOT EXISTS (
SELECT id FROM example_table WHERE id = 1
);
```
**CAVEAT** This approach is not ... |
Postgres: INSERT if does not exist already | 4,069,718 | 136 | 2010-11-01T14:24:53Z | 18,654,976 | 10 | 2013-09-06T09:54:37Z | [
"python",
"postgresql",
"sql-insert"
] | I'm using Python to write to a postgres database:
```
sql_string = "INSERT INTO hundred (name,name_slug,status) VALUES ("
sql_string += hundred + ", '" + hundred_slug + "', " + status + ");"
cursor.execute(sql_string)
```
But because some of my rows are identical, I get the following error:
```
psycopg2.IntegrityErr... | If you just want to insert or not insert (and not update otherwise), you can do it like this (using the invoice example):
```
INSERT INTO invoices (invoiceid, billed) SELECT '12345', 'TRUE'
WHERE NOT EXISTS (SELECT 1 FROM invoices WHERE invoiceid = '12345')
``` |
Postgres: INSERT if does not exist already | 4,069,718 | 136 | 2010-11-01T14:24:53Z | 31,742,830 | 47 | 2015-07-31T09:33:23Z | [
"python",
"postgresql",
"sql-insert"
] | I'm using Python to write to a postgres database:
```
sql_string = "INSERT INTO hundred (name,name_slug,status) VALUES ("
sql_string += hundred + ", '" + hundred_slug + "', " + status + ");"
cursor.execute(sql_string)
```
But because some of my rows are identical, I get the following error:
```
psycopg2.IntegrityErr... | Postgres 9.5 (released since 2016-01-07) offers an ["upsert"](https://wiki.postgresql.org/wiki/UPSERT) command:
```
INSERT ... ON CONFLICT DO NOTHING/UPDATE
```
It solves many of the subtle problems you can run into when using concurrent operation, which some other answers propose. |
Python datetime.strptime() Eating lots of CPU Time | 4,070,900 | 5 | 2010-11-01T16:28:53Z | 4,080,021 | 11 | 2010-11-02T16:48:27Z | [
"python",
"optimization",
"datetime"
] | I have some log parsing code that needs to turn a timestamp into a datetime object. I am using datetime.strptime but this function is using a lot of cputime according to cProfile's cumtime column. The timestamps are in the format of `01/Nov/2010:07:49:33`.
The current function is:
```
new_entry['time'] = datetime.str... | If those are fixed width formats then there is no need to parse the line - you can use slicing and a dictionary lookup to get the fields directly.
```
month_abbreviations = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4,
'May': 5, 'Jun': 6, 'Jul': 7, 'Aug': 8,
'Sep': 9, 'Oct': 10... |
Infinite yield problem | 4,071,207 | 5 | 2010-11-01T17:05:45Z | 4,071,228 | 16 | 2010-11-01T17:08:55Z | [
"python",
"generator"
] | Here is my simple code
```
class Fibonacci:
@staticmethod
def series():
fprev = 1
fnext = 1
yield fnext
while True:
yield fnext
fprev,fnext = fnext,fprev+fnext
under10 = (i for i in Fibonacci.series() if i<10)
for i in under10 :
print i
```
It's abs... | How should the interpreter know that all future numbers will be < 10? It would have to either *know* (somehow) that itâs churning out the Fibonacci series, or it would have to inspect the whole series.
It canât do the first, so it does the second.
You can fix this by using [`itertools.takewhile`](http://docs.pyth... |
Split by comma and strip whitespace in Python | 4,071,396 | 149 | 2010-11-01T17:29:37Z | 4,071,407 | 258 | 2010-11-01T17:30:38Z | [
"python",
"whitespace",
"strip"
] | I have some python code that splits on comma, but doesn't strip the whitespace:
```
>>> string = "blah, lots , of , spaces, here "
>>> mylist = string.split(',')
>>> print mylist
['blah', ' lots ', ' of ', ' spaces', ' here ']
```
I would rather end up with whitespace removed like this:
```
['blah', 'lots', 'o... | Use list comprehension -- simpler, and just as easy to read as a `for` loop.
```
my_string = "blah, lots , of , spaces, here "
[x.strip() for x in my_string.split(',')]
```
**See:** [Python docs on List Comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions)
[A good 2 second expla... |
Split by comma and strip whitespace in Python | 4,071,396 | 149 | 2010-11-01T17:29:37Z | 9,091,238 | 8 | 2012-02-01T05:30:22Z | [
"python",
"whitespace",
"strip"
] | I have some python code that splits on comma, but doesn't strip the whitespace:
```
>>> string = "blah, lots , of , spaces, here "
>>> mylist = string.split(',')
>>> print mylist
['blah', ' lots ', ' of ', ' spaces', ' here ']
```
I would rather end up with whitespace removed like this:
```
['blah', 'lots', 'o... | I know this has already been answered, but if you end doing this a lot, regular expressions may be a better way to go:
```
>>> import re
>>> re.sub(r'\s', '', string).split(',')
['blah', 'lots', 'of', 'spaces', 'here']
```
The `\s` matches any whitespace character, and we just replace it with an empty string `''`. Yo... |
Split by comma and strip whitespace in Python | 4,071,396 | 149 | 2010-11-01T17:29:37Z | 12,760,144 | 17 | 2012-10-06T13:18:58Z | [
"python",
"whitespace",
"strip"
] | I have some python code that splits on comma, but doesn't strip the whitespace:
```
>>> string = "blah, lots , of , spaces, here "
>>> mylist = string.split(',')
>>> print mylist
['blah', ' lots ', ' of ', ' spaces', ' here ']
```
I would rather end up with whitespace removed like this:
```
['blah', 'lots', 'o... | Split using a regular expression. Note I made the case more general with leading spaces. The list comprehension is to remove the null strings at the front and back.
```
>>> import re
>>> string = " blah, lots , of , spaces, here "
>>> pattern = re.compile("^\s+|\s*,\s*|\s+$")
>>> print([x for x in pattern.split(st... |
Python Turtle Module- Saving an image | 4,071,633 | 14 | 2010-11-01T17:54:11Z | 6,049,340 | 18 | 2011-05-18T18:27:57Z | [
"python",
"vector-graphics",
"turtle-graphics"
] | I would like to figure out how to save a bitmap or vector graphics image after creating a drawing with python's turtle module. After a bit of googling I can't find an easy answer. I did find a module called [canvas2svg](http://wm.ite.pl/proj/canvas2svg/index.html), but I'm very new to python and I don't know how to ins... | ```
from Tkinter import *
from turtle import *
import turtle
forward(100)
ts = turtle.getscreen()
ts.getcanvas().postscript(file="duck.eps")
```
This will help you; I had the same problem, I Googled it, but solved it by reading the source of the turtle module.
The canvas (tkinter) object has the postscript functio... |
Python BeautifulSoup XML Parsing | 4,071,696 | 5 | 2010-11-01T18:02:03Z | 4,093,940 | 14 | 2010-11-04T04:39:17Z | [
"python",
"xml",
"parsing"
] | I've written a simple script to parse XML chat logs using the BeautifulSoup module. The standard soup.prettify() works ok except chat logs have a lot of fluff in them. You can see both the script code and some of the XML input file I'm working with below:
**Code**
```
import sys
from BeautifulSoup import BeautifulSou... | BeautifulSoup makes getting at attributes and values in xml really simple. I tweaked your example function to use these features.
```
import sys
from BeautifulSoup import BeautifulSoup as Soup
def parseLog(file):
file = sys.argv[1]
handler = open(file).read()
soup = Soup(handler)
for message in soup.f... |
How to get absolute url in Pylons? | 4,071,837 | 4 | 2010-11-01T18:21:57Z | 4,079,680 | 8 | 2010-11-02T16:13:50Z | [
"python",
"routes",
"pylons"
] | How to get absolute url in Pylons ? | To generate a fully qualified URL with Routes, use `qualified=True` keyword in `url()` call.
Example:
```
print url("blog", id=123, qualified=True)
# depending on routing configuration,
# would print something like "http://somehost/blog/123"
```
If your web application is running behind load balancer or reverse pr... |
Python - datetime of a specific timezone | 4,071,924 | 11 | 2010-11-01T18:35:40Z | 4,072,048 | 20 | 2010-11-01T18:48:31Z | [
"python",
"datetime",
"timezone"
] | I am having the hardest time trying to get the current time in EDT timezone.
```
print datetime.time(datetime.now()).strftime("%H%M%S")
```
datetime.now([tz]) has an optional tz argument, but it has to be of type datetime.tzinfo... I have not ben able to figure out how to define a tzinfo object for Eastern timezone..... | I am not very conversent about the EDT time zone but this example should serve your purpose.
```
import datetime
```
datetime.datetime.now must be passed the time zone info which should be of type datetime.tzinfo. Here is a class that implements that with some of the required functions. I am providing no day light sa... |
Python - datetime of a specific timezone | 4,071,924 | 11 | 2010-11-01T18:35:40Z | 4,072,100 | 8 | 2010-11-01T18:52:55Z | [
"python",
"datetime",
"timezone"
] | I am having the hardest time trying to get the current time in EDT timezone.
```
print datetime.time(datetime.now()).strftime("%H%M%S")
```
datetime.now([tz]) has an optional tz argument, but it has to be of type datetime.tzinfo... I have not ben able to figure out how to define a tzinfo object for Eastern timezone..... | The [`tzinfo`](http://docs.python.org/library/datetime.html#tzinfo-objects) class only defines an interface, you will need to implement it yourself (see the documentation for an example) or use a third-party module which implements it, like [`pytz`](http://pytz.sourceforge.net/).
**Edit**: Sorry, I missed that you don... |
How to change a widget's font style without knowing the widget's font family/size? | 4,072,150 | 24 | 2010-11-01T18:58:39Z | 4,073,037 | 25 | 2010-11-01T21:06:16Z | [
"python",
"user-interface",
"fonts",
"tkinter"
] | Is there a way to change a *Tkinter* widget's font style without knowing the widget's font family and font size?
Use case: We create our UI using standard *Tkinter* widgets (*Label*, *Entry*, *Text*, etc). While our application runs we may want to dynamically change the font style of these widgets to bold and/or itali... | There's a much better way than using `.config()` to change your application font, especially if your goal is to change the font for a whole group of widgets (or all widgets).
One of the really great features of Tk is the notion of "named fonts". The beauty of named fonts is, if you update the font, all widgets that us... |
How to change a widget's font style without knowing the widget's font family/size? | 4,072,150 | 24 | 2010-11-01T18:58:39Z | 26,798,185 | 11 | 2014-11-07T09:36:26Z | [
"python",
"user-interface",
"fonts",
"tkinter"
] | Is there a way to change a *Tkinter* widget's font style without knowing the widget's font family and font size?
Use case: We create our UI using standard *Tkinter* widgets (*Label*, *Entry*, *Text*, etc). While our application runs we may want to dynamically change the font style of these widgets to bold and/or itali... | Even shorter for just one Label:
```
from Tkinter import *
import Tkinter as tk
root = tk.Tk()
# font="-weight bold" does your thing
example = Label(root, text="This is a bold example.", font="-weight bold")
example.pack()
root.mainloop()
``` |
Insert an element between two adjacent list elements which meet a condition | 4,072,496 | 3 | 2010-11-01T19:45:08Z | 4,072,544 | 9 | 2010-11-01T19:51:56Z | [
"python"
] | In python, what's a clean way to insert an element between any two elements that meet a condition?
A call like:
```
insert_between([1,2,3,4,7,8,9,15,16], 0, lambda x,y: x + 1 != y)
```
should produce:
```
[1,2,3,4,0,7,8,9,0,15,16]
```
Is there a better way than to iterate and append to second list? | ```
>>> def insert_between(iterable, fill, cond):
... iterable = iter(iterable)
... prev = next(iterable)
... yield prev
... for cur in iterable:
... if cond(prev, cur):
... yield fill
... yield cur
... prev = cur
...
>>>
>>> list(insert_between([1... |
Better way to write this if statement? | 4,072,871 | 2 | 2010-11-01T20:42:31Z | 4,072,978 | 10 | 2010-11-01T20:58:32Z | [
"python",
"comparison"
] | I have this tkinter GUI, and I need to get the values from the entries and compare.
`self.hystInt.get()` is the way to access the string in the string variable in the Entry. \*I have to write this for every variable so it ends up looking really ugly.
```
if (self.hystInt.get().isdigit() and int(self.hystInt.get()) >= ... | ```
def validate(num):
try:
return 200 <= int(num) <= 500
except ValueError:
return False
```
Simple is good! |
Python Tkinter Embed Matplotlib in GUI | 4,073,660 | 14 | 2010-11-01T22:35:42Z | 4,077,424 | 18 | 2010-11-02T12:05:16Z | [
"python",
"canvas",
"grid",
"matplotlib",
"tkinter"
] | I'm trying to embed a plot in my Tkinter GUI coded in Python. I believe the code below succeeds in simply putting a graph into a canvas, but I don't have any control of the canvas location within the GUI grid. I want to be able to have a subsection of my GUI be the plot...not the entirety of it. How can I position this... | You don't have any other widgets so it's hard to know where you want other widgets. Here's what I can tell you though: by doing `dataPlot.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)` you are asking Tkinter to fill the screen with the plot. This, because you ask it to fill in all directions (`fill=BOTH`) and exp... |
Writing a parallel programming framework, what have I missed? | 4,073,695 | 16 | 2010-11-01T22:40:30Z | 4,074,015 | 8 | 2010-11-01T23:42:16Z | [
"python",
"parallel-processing",
"python-2.x"
] | **Clarification**: As per some of the comments, I should clarify that this is intended as a simple framework to allow execution of programs that are *naturally* parallel (so-called embarrassingly parallel programs). It isn't, and never will be, a solution for tasks which require communication or synchronisation between... | I have actually written something that probably satisfies your needs: [jug](http://luispedro.org/software/jug). If it does not solve your problems, I promise you I'll fix any bugs you find.
The architecture is slightly different: workers all run the same code, but they effectively generate a similar dictionary and ask... |
Access from external to python development server | 4,073,977 | 9 | 2010-11-01T23:33:35Z | 4,073,993 | 17 | 2010-11-01T23:37:23Z | [
"python",
"django"
] | I can't access externally to python development server, I have a very small django project running on my machine, and now I want to enable computers in the same LAN have access to it, but it can't do.
There is no firewall running on my machine. Is there a way around this? | How are you running the server?
Have you tried something like this?
```
manage.py runserver 0.0.0.0:8080
```
From [the documentation](http://docs.djangoproject.com/en/1.2/ref/django-admin/):
> Note that the default IP address, 127.0.0.1, is not accessible from other machines on your network. To make your developme... |
Django - Access ForeignKey value without hitting database | 4,074,038 | 6 | 2010-11-01T23:49:16Z | 4,074,078 | 8 | 2010-11-02T00:00:08Z | [
"python",
"django",
"foreign-key-relationship"
] | I have a django model like so:
```
class Profile_Tag(models.Model):
profile = models.ForeignKey(Profile)
tag = models.ForeignKey(Tag)
```
and a view like so:
```
pts = Profile_Tag.objects.all()
for pt in pts:
print pt.profile.id
```
is there any way to access the profile foreignKey without hitting the d... | You can do something like this:
```
pt_ids = Profile_Tag.objects.values_list('profile', flat=True)
```
This will return you list of IDs. For model instance, there's another way:
```
pts = Profile_Tag.objects.all()
for pt in pts:
print pt.profile_id
``` |
What is getattr() exactly and how do I use it? | 4,075,190 | 110 | 2010-11-02T05:45:12Z | 4,075,211 | 34 | 2010-11-02T05:48:36Z | [
"python",
"getattr"
] | I was [reading about the `getattr()` function](http://diveintopython.net/power_of_introspection/getattr.html). The problem is that I still can't grasp the idea of its usage. The only thing I understand about `getattr()` is that `getattr(li, "pop")` is the same as calling `li.pop`.
I didn't understand when the book men... | You can view a full example here:
* <http://www.diveintopython.net/power_of_introspection/index.html>
Introspection can be used for different purpose, the one presented in 'Dive Into Python' is simply a way to add functionality (plug-in) dynamically in your application.
By **dynamically** I mean without doing modifi... |
What is getattr() exactly and how do I use it? | 4,075,190 | 110 | 2010-11-02T05:45:12Z | 4,075,549 | 10 | 2010-11-02T07:02:26Z | [
"python",
"getattr"
] | I was [reading about the `getattr()` function](http://diveintopython.net/power_of_introspection/getattr.html). The problem is that I still can't grasp the idea of its usage. The only thing I understand about `getattr()` is that `getattr(li, "pop")` is the same as calling `li.pop`.
I didn't understand when the book men... | Here's a quick and dirty example of how a class could fire different versions of a save method depending on which operating system it's being executed on using `getattr()`.
```
import os
class Log(object):
def __init__(self):
self.os = os.name
def __getattr__(self, name):
""" look for a 'save'... |
What is getattr() exactly and how do I use it? | 4,075,190 | 110 | 2010-11-02T05:45:12Z | 4,076,010 | 30 | 2010-11-02T08:32:53Z | [
"python",
"getattr"
] | I was [reading about the `getattr()` function](http://diveintopython.net/power_of_introspection/getattr.html). The problem is that I still can't grasp the idea of its usage. The only thing I understand about `getattr()` is that `getattr(li, "pop")` is the same as calling `li.pop`.
I didn't understand when the book men... | A pretty common use case for `getattr` is mapping data to functions.
For instance, in a web framework like Django or Pylons, `getattr` makes it straightforward to map a web request's URL to the function that's going to handle it. If you look under the hood of Pylons's routing, for instance, you'll see that (by default... |
What is getattr() exactly and how do I use it? | 4,075,190 | 110 | 2010-11-02T05:45:12Z | 4,076,099 | 118 | 2010-11-02T08:48:20Z | [
"python",
"getattr"
] | I was [reading about the `getattr()` function](http://diveintopython.net/power_of_introspection/getattr.html). The problem is that I still can't grasp the idea of its usage. The only thing I understand about `getattr()` is that `getattr(li, "pop")` is the same as calling `li.pop`.
I didn't understand when the book men... | Objects in Python can have attributes (actually, every object has built-in attributes -- data attributes and methods (functions are values, i.e. objects, too) to work with those).
For example you have an object `person`, that has several attributes: `name`, `gender`, etc.
You access these attributes (be it methods or... |
What is getattr() exactly and how do I use it? | 4,075,190 | 110 | 2010-11-02T05:45:12Z | 18,538,330 | 51 | 2013-08-30T17:22:36Z | [
"python",
"getattr"
] | I was [reading about the `getattr()` function](http://diveintopython.net/power_of_introspection/getattr.html). The problem is that I still can't grasp the idea of its usage. The only thing I understand about `getattr()` is that `getattr(li, "pop")` is the same as calling `li.pop`.
I didn't understand when the book men... | For me, getattr is easiest to explain this way:
**It allows you to call methods based on the contents of a string instead of typing the method name.**
For example, you cannot do this:
```
obj = MyObject()
for x in ['foo', 'bar']:
obj.x()
```
because x is not of the type "builtin", but "str". However, you CAN do... |
A more pythonic way to write this expression? | 4,077,249 | 8 | 2010-11-02T11:41:35Z | 4,077,309 | 41 | 2010-11-02T11:49:18Z | [
"python",
"sorting"
] | I'm supposed to take a list of words and sort it, except I need to group all Strings that begin with 'x' first.
Here's what I got:
```
list_1 = []
list_2 = []
for word in words:
list_1.append(word) if word[0] == 'x' else list_2.append(word)
return sorted(list_1) + sorted(list_2)
```
But I have a feeling there is... | ```
>>> words = ['xoo', 'dsd', 'xdd']
>>> sorted(words, key=lambda x: (x[0] != 'x', x))
['xdd', 'xoo', 'dsd']
```
Explanation: the key function returns a pair (tuple). The first element is `False` or `True`, depending on whether the first char in the string is `'x'`. `False` sorts before `True`, so strings starting wi... |
A more pythonic way to write this expression? | 4,077,249 | 8 | 2010-11-02T11:41:35Z | 4,077,322 | 9 | 2010-11-02T11:50:11Z | [
"python",
"sorting"
] | I'm supposed to take a list of words and sort it, except I need to group all Strings that begin with 'x' first.
Here's what I got:
```
list_1 = []
list_2 = []
for word in words:
list_1.append(word) if word[0] == 'x' else list_2.append(word)
return sorted(list_1) + sorted(list_2)
```
But I have a feeling there is... | First: stop saying "pythonic" when you mean "clean". It's just a cheesy buzzword.
Don't use terniary expressions like that; it's meant to be used as part of an expression, not as flow control. This is cleaner:
```
for word in words:
if word[0] == 'x':
list_1.append(word)
else:
list_2.append(wo... |
Perl or Python: Convert date from dd/mm/yyyy to yyyy-mm-dd | 4,077,896 | 11 | 2010-11-02T13:06:57Z | 4,077,960 | 16 | 2010-11-02T13:11:39Z | [
"python",
"perl",
"date",
"text-processing"
] | I have lots of dates in a column in a CSV file that I need to convert from dd/mm/yyyy to yyyy-mm-dd format. For example 17/01/2010 should be converted to 2010-01-17.
How can I do this in Perl or Python? | ```
>>> from datetime import datetime
>>> datetime.strptime('02/11/2010', '%d/%m/%Y').strftime('%Y-%m-%d')
'2010-11-02'
```
or more hackish way (that doesn't check for validity of values):
```
>>> '-'.join('02/11/2010'.split('/')[::-1])
'2010-11-02'
>>> '-'.join(reversed('02/11/2010'.split('/')))
'2010-11-02'
``` |
Perl or Python: Convert date from dd/mm/yyyy to yyyy-mm-dd | 4,077,896 | 11 | 2010-11-02T13:06:57Z | 4,078,817 | 29 | 2010-11-02T14:47:39Z | [
"python",
"perl",
"date",
"text-processing"
] | I have lots of dates in a column in a CSV file that I need to convert from dd/mm/yyyy to yyyy-mm-dd format. For example 17/01/2010 should be converted to 2010-01-17.
How can I do this in Perl or Python? | If you are guaranteed to have well-formed data consisting of nothing else but a singleton date in the DD-MM-YYYY format, then this works:
```
# FIRST METHOD
my $ndate = join("-" => reverse split(m[/], $date));
```
That works on a `$date` holding "07/04/1776" but fails on "this 17/01/2010 and that 01/17/2010 there". I... |
Perl or Python: Convert date from dd/mm/yyyy to yyyy-mm-dd | 4,077,896 | 11 | 2010-11-02T13:06:57Z | 4,080,369 | 11 | 2010-11-02T17:26:12Z | [
"python",
"perl",
"date",
"text-processing"
] | I have lots of dates in a column in a CSV file that I need to convert from dd/mm/yyyy to yyyy-mm-dd format. For example 17/01/2010 should be converted to 2010-01-17.
How can I do this in Perl or Python? | Use Time::Piece (in core since 5.9.5), very similar to the Python solution accepted, as it provides the strptime and strftime functions:
```
use Time::Piece;
my $dt_str = Time::Piece->strptime('13/10/1979', '%d/%m/%Y')->strftime('%Y-%m-%d');
```
or
```
$ perl -MTime::Piece
print Time::Piece->strptime('13/10/1979', '... |
combine python-mode with org-mode for emacs | 4,079,648 | 11 | 2010-11-02T16:10:51Z | 4,090,710 | 10 | 2010-11-03T19:11:12Z | [
"python",
"emacs",
"org-mode",
"folding"
] | I combined org-mode with lisp-mode to achieve beautiful code folding in emacs for lisp code: [lisp-orgi-mode](http://github.com/tinku99/ahk-org-mode/raw/master/lisp-org.el).
Basically, I use ';' instead of '\*' as the heading character. For comments, I just put a space before the ';', making it ' ;' so it doesn't count... | I use [hideshow-org](https://github.com/secelis/hideshow-org) ([and a small introduction here](http://gnufool.blogspot.com/2009/03/make-hideshow-behave-more-like-org-mode.html)) for this purpose, and I think it works really, really good.
These are some additional, but useful snippets:
```
(dolist (hook (list 'c-mode-... |
combine python-mode with org-mode for emacs | 4,079,648 | 11 | 2010-11-02T16:10:51Z | 4,093,889 | 7 | 2010-11-04T04:25:57Z | [
"python",
"emacs",
"org-mode",
"folding"
] | I combined org-mode with lisp-mode to achieve beautiful code folding in emacs for lisp code: [lisp-orgi-mode](http://github.com/tinku99/ahk-org-mode/raw/master/lisp-org.el).
Basically, I use ';' instead of '\*' as the heading character. For comments, I just put a space before the ';', making it ' ;' so it doesn't count... | Ok, I got outline-minor-mode working nicely with the following outline-regexp: "[ \t]\*# \|[ \t]+\(class\|def\|if\|elif\|else\|while\|for\|try\|except\|with\) "
Now I get code folding using both python syntax and comment lines as headings.
Would it be possible to adapt your code for using tab to call 'indent-for-tab-... |
Hiding Axis Labels | 4,079,795 | 17 | 2010-11-02T16:25:24Z | 4,098,603 | 52 | 2010-11-04T16:01:25Z | [
"python",
"matplotlib",
"tkinter"
] | I'm trying to hide the axis labels on the first subplot at 211.
I'd like to label the figure, not just a subplot (reference: "Isub Event Characteristics").
How can I control font properties like size, font, color?
```
f = Figure()
vdsvgsPlot = f.add_subplot(211)
vdsvgsPlot.plot(theLister()[3],theLister()[0])
vdsvgsPl... | You have several different questions here... Let me break them up a bit...
By "hide the axis labels on the first subplot" do you mean the actual axis labels (which aren't there unless you specify them), the tick labels (i.e. the numbers along the axis), the axis ticks, or all of the above?
If you mean "all of the abo... |
A good wxpython GUI builder? | 4,079,866 | 26 | 2010-11-02T16:33:19Z | 4,079,943 | 23 | 2010-11-02T16:41:05Z | [
"python",
"wxpython",
"gui-builder"
] | Is there a good wxpython GUI builder that does not require much coding, like in the case of the form builder in MS visual studio ? | There is [wxGlade](http://wxglade.sourceforge.net/). Here is a screenshot:

and [wxFormBuilder](http://wxformbuilder.org/)

Also, have a look here for more alternatives: [GUI Programming in Python](http://wiki.python.org/m... |
How to handle timeouts with httplib (python 2.6)? | 4,079,983 | 5 | 2010-11-02T16:44:36Z | 4,081,306 | 12 | 2010-11-02T19:18:57Z | [
"python",
"httplib"
] | I'm using httplib to access an api over https and need to build in exception handling in the event that the api is down.
Here's an example connection:
```
connection = httplib.HTTPSConnection('non-existent-api.com', timeout=1)
connection.request('POST', '/request.api', xml, headers={'Content-Type': 'text/xml'})
respo... | > Even better, what's the best way to gracefully handle the problem of a 3rd-party api being down?
what's mean API is down , API return http 404 , 500 ...
or you mean when the API can't be reachable ?
first of all i don't think you can know if a web service in general is down before trying to access it so i will rec... |
Python: os.stat().st_size gives different value than du | 4,080,254 | 6 | 2010-11-02T17:13:09Z | 4,080,292 | 7 | 2010-11-02T17:17:54Z | [
"python",
"linux"
] | I'm creating a utility that will walk through directories and get the sizes of child directories and files for all directories and store the value. However, the sizes aren't computed correctly.
Here's my class, which automatically recurses through all sub-directories:
```
class directory:
'''
Class that automatically... | Consider this file foo
```
-rw-rw-r-- 1 unutbu unutbu 25334 2010-10-31 12:55 foo
```
It consists of 25334 bytes.
tune2fs tells me foo resides on a filesystem with block size 4096 bytes:
```
% sudo tune2fs -l /dev/mapper/vg1-OS1
...
Block size: 4096
...
```
Thus, the smallest file on the filesystem wi... |
Python - optimize by not importing at module level? | 4,080,749 | 4 | 2010-11-02T18:10:58Z | 4,080,823 | 15 | 2010-11-02T18:18:56Z | [
"python",
"optimization",
"premature-optimization",
"python-import"
] | In a framework such as Django, I'd imagine that if a user lands on a page (running a view function called "some\_page"), and you have 8 imports at the top of module that are irrelevant to that view, you're wasting cycles on those imports. My questions are:
1. Is it a large enough amount of resources to make an impact ... | No, don't do this. In a normal python execution environment on the web (mod\_wsgi, gunicorn, etc.) when your process starts those imports will be executed, and then all subsequent requests will not re-execute the script. If you put the imports inside the functions they'll have to be processed every time the function is... |
Input variables in Python 3 | 4,081,002 | 3 | 2010-11-02T18:37:27Z | 4,081,037 | 8 | 2010-11-02T18:42:06Z | [
"python",
"input",
"python-3.x"
] | Is it possible to have a user input equal to a variable for tasks that involve chemical elements.
For example, Carbon has the molecular mass 12, but i do not want the use to input 12, They should input 'C'. but as the input turns this into a string, it is not possible to lik this to the variable C = 12.
Is there any ... | You could change your code like this:
```
>>> masses = {'C': 12}
>>> element = input('element symbol:')
element symbol:C
>>> masses[element]
12
>>> multiplier = input('how many?')
how many?5
>>> multiplier
'5' # string
>>> masses[element] * int(multiplier)
60
``` |
How to modify list entries during for loop? | 4,081,217 | 43 | 2010-11-02T19:04:29Z | 4,081,234 | 36 | 2010-11-02T19:07:16Z | [
"python"
] | Now I know that it is not safe to modify the list during an iterative looping. However, suppose I have a list of strings, and I want to strip the strings themselves. Does replacement of mutable values count as modification? | It's considered poor form. Use a list comprehension instead, with slice assignment if you need to retain existing references to the list.
```
a = [1, 3, 5]
b = a
a[:] = [x + 2 for x in a]
print b
``` |
How to modify list entries during for loop? | 4,081,217 | 43 | 2010-11-02T19:04:29Z | 4,082,739 | 43 | 2010-11-02T22:39:27Z | [
"python"
] | Now I know that it is not safe to modify the list during an iterative looping. However, suppose I have a list of strings, and I want to strip the strings themselves. Does replacement of mutable values count as modification? | Since the loop below only modifies elements already seen, it would be considered acceptable:
```
a = ['a',' b', 'c ', ' d ']
for i, s in enumerate(a):
a[i] = s.strip()
print a # ['a', 'b', 'c', 'd']
```
Which is different from:
```
a[:] = [s.strip() for s in a]
```
in that it doesn't require the creation of a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.