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 |
|---|---|---|---|---|---|---|---|---|---|
Extension method for python built-in types! | 6,738,987 | 21 | 2011-07-18T20:26:34Z | 6,739,060 | 17 | 2011-07-18T20:32:46Z | [
"python"
] | is it possible to add extension method to python built-in types?
I know that I can add extension method to defined type by simply adding new method by . as following:
```
class myClass:
pass
myClass.myExtensionMethod = lambda self,x:x * 2
z = myClass()
print z.myExtensionMethod(10)
```
But is any way to adding e... | No. Types defined in C cannot be monkeypatched. |
Extension method for python built-in types! | 6,738,987 | 21 | 2011-07-18T20:26:34Z | 6,739,207 | 9 | 2011-07-18T20:44:46Z | [
"python"
] | is it possible to add extension method to python built-in types?
I know that I can add extension method to defined type by simply adding new method by . as following:
```
class myClass:
pass
myClass.myExtensionMethod = lambda self,x:x * 2
z = myClass()
print z.myExtensionMethod(10)
```
But is any way to adding e... | Nope, you gotta subclass!
```
>>> import string
>>> class MyString(str):
... def disemvowel(self):
... return MyString(string.translate(self, None, "aeiou"))
...
>>> s = MyString("this is only a test")
>>> s.disemvowel()
'ths s nly tst'
```
---
Or more specific to your example
```
>>> class MyList(lis... |
Extension method for python built-in types! | 6,738,987 | 21 | 2011-07-18T20:26:34Z | 15,975,791 | 40 | 2013-04-12T15:54:10Z | [
"python"
] | is it possible to add extension method to python built-in types?
I know that I can add extension method to defined type by simply adding new method by . as following:
```
class myClass:
pass
myClass.myExtensionMethod = lambda self,x:x * 2
z = myClass()
print z.myExtensionMethod(10)
```
But is any way to adding e... | It can be done in pure Python with this incredibly clever module:
<https://pypi.python.org/pypi/forbiddenfruit>
For example:
```
import functools
import ctypes
import __builtin__
import operator
class PyObject(ctypes.Structure):
pass
Py_ssize_t = hasattr(ctypes.pythonapi, 'Py_InitModule4_64') and ctypes.c_int6... |
DictCursor doesn't seem to work under psycopg2 | 6,739,355 | 24 | 2011-07-18T20:59:48Z | 6,739,495 | 12 | 2011-07-18T21:11:53Z | [
"python",
"postgresql",
"dictionary",
"psycopg2"
] | I haven't worked with psycopg2 before but I'm trying to change the cursor factory to DictCursor so that fetchall or fetchone will return a dictionary instead of a list.
I created a test script to make things simple and only test this functionality. Here's my little bit of code that I feel should work
```
import psyco... | ```
res = cur.fetchall()
```
makes `res` a list of `psycopg2.extras.DictRow`s. If you do something like
```
for row in cur:
print(row['column_name'])
```
you'll be able to access the data with `dict`-like syntax. |
DictCursor doesn't seem to work under psycopg2 | 6,739,355 | 24 | 2011-07-18T20:59:48Z | 9,230,872 | 43 | 2012-02-10T16:10:48Z | [
"python",
"postgresql",
"dictionary",
"psycopg2"
] | I haven't worked with psycopg2 before but I'm trying to change the cursor factory to DictCursor so that fetchall or fetchone will return a dictionary instead of a list.
I created a test script to make things simple and only test this functionality. Here's my little bit of code that I feel should work
```
import psyco... | Use RealDictCursor:
```
cur = conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor)
cur.execute("SELECT * from review")
res = cur.fetchall()
```
This gives you a list with rows as real python dictionaries instead of "advanced psycopg2 list". |
Learning Python: If condition executing all the time | 6,739,453 | 3 | 2011-07-18T21:07:55Z | 6,739,472 | 11 | 2011-07-18T21:09:39Z | [
"python"
] | I am learning python and i can't figure out why the following program is printing **your number is greater than what i thought** even when the guessed number is smaller. is it like in python, it is comparing strings rather the numbers ?
```
number = 32
tries = 1
print "I have chosen a number, you have to guess it."
g... | `raw_input` will return a string. You need to parse it into a number for the compare to work properly. I think that's just `int(raw_input(...))` |
Combining NumPy arrays | 6,740,311 | 8 | 2011-07-18T22:45:29Z | 6,740,350 | 21 | 2011-07-18T22:51:15Z | [
"python",
"arrays",
"numpy"
] | I have two 20x100x3 [NumPy](http://en.wikipedia.org/wiki/NumPy) arrays which I want to combine into a 40 x 100 x 3 array, that is, just add more lines to the array. I am confused by which function I want: is it vstack, hstack, column\_stack or maybe something else? | I believe it's vstack you want
```
p=array_2
q=array_2
p=numpy.vstack([p,q])
``` |
Combining NumPy arrays | 6,740,311 | 8 | 2011-07-18T22:45:29Z | 6,740,606 | 12 | 2011-07-18T23:25:27Z | [
"python",
"arrays",
"numpy"
] | I have two 20x100x3 [NumPy](http://en.wikipedia.org/wiki/NumPy) arrays which I want to combine into a 40 x 100 x 3 array, that is, just add more lines to the array. I am confused by which function I want: is it vstack, hstack, column\_stack or maybe something else? | One of the best ways of learning is experimenting, but I would say you want `np.vstack` although there are other ways of doing the same thing:
```
a = np.ones((20,100,3))
b = np.vstack((a,a))
print b.shape # (40,100,3)
```
or
```
b = np.concatenate((a,a),axis=0)
```
**EDIT**
Just as a note, on my machine for the... |
Combining NumPy arrays | 6,740,311 | 8 | 2011-07-18T22:45:29Z | 6,767,394 | 8 | 2011-07-20T19:31:22Z | [
"python",
"arrays",
"numpy"
] | I have two 20x100x3 [NumPy](http://en.wikipedia.org/wiki/NumPy) arrays which I want to combine into a 40 x 100 x 3 array, that is, just add more lines to the array. I am confused by which function I want: is it vstack, hstack, column\_stack or maybe something else? | Might be worth mentioning that
```
np.concatenate((a1, a2, ...), axis=0)
```
is the general form and vstack and hstack are specific cases. I find it easiest to just know which dimension I want to stack over and provide that as the argument to np.concatenate. |
underlying data structure for float in python | 6,740,418 | 6 | 2011-07-18T23:00:44Z | 6,740,565 | 7 | 2011-07-18T23:20:18Z | [
"python",
"floating-point-precision"
] | Got a question regarding to the underlying data structure of float (and precision) in Python:
```
>>> b = 1.4 + 2.3
>>> b
3.6999999999999997
>>> c = 3.7
>>> c
3.7000000000000002
>>> print b, c
3.7 3.7
>>> b == c
False
```
it seems the values of b and c are machine dependent, they are the numbers that closest to t... | For the answer to your first question, take a look at the following (slightly condensed) code from Python's source:
```
#define PREC_REPR 17
#define PREC_STR 12
void PyFloat_AsString(char *buf, PyFloatObject *v) {
format_float(buf, 100, v, PREC_STR);
}
void PyFloat_AsReprString(char *buf, PyFloatObj... |
board-drawing code to move an oval | 6,740,855 | 2 | 2011-07-19T00:00:48Z | 6,789,351 | 19 | 2011-07-22T11:32:34Z | [
"python",
"tkinter",
"tk",
"python-2.7"
] | I am working on a python checkers game for college. I have the board drawn, using tk, but I can't seem to implement a movement function for the pieces. If anyone see any errors in my code, or can offer help, I would appreciate. Here is the complete source. Thanks in advance.
I know that this draws the checker pieces. ... | You can move an item on a canvas using the [coords](http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.coords-method) and/or [move](http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.move-method) methods to change the coordinates from what they are to what you want them to be.
Here's a simple example showing... |
Convert Unicode to UTF-8 Python | 6,740,865 | 4 | 2011-07-19T00:02:10Z | 6,741,448 | 10 | 2011-07-19T01:48:21Z | [
"python",
"database",
"unicode",
"utf-8"
] | I am working with a database that has throughout it scattered characters like this: ââ¬â¢. I need to take this from the database, convert it to UTF-8, and then import it into a different database, using python. When printed to the Windows Command Prompt, these characters look like this: \xe2\u20ac\u2122. I have trie... | Always *decode* on input, and *encode* on output. (There ought to be handy mnemonic for this: perhaps "*take your code [coat] off when you come indoors*".)
Decode on input: You say that the database encoding is "UTF\_8\_bin". Are you using [MySQL-Python](http://mysql-python.sourceforge.net/MySQLdb.html)? If so, then y... |
Creating a dictionary from a csv file? | 6,740,918 | 39 | 2011-07-19T00:09:26Z | 6,740,963 | 15 | 2011-07-19T00:15:28Z | [
"python",
"csv",
"dictionary",
"list-comprehension"
] | I am trying to create a dictionary from a csv file. The first column of the csv file contains unique keys and the second column contains values. Each row of the csv file represents a unique key, value pair within the dictionary. I tried to use the [`csv.DictReader`](https://docs.python.org/3/library/csv.html#csv.DictRe... | ```
import csv
reader = csv.reader(open('filename.csv', 'r'))
d = {}
for row in reader:
k, v = row
d[k] = v
``` |
Creating a dictionary from a csv file? | 6,740,918 | 39 | 2011-07-19T00:09:26Z | 6,740,968 | 54 | 2011-07-19T00:16:44Z | [
"python",
"csv",
"dictionary",
"list-comprehension"
] | I am trying to create a dictionary from a csv file. The first column of the csv file contains unique keys and the second column contains values. Each row of the csv file represents a unique key, value pair within the dictionary. I tried to use the [`csv.DictReader`](https://docs.python.org/3/library/csv.html#csv.DictRe... | I believe the syntax you were looking for is as follows:
```
with open('coors.csv', mode='r') as infile:
reader = csv.reader(infile)
with open('coors_new.csv', mode='w') as outfile:
writer = csv.writer(outfile)
mydict = {rows[0]:rows[1] for rows in reader}
```
Alternately, for python <= 2.7.1,... |
Creating a dictionary from a csv file? | 6,740,918 | 39 | 2011-07-19T00:09:26Z | 18,957,077 | 7 | 2013-09-23T10:33:30Z | [
"python",
"csv",
"dictionary",
"list-comprehension"
] | I am trying to create a dictionary from a csv file. The first column of the csv file contains unique keys and the second column contains values. Each row of the csv file represents a unique key, value pair within the dictionary. I tried to use the [`csv.DictReader`](https://docs.python.org/3/library/csv.html#csv.DictRe... | You can also use numpy for this.
```
from numpy import loadtxt
key_value = loadtxt("filename.csv", delimiter=",")
mydict = { k:v for k,v in key_value }
``` |
Add quotes to every list elements | 6,741,185 | 18 | 2011-07-19T00:59:05Z | 6,741,230 | 34 | 2011-07-19T01:06:46Z | [
"python"
] | I'm very new to python. I need a simple and clear script to add quotes to every list elements. Let me explain more. Here is the my code.
```
parameters = ['a', 'b', 'c']
query = "SELECT * FROM foo WHERE bar IN (%s)" % (', '.join(parameters))
```
I want to use this to query. But result is invalid query. Here is the re... | A naive solution would be to iterate over your `parameters` list and append quotes to the beginning and end of each element:
```
(', '.join('"' + item + '"' for item in parameters))
```
Note: this is vulnerable to SQL injection (whether coincidental or deliberate). A better solution is to let the database quote and i... |
Add quotes to every list elements | 6,741,185 | 18 | 2011-07-19T00:59:05Z | 6,741,238 | 9 | 2011-07-19T01:07:36Z | [
"python"
] | I'm very new to python. I need a simple and clear script to add quotes to every list elements. Let me explain more. Here is the my code.
```
parameters = ['a', 'b', 'c']
query = "SELECT * FROM foo WHERE bar IN (%s)" % (', '.join(parameters))
```
I want to use this to query. But result is invalid query. Here is the re... | For simple parameters, the following should work:
```
query = "SELECT * FROM foo WHERE bar IN %s" % repr(tuple(map(str,parameters)))
```
This may break down when the parameter names themselves include quotes, as the escaping rules are different. |
Using Python Fabric without the command-line tool (fab) | 6,741,523 | 17 | 2011-07-19T02:05:05Z | 8,344,580 | 16 | 2011-12-01T16:16:05Z | [
"python",
"fabric"
] | Altough Fabric documentations refers to a way of using the library for SSH access without requiring the fab command-line tool and/or tasks, I can't seem to manage a way to do it.
I want to run this file (*example.py*) by only executing '*python example.py*':
```
env.hosts = [ "example.com" ]
def ps():
run("ps")
p... | I ended up doing this:
```
from fabric.api import env
from fabric.api import run
class FabricSupport:
def __init__ (self):
pass
def run(self, host, port, command):
env.host_string = "%s:%s" % (host, port)
run(command)
myfab = FabricSupport()
myfab.run('example.com', 22, 'uname')
```... |
Getting around, numpy objects mismatch error in python | 6,743,158 | 4 | 2011-07-19T06:35:27Z | 6,743,184 | 14 | 2011-07-19T06:38:09Z | [
"python",
"arrays",
"matrix",
"numpy",
"mismatch"
] | I'm having a problem with multiplying two big matrices in python using numpy.
I have a (15,7) matrix and I want to multipy it by its transpose, i.e. AT(7,15)\*A(15\*7) and mathemeticaly this should work, but I get an error :
*ValueError:shape mismatch:objects cannot be broadcast to a single shape*
I'm using numpy in ... | You've probably represented the matrices as arrays. You can either convert them to matrices with `np.asmatrix`, or use `np.dot` to do the matrix multiplication:
```
>>> X = np.random.rand(15 * 7).reshape((15, 7))
>>> X.T * X
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: operands ... |
How to sort files in a directory before reading? | 6,743,407 | 3 | 2011-07-19T07:05:47Z | 6,743,512 | 7 | 2011-07-19T07:16:09Z | [
"python",
"sorting",
"file-io"
] | I am working with a program that writes output to a csv file based on the order that files are read in from a directory. However with a large number of files with the endings 1,2,3,4,5,6,7,8,9,10,11,12. My program actually reads the files by I guess alphabetical ordering: 1,10,11,12....,2,20,21.....99. The problem is t... | ```
files = ['String.ext.ext2.1.txt', 'String.ext.ext2.12.txt', 'String.ext.ext2.2.txt']
# files: coming from os.listdir() sorted alphabetically, thus not numerically
sorted_files = sorted(files, key=lambda x: int(x.split('.')[3]))
# returns: ['String.ext.ext2.1.txt', 'String.ext.ext2.2.txt', 'String.ext.ext2.12.txt']... |
Replace current process with invocation of subprocess? | 6,743,567 | 12 | 2011-07-19T07:21:50Z | 6,743,663 | 16 | 2011-07-19T07:31:49Z | [
"python",
"process",
"replace"
] | In python, is there a way to invoke a new process in, hand it the same context, such as standard IO streams, close the current process, and give control to the invoked process? This would effectively 'replace' the process.
I have a program whose behavior I want to repeat. However, it uses a third-party library, and it... | You may be interested in [`os.execv()`](http://docs.python.org/library/os.html?highlight=execv#os.execv) and friends:
> These functions all execute a new program, replacing the current
> process; they do not return. On Unix, the new executable is loaded
> into the current process, and will have the same process id as ... |
Inverse Cosine in Python | 6,745,464 | 10 | 2011-07-19T10:05:28Z | 6,745,479 | 24 | 2011-07-19T10:06:48Z | [
"python",
"math",
"trigonometry"
] | Apologies if this is straight forward, but I have not found any help in the python manual or google.
I am trying to find the inverse cosine for a value using python.
i.e. cos-1(x)
Does anyone know how to do this?
Thanks | We have the [`acos` function](http://docs.python.org/library/math.html#math.acos), which returns the angle in radians.
```
>>> import math
>>> math.acos(0)
1.5707963267948966
>>> _ * 2 - math.pi
0.0
``` |
Inverse Cosine in Python | 6,745,464 | 10 | 2011-07-19T10:05:28Z | 6,746,308 | 8 | 2011-07-19T11:19:21Z | [
"python",
"math",
"trigonometry"
] | Apologies if this is straight forward, but I have not found any help in the python manual or google.
I am trying to find the inverse cosine for a value using python.
i.e. cos-1(x)
Does anyone know how to do this?
Thanks | To augment the correct answers to use `math.acos`, it is also worth knowing that there are math functions suitable for complex numbers in `cmath`:
```
>>> import cmath
>>> cmath.acos(1j)
(1.5707963267948966-0.88137358701954294j)
```
Stick with `math.acos` if you're only interested in real numbers, |
No handlers could be found for logger | 6,745,615 | 17 | 2011-07-19T10:19:16Z | 7,048,543 | 22 | 2011-08-13T04:19:46Z | [
"python",
"django",
"logging"
] | I am newbie to Django.I am trying for Django logging now. While trying,I am getting this error **["No handlers could be found for logger "sample" "]**..here is my code,
(In my settings.py)
```
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple': {
'for... | The docs are a little unclear about this, but when you use the built-in functionality for specifying logging settings, you don't need to get an instance of the logger.
You would simply do the following:
```
import logging
def empdel(request,id):
e = get_object_or_404(emp, pk=id)
e.delete()
logging.info('... |
one liner for removing blank lines from a file in python? | 6,745,854 | 2 | 2011-07-19T10:40:15Z | 6,745,970 | 8 | 2011-07-19T10:50:05Z | [
"python"
] | I'm looking for one liner which will remove all the blank lines from a file in python.
python equivalent for --> `grep -v '^$' file_name > file_name` | ```
lines = [i for i in open(file_path) if i[:-1]]
```
If writing to another file is a requirement, you can use `file_object.writelines(lines)` with opening file for writing. |
How to store the return value of os.system that it has printed to stdout in python? | 6,746,126 | 3 | 2011-07-19T10:41:57Z | 8,537,931 | 11 | 2011-12-16T17:31:28Z | [
"python"
] | I am writing a python script which checks for number of active connections for a particular IP / port. For this I use os.system( 'my\_command') to grab the output. os.system returns the exit status of the command I've passed it (0 means the command returned without error).
How can I store this value which os.system thr... | ```
a=os.popen("your command").read()
```
new result stored at variable `a` :) |
Combination of all possible cases of a string | 6,747,123 | 5 | 2011-07-19T12:29:21Z | 6,747,267 | 7 | 2011-07-19T12:39:38Z | [
"python",
"string",
"permutation"
] | I am trying to create a program to generate all possible capitalization cases of a string in python. For example, given 'abcedfghij', I want a program to generate:
Abcdefghij
ABcdef..
.
.
aBcdef..
.
ABCDEFGHIJ
And so on. I am trying to find a quick way to do it, but I don't know where to start. | ```
from itertools import product, izip
def Cc(s):
s = s.lower()
for p in product(*[(0,1)]*len(s)):
yield ''.join( c.upper() if t else c for t,c in izip(p,s))
print list(Cc("Dan"))
```
prints:
```
['dan', 'daN', 'dAn', 'dAN', 'Dan', 'DaN', 'DAn', 'DAN']
``` |
Combination of all possible cases of a string | 6,747,123 | 5 | 2011-07-19T12:29:21Z | 6,747,529 | 9 | 2011-07-19T12:57:45Z | [
"python",
"string",
"permutation"
] | I am trying to create a program to generate all possible capitalization cases of a string in python. For example, given 'abcedfghij', I want a program to generate:
Abcdefghij
ABcdef..
.
.
aBcdef..
.
ABCDEFGHIJ
And so on. I am trying to find a quick way to do it, but I don't know where to start. | Similar to Dan's solution, but much simpler:
```
>>> import itertools
>>> def cc(s):
... return (''.join(t) for t in itertools.product(*zip(s.lower(), s.upper())))
...
>>> print list(cc('dan'))
```
```
['dan', 'daN', 'dAn', 'dAN', 'Dan', 'DaN', 'DAn', 'DAN']
``` |
Generating HTML documents in python | 6,748,559 | 21 | 2011-07-19T14:12:17Z | 6,748,854 | 18 | 2011-07-19T14:30:32Z | [
"python",
"html"
] | In python, what is the most elegant way to generate HTML documents. I currently manually append all of the tags to a giant string, and write that to a file. Is there a more elegant way of doing this? | I would suggest using one of the many template languages available for python, for example the one [built into Django](https://docs.djangoproject.com/en/dev/topics/templates/) (you don't have to use the rest of Django to use its templating engine) - a google query should give you plenty of other alternative template im... |
Generating HTML documents in python | 6,748,559 | 21 | 2011-07-19T14:12:17Z | 22,869,282 | 10 | 2014-04-04T17:30:09Z | [
"python",
"html"
] | In python, what is the most elegant way to generate HTML documents. I currently manually append all of the tags to a giant string, and write that to a file. Is there a more elegant way of doing this? | I find [yattag](http://www.yattag.org) to be the most elegant way of doing this.
```
from yattag import Doc
doc, tag, text = Doc().tagtext()
with tag('html'):
with tag('body'):
with tag('p', id = 'main'):
text('some text')
with tag('a', href='/my-url'):
text('some link')
... |
Understanding timedelta | 6,749,294 | 31 | 2011-07-19T14:59:05Z | 6,749,443 | 51 | 2011-07-19T15:09:06Z | [
"python",
"timedelta"
] | Given the python code below, please help me understand what is happening there.
```
start_time = time.time()
time.sleep(42)
end_time = time.time()
uptime = end_time - start_time
human_uptime = str(datetime.timedelta(seconds=int(uptime)))
```
So I get the difference between `start time` and `end time`, on line 5 I r... | Because timedelta is defined like:
```
class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
All arguments are optional and default to 0.
```
You can easily say "Three days and four milliseconds" with optional arguments that way.
```
>>> datetime.timedelta(days=3, ... |
How to query database by id using SqlAlchemy? | 6,750,017 | 24 | 2011-07-19T15:43:42Z | 6,756,723 | 37 | 2011-07-20T03:34:45Z | [
"python",
"sql",
"model",
"sqlalchemy"
] | I need to query a SQLAlchemy database by its `id` something similar to
> User.query.filter\_by(username='peter')
but for id. How do I do this? [Searching over Google and SO didn't help] | Query has a [get function](http://www.sqlalchemy.org/docs/orm/query.html#sqlalchemy.orm.query.Query.get) that supports querying by ID.
For example, to query for an object with ID of 23: `User.query.get(23)` |
how to do re.compile() with a list in python | 6,750,240 | 6 | 2011-07-19T15:59:32Z | 6,750,274 | 18 | 2011-07-19T16:01:39Z | [
"python",
"regex"
] | I have a list of strings in which I want to filter for strings that contains keywords.
I want to do something like:
```
fruit = re.compile('apple', 'banana', 'peach', 'plum', 'pinepple', 'kiwi']
```
so I can then use re.search(fruit, list\_of\_strings) to get only the strings containing fruits, but I'm not sure how ... | You need to turn your fruit list into the string `apple|banana|peach|plum|pineapple|kiwi` so that it is a valid regex, the following should do this for you:
```
fruit_list = ['apple', 'banana', 'peach', 'plum', 'pineapple', 'kiwi']
fruit = re.compile('|'.join(fruit_list))
```
**edit**: As ridgerunner pointed out in c... |
SQLAlchemy - order_by on relationship for join table | 6,750,251 | 6 | 2011-07-19T16:00:37Z | 13,377,228 | 9 | 2012-11-14T10:40:26Z | [
"python",
"sql",
"model",
"sqlalchemy",
"declarative"
] | I'm using declarative SQLAlchemy and I have three models: `Role`, `Permission`, and `RolePermission`. In my `Role` model, I have the following:
```
class Role(Base):
name = Column(u'NAME', VARCHAR(50), nullable=False, unique=True)
permissionLinks = relationship(RolePermission, backref="role", order_by=name)
... | I couldn't make any of these solutions work, however I found an easier way.
```
from sqlalchemy.ext.declarative import declarative_base
class User(Base):
# ....
addresses = relationship("Address",
order_by="desc(Address.email)",
primaryjoin="Address.user_id==U... |
How do I install heapy under python 2.7? | 6,750,563 | 12 | 2011-07-19T16:22:50Z | 6,751,519 | 15 | 2011-07-19T17:38:07Z | [
"python",
"memory-management",
"memory-leaks"
] | It seems the latest version is for 2.6 only.
I'm facing `ImportError: DLL load failed: The specified module could not be found.` and couldn't find any solution around, anybody knows?
Is there any other memory profiler available for python 2.7?
The error traceback:
```
>>> import guppy
>>> from guppy import hpy
>>> ... | I had the same error when I tried to launch python from folder where guppy source files were situated. But out of this directory I had problems with instantiating hpy. Finally I got heapy working on python2.7 by installing it from trunk
```
pip install https://guppy-pe.svn.sourceforge.net/svnroot/guppy-pe/trunk/guppy
... |
Hot-swapping of Python running program | 6,751,263 | 15 | 2011-07-19T17:19:09Z | 6,751,846 | 7 | 2011-07-19T18:03:30Z | [
"python",
"hotswap"
] | The following code allows you to modify the contents of `runtime.py` at run time. In other words, you don't have to interrupt `runner.py`.
```
#runner.py
import time
import imp
def main():
while True:
mod = imp.load_source("runtime", "./runtime.py")
mod.function()
time.sleep(1)
if __name_... | You could poll the runtime.py file, waiting for it to change. Once it changes, just call
```
reload(runtime)
```
Any time I'm debugging a python module, I use this approach in the interactive python command prompt (except I manually call reload(), I don't poll anything).
EDIT:
To detect changes in a file, check out ... |
Can't login to Django /admin interface | 6,751,434 | 12 | 2011-07-19T17:31:42Z | 6,893,335 | 15 | 2011-08-01T00:51:17Z | [
"python",
"django",
"google-app-engine",
"django-nonrel"
] | First of all, I am a newbie. I'm running **Ubuntu 11.04** which comes with **Python 2.7 so I installed Python2.5** in different dir to run **Django-Non-Rel on Google App Engine**.
I did the Guestbook tutorial and now I am trying to add admin access but when I type in correct username:password Django thinks its incorrec... | There is some kind of limitation in django-nonrel.
To create a superuser:
* Stop the local webserver
* Create the superuser
```
python manage.py createsuperuser
```
* Run the webserver again
```
python manage.py runserver
``` |
Python - TypeError: (function) takes exactly 2 arguments (3 given) - but I only gave 2! | 6,751,656 | 3 | 2011-07-19T17:49:57Z | 6,751,680 | 10 | 2011-07-19T17:52:06Z | [
"python"
] | I'm parsing a list of patient visits (csv file). To deal with this, I have a custom set of classes:
```
class Patient:
def __init__(self,Rx,ID):
....
class PtController:
def __init__(self,openCSVFile):
self.dict=DictReader(openCSVFile)
self.currentPt = ''
....
def initNewPt(se... | You do not need to pass `self` directly as in `self.initNewPt(self,firstRow)`, since it is automatically passed implicitly by Python. |
How to replace a double backslash with a single backslash in python? | 6,752,485 | 12 | 2011-07-19T18:51:30Z | 6,752,502 | 9 | 2011-07-19T18:53:10Z | [
"python",
"escaping",
"backslash"
] | I have a string. In that string are double backslashes. I want to replace the double backslashes with single backslashes, so that unicode char codes can be parsed correctly.
```
(Pdb) p fetched_page
'<p style="text-align:center;" align="center"><strong><span style="font-family:\'Times New Roman\', serif;font-size:115%... | I'm not getting the behaviour you describe:
```
>>> x = "\\\\\\\\"
>>> print x
\\\\
>>> y = x.replace('\\\\', '\\')
>>> print y
\\
```
When you see `'\\\\'` in your output, you're seeing twice as many slashes as there are in the string because each on is escaped. The code you wrote should work fine. Trying `print`ing... |
How to replace a double backslash with a single backslash in python? | 6,752,485 | 12 | 2011-07-19T18:51:30Z | 6,752,685 | 16 | 2011-07-19T19:06:59Z | [
"python",
"escaping",
"backslash"
] | I have a string. In that string are double backslashes. I want to replace the double backslashes with single backslashes, so that unicode char codes can be parsed correctly.
```
(Pdb) p fetched_page
'<p style="text-align:center;" align="center"><strong><span style="font-family:\'Times New Roman\', serif;font-size:115%... | You can try `codecs.escape_decode`, this should decode the escape sequences. |
write xml with beautiful soup | 6,753,276 | 3 | 2011-07-19T19:55:27Z | 6,753,385 | 10 | 2011-07-19T20:03:16Z | [
"python",
"beautifulsoup"
] | this may be a truly stupid question but I haven't readily found the answer.
once i modify the xml tree as necessary, how do I write it back out to file?
code:
```
workbook = open("C:\\Users\\rabdel.WINCMPT\\Documents\\Retail Footwear.twb")
soup = BeautifulSoup(workbook)
for dashboard in soup.findAll("dashboard"):
... | Simplest way, get the output as a string and write to file:
```
f = open(workbook.name, "w")
f.write(soup.prettify())
f.close()
``` |
TypeError : Unhashable type | 6,754,102 | 16 | 2011-07-19T21:01:58Z | 6,754,166 | 13 | 2011-07-19T21:07:55Z | [
"python"
] | I am trying to get a list of list of tuples : something like `[ [(1,0),(2,0),(3,0)],[(1,1),(2,1),(3,1)....]]`
I used this statement
```
set([(a,b)for a in range(3)]for b in range(3))
```
But it gives me an error
```
TypeError: unhashable type: 'list'
```
I have 2 questions for the Python Guru's:
a) When I look at ... | You are creating a `set` via `set(...)` call, and `set` needs hashable items. You can't have set of lists. Because list's arent hashable.
`[[(a,b) for a in range(3)] for b in range(3)]` is a list. It's not a hashable type. The `__hash__` you saw in dir(...) isn't a method, it's just None.
A list comprehension returns... |
Pyramid equivalent to Django's syncdb command? | 6,754,465 | 7 | 2011-07-19T21:35:31Z | 6,754,622 | 10 | 2011-07-19T21:55:43Z | [
"python",
"django",
"sqlalchemy",
"web-frameworks",
"pyramid"
] | I noticed in the [Pyramid + SQLAlchemy + URL Dispatch Wiki Tutorial](http://docs.pylonsproject.org/projects/pyramid/1.0/tutorials/wiki2/index.html) that the database is initialized in the main function when the application is run.
```
def main(global_config, **settings):
""" This function returns a WSGI applicatio... | Since Pyramid does not make any assumptions about data models, it does not attempt to manage them for you. This is entirely up to you and what specific data layer you are using.
With respect to using SQLAlchemy, it is possible to manage migrations using the SQLAlchemy-migrate package. When you set this up, it provides... |
Logging in to google using python? | 6,754,709 | 2 | 2011-07-19T22:05:53Z | 24,881,998 | 9 | 2014-07-22T08:08:09Z | [
"python",
"login"
] | I am fairly new to web programing but for the sake of it, I am trying to login to google account not using standard code but as a python application, but it is impossible to do so
has anyone tried to this before? can anyone help? | I made a python class that handle google login and the is able to get any google service page that requires the user to be logged in:
```
class SessionGoogle:
def __init__(self, url_login, url_auth, login, pwd):
self.ses = requests.session()
login_html = self.ses.get(url_login)
soup_login =... |
Exceptions and Python | 6,755,017 | 2 | 2011-07-19T22:45:44Z | 6,755,039 | 7 | 2011-07-19T22:48:22Z | [
"python",
"exception"
] | I'm very new to Python and I have a problem which I thought I had solved but it keeps occurring. I have something similar to the following.
```
def funct1()
dosomestuff
funct2()
def funct2()
dosomestuff
funct3()
def funct3()
dosomestuff
funct1()
def exceptionRecovery()
checksomethings
... | Your program is essentially an infinitely recursive program. You're blowing away Python's call stack with extreme prejudice. |
Exceptions and Python | 6,755,017 | 2 | 2011-07-19T22:45:44Z | 6,755,043 | 9 | 2011-07-19T22:49:00Z | [
"python",
"exception"
] | I'm very new to Python and I have a problem which I thought I had solved but it keeps occurring. I have something similar to the following.
```
def funct1()
dosomestuff
funct2()
def funct2()
dosomestuff
funct3()
def funct3()
dosomestuff
funct1()
def exceptionRecovery()
checksomethings
... | Do you get a stackoverflow exception per chance :) ? Since python does not have tail-call recursion optimization, you can not infinitely nest function calls. For this reason you should consider putting your logic into an infinite while loop.
```
while True:
//logic to call func1, 2, 3 or whatever
``` |
Proper way to reset csv.reader for multiple iterations? | 6,755,460 | 9 | 2011-07-19T23:46:35Z | 6,755,778 | 8 | 2011-07-20T00:41:11Z | [
"python",
"csv",
"iterator"
] | Having an issue with a custom iterator in that it will only iterate over the file once. I am calling `seek(0)` on the relevant file object in between iterations, but `StopIteration` is thrown on the first call to `next()` on the 2nd run through. I feel I am overlooking something obvious, but would appreciate some fresh... | I think that you are better off not trying to do the `.seek(0)` but rather opening the file from the filename each time.
And I don't recommend you just return `self` in the `__iter__()` method. That means you only ever have one instance of your object. I don't know how likely it is for someone to try to use your objec... |
Handle undeclared dict key in Python | 6,755,655 | 7 | 2011-07-20T00:17:22Z | 6,755,668 | 18 | 2011-07-20T00:20:28Z | [
"python",
"exception",
"exception-handling"
] | In my Ruby application I have a hash table:
```
c = {:sample => 1,:another => 2}
```
I can handle the table like this:
```
[c[:sample].nil? , c[:another].nil? ,c[:not_in_list].nil?]
```
I'm trying to do the same thing in Python. I created a new dictionary:
```
c = {"sample":1, "another":2}
```
I couldn't handle t... | In your particular case, you should probably do this instead of comparing with `None`:
```
"not_in_dictionary" in c
```
If you were literally using this code, it will not work:
```
c[:not_in_dictionary] is not None
```
Python doesn't have special `:`keywords for dictionary keys; ordinary strings are used instead.
... |
Check the exit status of last command in ipython | 6,755,794 | 6 | 2011-07-19T23:18:53Z | 6,766,813 | 12 | 2011-07-20T18:40:45Z | [
"python",
"ipython"
] | Does anybody know how to check the status of the last executed command (exit code) in ipython? | It should be stored as `_exit_code` after you run the command (at least in the upcoming v0.11 release). |
Yield in a recursive function | 6,755,869 | 47 | 2011-07-20T00:59:01Z | 6,755,896 | 28 | 2011-07-20T01:03:30Z | [
"python",
"recursion",
"iterator",
"directory-structure",
"yield"
] | I am trying to do something to all the files under a given path. I don't want to collect all the file names beforehand then do something with them, so I tried this:
```
import os
import stat
def explore(p):
s = ''
list = os.listdir(p)
for a in list:
path = p + '/' + a
stat_info = os.lstat(path )
if ... | Use [`os.walk`](http://docs.python.org/library/os.html#os.walk) instead of reinventing the wheel.
In particular, following the examples in the library documentation, here is an untested attempt:
```
import os
from os.path import join
def hellothere(somepath):
for root, dirs, files in os.walk(somepath):
f... |
Yield in a recursive function | 6,755,869 | 47 | 2011-07-20T00:59:01Z | 6,755,918 | 112 | 2011-07-20T01:06:20Z | [
"python",
"recursion",
"iterator",
"directory-structure",
"yield"
] | I am trying to do something to all the files under a given path. I don't want to collect all the file names beforehand then do something with them, so I tried this:
```
import os
import stat
def explore(p):
s = ''
list = os.listdir(p)
for a in list:
path = p + '/' + a
stat_info = os.lstat(path )
if ... | Iterators do not work recursively like that. You have to re-yield each result, by replacing
```
explore(path)
```
with something like
```
for value in explore(path):
yield value
```
[Python 3.3](http://python.org/download/releases/3.3.0/) added the syntax `yield from X`, as proposed in [PEP 380](http://www.pyth... |
Yield in a recursive function | 6,755,869 | 47 | 2011-07-20T00:59:01Z | 6,755,923 | 7 | 2011-07-20T01:07:03Z | [
"python",
"recursion",
"iterator",
"directory-structure",
"yield"
] | I am trying to do something to all the files under a given path. I don't want to collect all the file names beforehand then do something with them, so I tried this:
```
import os
import stat
def explore(p):
s = ''
list = os.listdir(p)
for a in list:
path = p + '/' + a
stat_info = os.lstat(path )
if ... | Change this:
```
explore(path)
```
To this:
```
for subpath in explore(path):
yield subpath
```
Or use `os.walk`, as phooji suggested (which is the better option). |
Yield in a recursive function | 6,755,869 | 47 | 2011-07-20T00:59:01Z | 8,903,271 | 34 | 2012-01-17T23:42:37Z | [
"python",
"recursion",
"iterator",
"directory-structure",
"yield"
] | I am trying to do something to all the files under a given path. I don't want to collect all the file names beforehand then do something with them, so I tried this:
```
import os
import stat
def explore(p):
s = ''
list = os.listdir(p)
for a in list:
path = p + '/' + a
stat_info = os.lstat(path )
if ... | The problem is this line of code:
```
explore(path)
```
What does it do?
* calls `explore` with the new `path`
* `explore` runs, creating a generator
* the generator is returned to the spot where `explore(path)` was executed **. . .**
* and is discarded
Why is it discarded? It wasn't assigned to anything, it wasn't... |
Python: OpenMPI Vs. RabbitMQ | 6,756,630 | 4 | 2011-07-20T03:18:38Z | 6,756,939 | 10 | 2011-07-20T04:16:33Z | [
"python",
"messaging",
"mpi",
"rabbitmq",
"amqp"
] | Suppose that one is interested to write a `python` app where there should be communication between different processes. The communications will be done by sending `strings` and/or `numpy` arrays.
What are the considerations to prefer `OpenMPI` vs. a tool like `RabbitMQ`? | There is no single correct answer to such question. It all depends on a big number of different factors. For example:
1. What kind of communications do you have? Are you sending large packets or small packets, do you need good bandwidth or low latency?
2. What kind of delivery guarantees do you need?
3. OpenMPI can in... |
Python PIL Image.tostring() | 6,756,820 | 4 | 2011-07-20T03:52:22Z | 6,758,117 | 8 | 2011-07-20T06:57:55Z | [
"python",
"python-imaging-library",
"pyopengl"
] | I'm new to Python and PIL. I am trying to follow code samples on how to load an image into to Python through PIL and then draw its pixels using openGL. Here are some line of the code:
```
from Image import *
im = open("gloves200.bmp")
pBits = im.convert('RGBA').tostring()
```
.....
```
glDrawPixels(200, 200, GL_RGB... | I think you were close. Try:
```
pBits = im.convert("RGBA").tostring("raw", "RGBA")
```
The image first has to be converted to RGBA mode in order for the RGBA rawmode packer to be available (see [Pack.c](https://bitbucket.org/effbot/pil-117/src/7493ffdf4aff/libImaging/Pack.c#cl-459) in libimaging). You can check that... |
Importing a function from a class in another file? | 6,757,192 | 22 | 2011-07-20T04:57:54Z | 6,757,225 | 28 | 2011-07-20T05:03:20Z | [
"python",
"class",
"import"
] | I'm writing a Python program for fun but got stuck trying to import a function from a class in another file. Here is my code:
```
#jurassic park mainframe
from random import randint
from sys import exit
from comm_system import Comm_system #the file i want to import from
class Jpark_mainframe(object):
def mainf... | ```
from otherfile import TheClass
theclass = TheClass()
# if you want to return the output of run
return theclass.run()
# if you want to return run itself to be used later
return theclass.run
```
Change the end of comm system to:
```
if __name__ == '__main__':
a_game = Comm_system()
a_game.run()
```
It's ... |
In pyramid how to return 400 response with json data? | 6,757,584 | 7 | 2011-07-20T05:56:25Z | 6,768,681 | 21 | 2011-07-20T21:16:47Z | [
"jquery",
"python",
"pyramid"
] | I have the following jquery code:
```
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
statusCode: {
200: function (data, textStatus, jqXHR) {
console.log(data);
},
201: function (data, textStatus, jqXHR) {
log(data);
... | Well you should probably start off by serializing the `error_dict` using a json library.
```
import json
out = json.dumps(error_dict)
```
Given that you don't give any context on how your view is setup, I can only show you how I would do it:
```
@view_config(route_name='some_route', renderer='json')
def myview(reque... |
How to convert two strings to give you a function name in Python | 6,757,630 | 4 | 2011-07-20T06:01:11Z | 6,757,643 | 7 | 2011-07-20T06:03:23Z | [
"python"
] | If you had two strings, like so ->
```
string1 = "get"
string2 = "Feed"
```
So how would you use these 2 strings to call a function named -> getFeed() ? | Depending on where the function is, you can use one of these:
```
globals()[string1 + string2]()
locals()[string1 + string2]()
``` |
Getting a list from a config file with ConfigParser in Python | 6,759,016 | 4 | 2011-07-20T08:24:53Z | 6,759,256 | 8 | 2011-07-20T08:48:06Z | [
"python",
"list",
"python-3.x",
"configuration-files",
"configparser"
] | I have something like this in my config file (a config option that contains a list of strings):
```
[filters]
filtersToCheck = ['foo', '192.168.1.2', 'barbaz']
```
is there a more elegant (built-in) way to get a list from filtersToCheck instead of removing the brackets, single-quotes, spaces and then using split() to... | You cannot use the python object like a list in the value for the config file. But you can ofcourse have them as comma separated values and once you get it do a split
```
[filters]
filtersToCheck = foo,192.168.1.2,barbaz
```
and do
```
filtersToCheck = value.split(',')
```
The other approach is ofcourse, subclassin... |
Sorting files by date | 6,759,415 | 7 | 2011-07-20T09:02:32Z | 6,759,499 | 18 | 2011-07-20T09:10:28Z | [
"python",
"list",
"sorting"
] | I found this directory checking code on the web and modified it a little, so it would print out added files. There's a buoy that sends me readings every now-and-then, but sometimes the connection is lost and instead of one file it sends multiple files. I need the program to sort them for me by date created. Is there a ... | ```
added.sort(key=lambda x: os.stat(os.path.join(path_to_watch, x)).st_mtime)
```
Will sort the `added` list by the last modified time of the files
Use `st_ctime` instaed of `st_mtime` for creation time on Windows (it doesn't mean that on other platforms). |
Python: Iterating through constructor's arguments | 6,760,536 | 10 | 2011-07-20T10:34:03Z | 6,760,593 | 16 | 2011-07-20T10:39:19Z | [
"python",
"constructor",
"arguments"
] | I often find myself writing class constructors like this:
```
class foo:
def __init__(self, arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
```
This can obviously become a pain if the number of arguments (and class attributes) gets high. I'm looking for the most pytho... | The most Pythonic way is what you've already written. If you are happy to require named arguments, you could do this:
```
class foo:
def __init__(self, **kwargs):
vars(self).update(kwargs)
``` |
Creating a singleton in Python | 6,760,685 | 296 | 2011-07-20T10:47:57Z | 6,760,726 | 48 | 2011-07-20T10:52:04Z | [
"python",
"singleton",
"decorator",
"base-class",
"metaclass"
] | *This question is not for the discussion of whether or not the [singleton design pattern](http://en.wikipedia.org/wiki/Singleton_pattern) is desirable, is an anti-pattern, or for any religious wars, but to discuss how this pattern is best implemented in Python in such a way that is most pythonic. In this instance I def... | ```
class Foo(object):
pass
some_global_variable = Foo()
```
Modules are imported only once, everything else is overthinking. Don't use singletons and try not to use globals. |
Creating a singleton in Python | 6,760,685 | 296 | 2011-07-20T10:47:57Z | 6,760,821 | 30 | 2011-07-20T10:58:19Z | [
"python",
"singleton",
"decorator",
"base-class",
"metaclass"
] | *This question is not for the discussion of whether or not the [singleton design pattern](http://en.wikipedia.org/wiki/Singleton_pattern) is desirable, is an anti-pattern, or for any religious wars, but to discuss how this pattern is best implemented in Python in such a way that is most pythonic. In this instance I def... | Use a module. It is imported only once. Define some global variables in it - they will be singleton's 'attributes'. Add some functions - the singleton's 'methods'. |
Creating a singleton in Python | 6,760,685 | 296 | 2011-07-20T10:47:57Z | 6,798,042 | 199 | 2011-07-23T03:28:20Z | [
"python",
"singleton",
"decorator",
"base-class",
"metaclass"
] | *This question is not for the discussion of whether or not the [singleton design pattern](http://en.wikipedia.org/wiki/Singleton_pattern) is desirable, is an anti-pattern, or for any religious wars, but to discuss how this pattern is best implemented in Python in such a way that is most pythonic. In this instance I def... | ## Use a Metaclass
I would recommend **Method #2**, but you're better off using a **metaclass** than a base class. Here is a sample implementation:
```
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singl... |
Python: sub list of items depending on a certain value of the items, e.g. boolean | 6,760,857 | 2 | 2011-07-20T11:01:17Z | 6,760,878 | 7 | 2011-07-20T11:03:06Z | [
"python",
"list",
"boolean",
"sublist"
] | I have a list of similar objects, some of them have a certain value set, here more specifically a boolean flag:
```
myList = [WhatEver(..., True, ...), WhatEver(..., True, ...), WhatEver(..., False, ...), WhatEver(..., True, ...), WhatEver(..., False, ...), ...]
```
Is there a painless way in Python to get a sub list... | Yes, there is. [List comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) are a very good fit for this:
```
[item for item in myList if item.flag]
[item for item in myList if not item.flag]
```
where `flag` is the name of `WhatEver`'s field that you want to check. |
How to slice list into contiguous groups of non-zero integers in Python | 6,760,871 | 3 | 2011-07-20T11:02:27Z | 6,761,015 | 10 | 2011-07-20T11:14:20Z | [
"python"
] | Can't seem to find a clue to this online and can't figure it out myself so:
How would I go about slicing a list so that I return a list of slices of contiguous non-zero integers. ie:
```
data = [3, 7, 4, 0, 1, 3, 7]
```
and I want to produce:
```
slices = [[3, 7, 4], [1, 3, 7]]
```
I have tried various methods of ... | ```
import itertools
[ list(x[1]) for x in itertools.groupby(data, lambda x: x == 0) if not x[0] ]
``` |
inspect.getmembers() vs __dict__.items() vs dir() | 6,761,106 | 15 | 2011-07-20T11:23:34Z | 6,761,335 | 13 | 2011-07-20T11:45:15Z | [
"python",
"namespaces"
] | Can anybody explain to me with adequate examples whats the difference b/w
```
>>> import inspect
>>> inspect.getmembers(1)
```
and
```
>>> type(1).__dict__.items()
```
and
```
>>> dir(1)
```
except that they show an decreasing no.s of attributes & methods in that order.
1 is integer (but it can be of any type.)
... | `dir()` allows you to customize what attributes your object reports, by defining `__dir__()`.
From the manual, if `__dir__()` is not defined:
> If the object is a module object, the list contains the names of the moduleâs attributes.
>
> If the object is a type or class object, the list contains the names of its at... |
How to disable reverse dns lookup in python webserver? | 6,761,559 | 6 | 2011-07-20T12:01:31Z | 6,761,844 | 11 | 2011-07-20T12:25:10Z | [
"python",
"networking",
"dns"
] | i have a simple python cgi server:
```
import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable() ## This line enables CGI error reporting
server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 8000)
httpd = server(server_address, handler)
httpd.serve_fore... | You can subclass your own handler class, which won't do the DNS lookups. This follows from <http://docs.python.org/library/cgihttpserver.html#module-CGIHTTPServer> which says [CGIHTTPRequestHandler](http://docs.python.org/library/cgihttpserver.html#CGIHTTPServer.CGIHTTPRequestHandler) is interface compatible with [Base... |
importing multiple functions from a Python module | 6,761,825 | 15 | 2011-07-20T12:23:19Z | 6,761,850 | 22 | 2011-07-20T12:25:32Z | [
"python",
"coding-style",
"import"
] | I am importing lots of functions from a module
Is it better to use
```
from my_module import function1, function2, function3, function4, function5, function6, function7
```
which is a little messy, but avoids flooding the current namespace with everything from that module or
```
from my_module import *
```
Which l... | If you really need that many functions, you are already polluting your namespace.
I would suggest:
```
import my_module
```
Or, if my\_module has a long name use an alias:
```
import my_long_module as m
``` |
What is the easiest way to get all strings that do not start with a character? | 6,763,414 | 2 | 2011-07-20T14:17:28Z | 6,763,438 | 9 | 2011-07-20T14:19:48Z | [
"python",
"string",
"startswith"
] | I am trying to parse about 20 million lines from a text file and am looking for a way to do some further manipulations on lines that do not start with question marks. I would like a solution that does not use regex matching. What I would like to do is something like this:
```
for line in x:
header = line.startswit... | Use generator expressions, the best way I think.
```
for line in (line for line in x if not line.startswith('?')):
DO_STUFF
```
Or your way:
```
for line in x:
if line.startswith("?"):
continue
DO_STUFF
```
Or:
```
for line in x:
if not line.startswith("?"):
DO_STUFF
```
It is real... |
How does Python handle checking 'if object in list' | 6,764,063 | 3 | 2011-07-20T15:05:03Z | 6,764,097 | 10 | 2011-07-20T15:07:36Z | [
"python",
"performance",
"algorithm",
"list"
] | I'm wondering because I need to have have a function that is disgustingly fast at checking if a word is in a dictionary list - I'm considering leaving the dictionary as a large string and running regex against instead. This needs to be absurdly fast. So I just need a basic overview of *how* python handles checking if a... | If you want a blazingly fast membership test, then a list is the wrong data structure. Take a look at the implementation of `list_contains` in [`listobject.c`, line 437](http://hg.python.org/cpython/file/b754641a429f/Objects/listobject.c#l437). It iterates over the list in order, comparing the item with each element in... |
Python: How to remove all duplicate items from a list | 6,764,909 | 14 | 2011-07-20T16:03:16Z | 6,764,940 | 42 | 2011-07-20T16:05:12Z | [
"python",
"list"
] | How would I use python to check a list and delete all duplicates? I don't want to have to specify what the duplicate item is - I want the code to figure out if there are any and remove them if so, keeping only one instance of each. It also must work if there are multiple duplicates in a list.
For example, in my code b... | Use `set()`:
```
woduplicates = set(lseparatedOrblist)
```
Returns a set without duplicates. If you, for some reason, need a list back:
```
woduplicates = list(set(lseperatedOrblist))
``` |
Python: How to remove all duplicate items from a list | 6,764,909 | 14 | 2011-07-20T16:03:16Z | 6,764,969 | 29 | 2011-07-20T16:06:42Z | [
"python",
"list"
] | How would I use python to check a list and delete all duplicates? I don't want to have to specify what the duplicate item is - I want the code to figure out if there are any and remove them if so, keeping only one instance of each. It also must work if there are multiple duplicates in a list.
For example, in my code b... | Just make a new list to populate, if the item for your list is not yet in the new list input it, else just move on to the next item in your original list.
```
for i in mylist:
if i not in newlist:
newlist.append(i)
```
I think this is the correct syntax, but my python is a bit shaky, I hope you at least get the... |
Python: How to remove all duplicate items from a list | 6,764,909 | 14 | 2011-07-20T16:03:16Z | 6,764,973 | 20 | 2011-07-20T16:07:17Z | [
"python",
"list"
] | How would I use python to check a list and delete all duplicates? I don't want to have to specify what the duplicate item is - I want the code to figure out if there are any and remove them if so, keeping only one instance of each. It also must work if there are multiple duplicates in a list.
For example, in my code b... | You can do this like that:
```
x = list(set(x))
```
Example: if you do something like that:
```
x = [1,2,3,4,5,6,7,8,9,10,2,1,6,31,20]
x = list(set(x))
x
```
you will see the following result:
```
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 31]
```
There is only one thing you should think of: the resulting list will not ... |
Python: How to remove all duplicate items from a list | 6,764,909 | 14 | 2011-07-20T16:03:16Z | 6,765,391 | 7 | 2011-07-20T16:38:51Z | [
"python",
"list"
] | How would I use python to check a list and delete all duplicates? I don't want to have to specify what the duplicate item is - I want the code to figure out if there are any and remove them if so, keeping only one instance of each. It also must work if there are multiple duplicates in a list.
For example, in my code b... | This should be faster and will preserve the original order:
```
seen = {}
new_list = [seen.setdefault(x, x) for x in my_list if x not in seen]
```
If you don't care about order, you can just:
```
new_list = list(set(my_list))
``` |
piping postgres COPY in python with psycopg2 | 6,765,310 | 7 | 2011-07-20T16:33:20Z | 9,166,750 | 10 | 2012-02-06T20:24:25Z | [
"python",
"sql",
"copy",
"pipe",
"psycopg2"
] | I'm writing a script to do a copy of some data between two machines on the same network using psycopg2. I'm replacing some old, ugly bash that does the copy with
```
psql -c -h remote.host "COPY table TO STDOUT" | psql -c "COPY table FROM STDIN"
```
This seems like both the simplest and [most efficient](http://www.de... | You will have to put one of your calls in a separate thread. I just realized you can use [os.pipe()](http://docs.python.org/release/2.6/library/os.html#os.pipe), which makes the rest quite straightforward:
```
#!/usr/bin/python
import psycopg2
import os
import threading
fromdb = psycopg2.connect("dbname=from_db")
tod... |
python `in` keyword as a function used in a filter | 6,766,243 | 9 | 2011-07-20T17:54:09Z | 6,766,265 | 8 | 2011-07-20T17:55:47Z | [
"python",
"keyword"
] | is it possible to use the python keyword `in` in a filter? I know that binary, unary, assignment operations are equivalent to a function call.
such as
```
''!=3
```
is the same as
```
''.__ne__(3)
```
is there an analogous thing for the `in` function?
I want to do something like this. ..
```
filter( list1.__in__,... | You are looking for [`__contains__`](http://docs.python.org/reference/datamodel.html#object.__contains__).
```
>>> [1, 2, 3].__contains__(2)
True
>>> [1, 2, 3].__contains__(4)
False
```
And for what you want to do:
```
>>> list1 = [2, 4, 6, 8, 10]
>>> filter(list1.__contains__, [1, 2, 3, 4, 5])
[2, 4]
``` |
python `in` keyword as a function used in a filter | 6,766,243 | 9 | 2011-07-20T17:54:09Z | 6,766,306 | 15 | 2011-07-20T17:59:53Z | [
"python",
"keyword"
] | is it possible to use the python keyword `in` in a filter? I know that binary, unary, assignment operations are equivalent to a function call.
such as
```
''!=3
```
is the same as
```
''.__ne__(3)
```
is there an analogous thing for the `in` function?
I want to do something like this. ..
```
filter( list1.__in__,... | ```
filter( list1.__contains__, list2 )
```
is more cleanly written as:
```
[ v for v in list2 if v in list1 ]
```
and to show equivalence:
```
>>> list1 = [2, 4, 6, 8, 10]
>>> list2 = [1, 2, 3, 4, 5]
>>> [ v for v in list2 if v in list1 ]
[2, 4]
``` |
Find where python is installed (if it isnt default dir) | 6,767,283 | 29 | 2011-07-20T19:19:18Z | 6,767,301 | 30 | 2011-07-20T19:21:21Z | [
"python"
] | Python is on my machine, i just don't know where, if i type python in terminal it will open Python 2.6.4, this isn't in it's default directory, there surely is a way of finding it's install location from here? | What OS are you using? In unix (mac os X included) you can do `which python` and it will tell you. |
Find where python is installed (if it isnt default dir) | 6,767,283 | 29 | 2011-07-20T19:19:18Z | 6,767,329 | 45 | 2011-07-20T19:24:35Z | [
"python"
] | Python is on my machine, i just don't know where, if i type python in terminal it will open Python 2.6.4, this isn't in it's default directory, there surely is a way of finding it's install location from here? | `sys` has some useful stuff:
```
$ python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:13:38) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.executable
'c:\\Python26\\python.exe'
>>> sys.exec_prefix
'c:\\Python26'
>>>
>>> print '\n'.join(... |
Find where python is installed (if it isnt default dir) | 6,767,283 | 29 | 2011-07-20T19:19:18Z | 6,767,762 | 16 | 2011-07-20T20:01:21Z | [
"python"
] | Python is on my machine, i just don't know where, if i type python in terminal it will open Python 2.6.4, this isn't in it's default directory, there surely is a way of finding it's install location from here? | Platform independent solution in one line is
```
python -c "import sys; print sys.executable"
``` |
How to get process status using pid? | 6,767,649 | 6 | 2011-07-20T19:53:35Z | 6,767,792 | 10 | 2011-07-20T20:03:42Z | [
"python"
] | If I known a process's pid, how can I tell if the process is an zombie using Python ? | You could use a the `status` feature from [psutils](https://github.com/giampaolo/psutil):
```
import psutil
p = psutil.Process(the_pid_you_want)
if p.status == psutil.STATUS_ZOMBIE:
....
``` |
How to get process status using pid? | 6,767,649 | 6 | 2011-07-20T19:53:35Z | 6,767,808 | 11 | 2011-07-20T20:04:27Z | [
"python"
] | If I known a process's pid, how can I tell if the process is an zombie using Python ? | here's a quick hack using `procfs` (assuming you're using Linux):
```
def procStatus(pid):
for line in open("/proc/%d/status" % pid).readlines():
if line.startswith("State:"):
return line.split(":",1)[1].strip().split(' ')[0]
return None
```
this function should return `'Z'` for zombies. |
NLTK - when to normalize the text? | 6,767,770 | 5 | 2011-07-20T20:01:51Z | 6,767,866 | 8 | 2011-07-20T20:10:34Z | [
"python",
"nlp",
"nltk"
] | I've finished gathering my data I plan to use for my corpus, but I'm a bit confused about whether I should normalize the text. I plan to tag & chunk the corpus in the future. Some of NLTK's corpora are all lower case and others aren't.
Can anyone shed some light on this subject, please? | By "normalize" do you just mean making everything lowercase?
The decision about whether to lowercase everything is really dependent of what you plan to do. For some purposes, lowercasing everything is better because it lowers the sparsity of the data (uppercase words are rarer and might confuse the system unless you h... |
Difference between frompyfunc and vectorize in numpy | 6,768,245 | 16 | 2011-07-20T20:40:02Z | 11,157,577 | 10 | 2012-06-22T13:54:25Z | [
"python",
"arrays",
"numpy",
"vectorization"
] | What is the difference between [vectorize](http://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html) and [frompyfunc](http://docs.scipy.org/doc/numpy/reference/generated/numpy.frompyfunc.html#numpy.frompyfunc) in numpy?
Both seem very similar. What is a typical use case for each of them?
**Edit**: As ... | As JoshAdel points out, `vectorize` wraps `frompyfunc`. Vectorize adds extra features:
* Copies the docstring from the original function
* Allows you to exclude an argument from broadcasting rules.
* Returns an array of the correct dtype instead of dtype=object
**Edit:** After some brief benchmarking, I find that `ve... |
Key to maxima of dictionary in python | 6,768,466 | 4 | 2011-07-20T20:57:30Z | 6,768,549 | 9 | 2011-07-20T21:03:54Z | [
"python",
"dictionary"
] | I have a dictionary, "scores", of integers and I want to find the key(s) of the highest value. I used this code:
```
key = max(scores, key=scores.get)
```
however, this only gives back one key. How does this deal with ties in highest value? I only get one number back. Which is it in the case of a tie? How can I get a... | You could run the following, for example:
```
max_value = max(scores.values())
keys = [ i for (i,v) in scores.iteritems() if v == max_value ]
```
"keys" would now hold all the keys which correspond to the maximum value. |
argument of type 'NoneType' is not iterable | 6,769,196 | 5 | 2011-07-20T22:13:49Z | 6,769,500 | 18 | 2011-07-20T22:52:05Z | [
"python",
"xml",
"loops",
"elementtree"
] | I am trying to open a directory that contains a series of XML's in one specific directory.
In the following code, I am iterating through each XML document, and I'm setting some "if statements" to read the text in the XML, find keywords and replace them and then write a new file to a new location.
I am getting the f... | You will find that there are many elements in an xml document which contain no character data (i.e. text). One of the nice things about python is that None is false in a conditional, coupling that with knowledge of how conditional statements short circuit means that there's a really simple solution to your problem, cha... |
Python Algorithm Challenge? | 6,769,315 | 5 | 2011-07-20T22:29:42Z | 6,769,339 | 10 | 2011-07-20T22:33:43Z | [
"python",
"algorithm"
] | I have a `python` function (call it `myFunction`) that gets as input **a list of numbers**, and, following a complex calculation, returns back the result of the calculation (which is a **number**).
The function looks like this:
```
def myFunction( listNumbers ):
# initialize the result of the calculation
calc... | You could use a [generator](http://wiki.python.org/moin/Generators) as an input. The generator will only return when there is data available to process.
Update: thanks for the brilliant comment, I wanted to remove this entry :)
```
class lazylist(object):
def __init__(self):
self.cnt = 0
self.leng... |
Looking for more pythonic list comparison solution | 6,770,002 | 5 | 2011-07-21T00:15:26Z | 6,770,033 | 7 | 2011-07-21T00:19:37Z | [
"python",
"list"
] | Ok so I have two lists:
```
x = [1, 2, 3, 4]
y = [1, 1, 2, 5, 6]
```
I compare them in such a way so I get the following output:
```
x = [3, 4]
y = [1, 5, 6]
```
The basic is idea to go through each list and compare them. If they have an element in common remove that element. But only one of that element not all of... | It's possible that the data structure you are looking for is the [**multiset**](http://en.wikipedia.org/wiki/Multiset) (or "bag"), and if so, a good way to implement it in Python is to use [`collections.Counter`](http://docs.python.org/library/collections.html#collections.Counter):
```
>>> from collections import Coun... |
Most efficient way to reverse a numpy array | 6,771,428 | 118 | 2011-07-21T04:58:24Z | 6,771,620 | 97 | 2011-07-21T05:25:54Z | [
"python",
"numpy"
] | Believe it or not, after profiling my current code, the repetitive operation of numpy array reversion ate a giant chunk of the running time. What I have right now is the common view-based method:
```
reversed_arr = arr[::-1]
```
Is there any other way to do it more efficiently, or is it just an illusion from my obses... | When you create `reversed_arr` you are creating a view into the original array. You can then change the original array, and the view will update to reflect the changes.
Are you re-creating the view more often than you need to? You should be able to do something like this:
```
arr = np.array(some_sequence)
reversed_ar... |
Most efficient way to reverse a numpy array | 6,771,428 | 118 | 2011-07-21T04:58:24Z | 24,813,184 | 17 | 2014-07-17T20:43:02Z | [
"python",
"numpy"
] | Believe it or not, after profiling my current code, the repetitive operation of numpy array reversion ate a giant chunk of the running time. What I have right now is the common view-based method:
```
reversed_arr = arr[::-1]
```
Is there any other way to do it more efficiently, or is it just an illusion from my obses... | `np.fliplr()` flips the array left to right.
Note that for 1d arrays, you need to trick it a bit:
```
arr1d = np.array(some_sequence)
reversed_arr = np.fliplr([arr1d])[0]
``` |
Use openpyxl to edit a Excel2007 file (.xlsx) without changing its own styles? | 6,772,438 | 11 | 2011-07-21T07:04:44Z | 6,785,269 | 11 | 2011-07-22T03:13:57Z | [
"python",
"excel-2007",
"openpyxl"
] | I have a .xlsx file to edit, I found [openpyxl](http://packages.python.org/openpyxl/) could manipulate Excel 2007 files.
I only want to change the value in some cells and leave other settings unchanged.
But after I went through the [Documentation](http://packages.python.org/openpyxl/index.html), I cannot find the exam... | Now openpyxl cannot handle styles good enough, so I tried using pywin32 COM and got the solution.
Here is a good [python-excel-mini-cookbook](http://pythonexcels.com/blog/python-excel-mini-cookbook/) to use pywin32 COM for Excel |
How to force deletion of a python object? | 6,772,481 | 29 | 2011-07-21T07:09:58Z | 6,772,907 | 42 | 2011-07-21T07:55:19Z | [
"python",
"constructor",
"garbage-collection",
"destructor",
"reference-counting"
] | I am curious about the details of `__del__` in python, when and why it should be used and what it shouldn't be used for. I've learned the hard way that it is not really like what one would naively expected from a destructor, in that it is not the opposite of `__new__` / `__init__`.
```
class Foo(object):
def __in... | The way to close resources are context managers, aka the `with` statement:
```
class Foo(object):
def __init__(self):
self.bar = None
def __enter__(self):
if self.bar != 'open':
print 'opening the bar'
self.bar = 'open'
return self # this is bound to the `as` part
def close(self):
... |
How is Pythons glob.glob ordered? | 6,773,584 | 50 | 2011-07-21T08:59:21Z | 6,773,636 | 35 | 2011-07-21T09:02:39Z | [
"python"
] | I have written the following Python code:
```
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, glob
path = '/home/my/path'
for infile in glob.glob( os.path.join(path, '*.png') ):
print infile
```
Now I get this:
```
/home/my/path/output0352.png
/home/my/path/output0005.png
/home/my/path/output0137.png
/hom... | It is probably not sorted at all and uses the order at which entries appear in the filesystem, i.e. the one you get when using `ls -U`. (At least on my machine this produces the same order as listing `glob` matches). |
How is Pythons glob.glob ordered? | 6,773,584 | 50 | 2011-07-21T08:59:21Z | 6,773,640 | 8 | 2011-07-21T09:02:52Z | [
"python"
] | I have written the following Python code:
```
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, glob
path = '/home/my/path'
for infile in glob.glob( os.path.join(path, '*.png') ):
print infile
```
Now I get this:
```
/home/my/path/output0352.png
/home/my/path/output0005.png
/home/my/path/output0137.png
/hom... | glob.glob() is a wrapper around os.listdir() so the underlaying OS is in charge for delivering the data. In general: you can not make an assumption on the ordering here. The basic assumption is: *no* ordering. If you need some sorting: sort on the application level. |
How is Pythons glob.glob ordered? | 6,773,584 | 50 | 2011-07-21T08:59:21Z | 6,773,661 | 28 | 2011-07-21T09:04:37Z | [
"python"
] | I have written the following Python code:
```
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, glob
path = '/home/my/path'
for infile in glob.glob( os.path.join(path, '*.png') ):
print infile
```
Now I get this:
```
/home/my/path/output0352.png
/home/my/path/output0005.png
/home/my/path/output0137.png
/hom... | By checking the source code of `glob.glob` you see that it internally calls `os.listdir`, described here:
<http://docs.python.org/library/os.html?highlight=os.listdir#os.listdir>
Key sentence: os.listdir(path)
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary o... |
How is Pythons glob.glob ordered? | 6,773,584 | 50 | 2011-07-21T08:59:21Z | 6,774,404 | 132 | 2011-07-21T10:07:26Z | [
"python"
] | I have written the following Python code:
```
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, glob
path = '/home/my/path'
for infile in glob.glob( os.path.join(path, '*.png') ):
print infile
```
Now I get this:
```
/home/my/path/output0352.png
/home/my/path/output0005.png
/home/my/path/output0137.png
/hom... | Order is arbitrary, but you can sort them yourself
If you want sorted by name:
```
sorted(glob.glob('*.png'))
```
sorted by modification time:
```
import os
sorted(glob.glob('*.png'), key=os.path.getmtime)
```
sorted by size:
```
import os
sorted(glob.glob('*.png'), key=os.path.getsize)
```
etc. |
Why is my xlabel cut off in my matplotlib plot? | 6,774,086 | 73 | 2011-07-21T09:37:24Z | 6,776,578 | 92 | 2011-07-21T13:11:18Z | [
"python",
"matplotlib"
] | I am plotting a dataset using `matplotlib` where I have an xlabel that is quite "tall" (it's a formula rendered in TeX that contains a fraction and is therefore has the height equivalent of a couple of lines of text).
In any case, the bottom of the formula is always cut off when I draw the figures. Changing figure siz... | Use:
```
import matplotlib.pyplot as plt
plt.gcf().subplots_adjust(bottom=0.15)
```
to make room for the label.
Edit:
Since i gave the answer, `matplotlib` has added the **`tight_layout()`** function.
So i suggest to use it:
```
plt.tight_layout()
```
should make room for the xlabel. |
Why is my xlabel cut off in my matplotlib plot? | 6,774,086 | 73 | 2011-07-21T09:37:24Z | 17,390,833 | 49 | 2013-06-30T13:28:48Z | [
"python",
"matplotlib"
] | I am plotting a dataset using `matplotlib` where I have an xlabel that is quite "tall" (it's a formula rendered in TeX that contains a fraction and is therefore has the height equivalent of a couple of lines of text).
In any case, the bottom of the formula is always cut off when I draw the figures. Changing figure siz... | An easy option is to configure matplotlib to automatically adjust the plot size. It works perfectly for me and I'm not sure why it's not activated by default.
**Method 1**
Set this in your matplotlibrc file
```
figure.autolayout : True
```
See here for more information on customizing the matplotlibrc file: <http://... |
Flask vs webapp2 for Google App Engine | 6,774,371 | 95 | 2011-07-21T10:03:51Z | 6,775,079 | 12 | 2011-07-21T11:09:33Z | [
"python",
"google-app-engine",
"flask",
"webapp2"
] | I'm starting new Google App Engine application and currently considering two frameworks: [Flask](http://flask.pocoo.org/) and [webapp2](http://webapp-improved.appspot.com/). I'm rather satisfied with built-in webapp framework that I've used for my previous App Engine application, so I think webapp2 will be even better ... | Your question is extremely broad, but there appears to be no big problems using Flask on Google App Engine.
This mailing list thread links to several templates:
<http://flask.pocoo.org/mailinglist/archive/2011/3/27/google-app-engine/#4f95bab1627a24922c60ad1d0a0a8e44>
And here is a tutorial specific to the Flask / Ap... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.