title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Python, print delimited list
2,399,112
25
2010-03-08T03:25:03Z
2,399,163
9
2010-03-08T03:42:18Z
[ "python", "string", "printing" ]
Consider this Python code for printing a list of comma separated values ``` for element in list: print element + ",", ``` What is the preferred method for printing such that a comma does not appear if `element` is the final element in the list. ex ``` a = [1, 2, 3] for element in a print str(element) +",", o...
A `','.join` as suggested in other answers is the typical Python solution; the normal approach, which peculiarly I don't see in any of the answers so far, is ``` print ','.join(str(x) for x in a) ``` known as a generator expression or genexp. If you prefer a loop (or need one for other purposes, if you're doing more...
Python, lazy list
2,399,194
7
2010-03-08T03:52:09Z
2,399,233
8
2010-03-08T04:06:21Z
[ "python", "lazy-evaluation" ]
Is it possible to have a list be evaluated lazily in Python? For example ``` a = 1 list = [a] print list #[1] a = 2 print list #[1] ``` If the list was set to evaluate lazily then the final line would be [2]
The concept of "lazy" evaluation normally comes with functional languages -- but in those you could not reassign two different values to the same identifier, so, not even there could your example be reproduced. The point is not about laziness at all -- it is that using an identifier is guaranteed to be identical to ge...
How to invoke the super constructor in Python?
2,399,307
127
2010-03-08T04:35:17Z
2,399,332
156
2010-03-08T04:43:13Z
[ "python", "class", "inheritance" ]
``` class A: def __init__(self): print "world" class B(A): def __init__(self): print "hello" B() hello ``` In all other languages I've worked with the super constructor is invoked implicitly. How does one invoke it in Python? I would expect `super(self)` but this doesn't work
`super()` returns a parent-like object *in new-style classes*: ``` class A(object): def __init__(self): print "world" class B(A): def __init__(self): print "hello" super(B, self).__init__() B() ```
How to invoke the super constructor in Python?
2,399,307
127
2010-03-08T04:35:17Z
2,399,348
37
2010-03-08T04:48:00Z
[ "python", "class", "inheritance" ]
``` class A: def __init__(self): print "world" class B(A): def __init__(self): print "hello" B() hello ``` In all other languages I've worked with the super constructor is invoked implicitly. How does one invoke it in Python? I would expect `super(self)` but this doesn't work
With Python 2.x old-style classes it would be this: ``` class A: def __init__(self): print "world" class B(A): def __init__(self): print "hello" A.__init__(self) ```
How to invoke the super constructor in Python?
2,399,307
127
2010-03-08T04:35:17Z
2,399,385
25
2010-03-08T05:01:49Z
[ "python", "class", "inheritance" ]
``` class A: def __init__(self): print "world" class B(A): def __init__(self): print "hello" B() hello ``` In all other languages I've worked with the super constructor is invoked implicitly. How does one invoke it in Python? I would expect `super(self)` but this doesn't work
One way is to call A's constructor and pass `self` as an argument, like so: ``` class B(A): def __init__(self): A.__init__(self) print "hello" ``` The advantage of this style is that it's very clear. It call A's constructor. The downside is that it doesn't handle diamond-shaped inheritance very we...
How to invoke the super constructor in Python?
2,399,307
127
2010-03-08T04:35:17Z
33,191,175
17
2015-10-17T20:17:54Z
[ "python", "class", "inheritance" ]
``` class A: def __init__(self): print "world" class B(A): def __init__(self): print "hello" B() hello ``` In all other languages I've worked with the super constructor is invoked implicitly. How does one invoke it in Python? I would expect `super(self)` but this doesn't work
In line with the other answers, there are multiple ways to call super class methods (including the constructor), however in Python-3.x the process has been simplified: **Python-2.x** ``` class A(object): def __init__(self): print "world" class B(A): def __init__(self): print "hello" super(B, self).__init_...
Generator speed in python 3
2,399,308
7
2010-03-08T04:35:22Z
2,401,657
8
2010-03-08T13:44:55Z
[ "python", "python-3.x" ]
I am going through a [link about generators](http://www.dabeaz.com/generators/Generators.pdf) that someone posted. In the beginning he compares the two functions below. On his setup he showed a speed increase of 5% with the generator. I'm running windows XP, python 3.1.1, and cannot seem to duplicate the results. I ke...
For what it's worth, the main purpose of the speed comparison in the presentation was to point out that using generators does not introduce a huge performance overhead. Many programmers, when first seeing generators, might start wondering about the hidden costs. For example, is there all sorts of fancy magic going on b...
In python, what does len(list) do?
2,399,835
11
2010-03-08T07:18:36Z
2,399,932
16
2010-03-08T07:52:14Z
[ "python", "list" ]
Does `len(list)` calculate the length of the list every time it is called, or does it return the value of the built-in counter? I have a context where I need to check the length of a list every time through a loop, like: ``` listData = [] for value in ioread(): if len(listData)>=25: processlistdata() ...
You should probably be aware, if you're worried about this operation's performance, that "lists" in Python [are really](http://bytes.com/topic/python/answers/101848-list-implementation) dynamic arrays. That is, they're not implemented as linked lists, which you generally have to "walk" to compute a length for (unless s...
How to create a timer using tkinter?
2,400,262
37
2010-03-08T09:16:34Z
2,401,181
60
2010-03-08T12:20:02Z
[ "python", "user-interface", "tkinter" ]
I need to code a program with Python's tkinter library. My major problem is that I don't know how to create a *timer* or a *clock* like `hh:mm:ss`. I need it to update itself (that's what I don't know how to do).
Tkinter root windows have a method called `after` which can be used to schedule a function to be called after a given period of time. If that function itself calls `after` you've set up an automatically recurring event. Here is a working example: ``` # for python 3.x use 'tkinter' rather than 'Tkinter' import Tkinter...
Ubuntu System Tray in Python
2,400,432
11
2010-03-08T09:53:47Z
2,400,511
7
2010-03-08T10:09:37Z
[ "python", "linux", "ubuntu", "tkinter" ]
How do I put a program in the system tray (I don't think it's called like that in Linux) in python TKINTER for UBUNTU 9.04.
I don't believe you can do that using Tkinter. You will have to use the gtk libraries. An example, found on a Ubuntu forum: <http://ubuntuforums.org/showpost.php?s=bc369fc9343ae728577f1bdcd292caca&p=1053546&postcount=3> Here's an example (in Perl) of combining gtk and Tk. Gtk handles the tray icon, and the rest of th...
Easiest way to replace a string using a dictionary of replacements?
2,400,504
38
2010-03-08T10:08:23Z
2,400,569
13
2010-03-08T10:19:34Z
[ "python", "regex" ]
Consider.. ``` dict = { 'Спорт':'Досуг', 'russianA':'englishA' } s = 'Спорт russianA' ``` I'd like to replace all dict keys with their respective dict values in `s`.
You could use the [reduce](http://docs.python.org/2.7/library/functions.html#reduce) function: ``` reduce(lambda x, y: x.replace(y, dict[y]), dict, s) ```
Easiest way to replace a string using a dictionary of replacements?
2,400,504
38
2010-03-08T10:08:23Z
2,400,577
49
2010-03-08T10:20:39Z
[ "python", "regex" ]
Consider.. ``` dict = { 'Спорт':'Досуг', 'russianA':'englishA' } s = 'Спорт russianA' ``` I'd like to replace all dict keys with their respective dict values in `s`.
Using re: ``` import re s = 'Спорт not russianA' d = { 'Спорт':'Досуг', 'russianA':'englishA' } pattern = re.compile(r'\b(' + '|'.join(d.keys()) + r')\b') result = pattern.sub(lambda x: d[x.group()], s) # Output: 'Досуг not englishA' ``` This will match whole words only. If you don't need that, ...
Easiest way to replace a string using a dictionary of replacements?
2,400,504
38
2010-03-08T10:08:23Z
2,401,481
8
2010-03-08T13:15:12Z
[ "python", "regex" ]
Consider.. ``` dict = { 'Спорт':'Досуг', 'russianA':'englishA' } s = 'Спорт russianA' ``` I'd like to replace all dict keys with their respective dict values in `s`.
Solution [found here](http://www.daniweb.com/code/snippet216636.html#) (I like its simplicity): ``` def multipleReplace(text, wordDict): for key in wordDict: text = text.replace(key, wordDict[key]) return text ```
Best web application language for Delphi Developers
2,400,605
5
2010-03-08T10:26:18Z
2,400,960
7
2010-03-08T11:37:37Z
[ "php", "python", "ruby", "delphi" ]
I'm Delphi developer, and I would like to build few web applications, I know about Intraweb, but I think it's not a real tool for web development, maybe for just intranet applications so I'm considering PHP, Python or ruby, I prefer python because it's better syntax than other( I feel it closer to Delphi), also I want...
Try Morfik <http://www.morfik.com/> P.S. It looked promising a few years ago, but after I digged it deeper I must admit that it's quite limited web development environment for a very basic web development.
Is there a memory efficient and fast way to load big json files in python?
2,400,643
33
2010-03-08T10:34:15Z
2,402,417
10
2010-03-08T15:33:47Z
[ "python", "json", "large-files" ]
I have some json files with 500MB. If I use the "trivial" json.load to load its content all at once, it will consume a lot of memory. Is there a way to read partially the file? If it was a text, line delimited file, I would be able to iterate over the lines. I am looking for analogy to it. Any suggestions? Thanks
So the problem is not that each file is too big, but that there are too many of them, and they seem to be adding up in memory. Python's garbage collector should be fine, unless you are keeping around references you don't need. It's hard to tell exactly what's happening without any further information, but some things y...
Is there a memory efficient and fast way to load big json files in python?
2,400,643
33
2010-03-08T10:34:15Z
17,326,199
34
2013-06-26T17:01:03Z
[ "python", "json", "large-files" ]
I have some json files with 500MB. If I use the "trivial" json.load to load its content all at once, it will consume a lot of memory. Is there a way to read partially the file? If it was a text, line delimited file, I would be able to iterate over the lines. I am looking for analogy to it. Any suggestions? Thanks
There was a duplicate to this question that had a better answer. See <http://stackoverflow.com/a/10382359/1623645>, which suggests [ijson](https://pypi.python.org/pypi/ijson/). **Update:** I tried it out, and ijson is to JSON what SAX is to XML. For instance, you can do this: ``` import ijson for prefix, the_type, v...
Python - Differences between elements of a list
2,400,840
41
2010-03-08T11:16:11Z
2,400,875
57
2010-03-08T11:23:38Z
[ "python", "list" ]
Given a list of numbers how to find differences between every (`i`)-th and (`i+1`)-th of its elements? Should one better use lambda or maybe lists comprehension? Example: Given a list `t=[1,3,6,...]` it is to find a list `v=[2,3,...]` because `3-1=2`, `6-3=3`, etc.
``` >>> t [1, 3, 6] >>> [j-i for i, j in zip(t[:-1], t[1:])] # or use itertools.izip in py2k [2, 3] ```
Python - Differences between elements of a list
2,400,840
41
2010-03-08T11:16:11Z
2,401,936
45
2010-03-08T14:26:04Z
[ "python", "list" ]
Given a list of numbers how to find differences between every (`i`)-th and (`i+1`)-th of its elements? Should one better use lambda or maybe lists comprehension? Example: Given a list `t=[1,3,6,...]` it is to find a list `v=[2,3,...]` because `3-1=2`, `6-3=3`, etc.
The other answers are correct but if you're doing numerical work, you might want to consider numpy. Using numpy, the answer is: ``` v = numpy.diff(t) ```
Python - Differences between elements of a list
2,400,840
41
2010-03-08T11:16:11Z
16,714,453
17
2013-05-23T12:51:33Z
[ "python", "list" ]
Given a list of numbers how to find differences between every (`i`)-th and (`i+1`)-th of its elements? Should one better use lambda or maybe lists comprehension? Example: Given a list `t=[1,3,6,...]` it is to find a list `v=[2,3,...]` because `3-1=2`, `6-3=3`, etc.
If you don't want to use `numpy` nor `zip`, you can use the simple (simplest in my opinion) solution: ``` >>> t = [1, 3, 6] >>> v = [t[i+1]-t[i] for i in range(len(t)-1)] >>> v [2, 3] ```
Why subprocess.Popen doesn't work when args is sequence?
2,400,878
6
2010-03-08T11:24:23Z
2,401,128
9
2010-03-08T12:10:27Z
[ "python", "subprocess" ]
I'm having a problem with subprocess.Popen when args parameter is given as sequence. For example: ``` import subprocess maildir = "/home/support/Maildir" ``` This works (it prints the correct size of /home/support/Maildir dir): ``` size = subprocess.Popen(["du -s -b " + maildir], shell=True, ...
From the [documentation](http://docs.python.org/library/subprocess.html#using-the-subprocess-module) > On Unix, with shell=True: […] If args is a sequence, the first item specifies the > command string, and any **additional items will be treated as additional arguments to > the shell itself**. That is to say, Popen ...
Python recursive function error: "maximum recursion depth exceeded"
2,401,447
11
2010-03-08T13:10:12Z
2,401,520
20
2010-03-08T13:20:42Z
[ "python", "recursion" ]
I solved Problem 10 of Project Euler with the following code, which works through brute force: ``` def isPrime(n): for x in range(2, int(n**0.5)+1): if n % x == 0: return False return True def primeList(n): primes = [] for i in range(2,n): if isPrime(i): pri...
Recursion is not the most idiomatic way to do things in Python, as it doesn't have [tail recursion](http://en.wikipedia.org/wiki/Tail_recursion) optimization thus making impractical the use of recursion as a substitute for iteration (even if in your example the function is not tail-recursive, that wouldn't help anyway)...
Game cross-compiling and packaging
2,401,599
5
2010-03-08T13:34:11Z
2,468,589
7
2010-03-18T09:17:01Z
[ "python", "c", "cross-platform", "packaging", "cross-compiling" ]
Some friends and I wanted to develop a game. Any language will do. I've been programming in C for years, but never wrote a game before. One of us knows SDL a little bit. It would also be a nice excuse to learn Python+pygame. We wish our game to be 'standalone'. By standalone, I mean most users (at least Linux, Mac and...
If you haven't programmed a game before, I'd recommend that you start with Python and Pygame. Python itself is very easy to learn if you're already a programmer, so that won't be too much of a leap for you. With Pygame, you spend almost no time writing "glue" or dealing with mundane low-level details like window manag...
open file in "w" mode: IOError: [Errno 2] No such file or directory
2,401,628
21
2010-03-08T13:39:04Z
2,401,650
11
2010-03-08T13:43:35Z
[ "python", "file-io" ]
When I try to open a file in **write** mode with the following code: `packetFile = open("%s/%s/%s/%s.mol2" % ("dir", "dir2", "dir3", "some_file"), "w")` Gives me the following error: `IOError: [Errno 2] No such file or directory: 'dir/dir2/dir3/some_file.mol2'` The "w" mode should create the file if it doesn't exis...
Since you don't have a 'starting' slash, your python script is looking for this file relative to the current working directory (and not to the root of the filesystem). Also note that the directories leading up to the file must exist! And: use [os.path.join](http://docs.python.org/library/os.path.html#os.path.join) to ...
open file in "w" mode: IOError: [Errno 2] No such file or directory
2,401,628
21
2010-03-08T13:39:04Z
2,401,655
23
2010-03-08T13:44:47Z
[ "python", "file-io" ]
When I try to open a file in **write** mode with the following code: `packetFile = open("%s/%s/%s/%s.mol2" % ("dir", "dir2", "dir3", "some_file"), "w")` Gives me the following error: `IOError: [Errno 2] No such file or directory: 'dir/dir2/dir3/some_file.mol2'` The "w" mode should create the file if it doesn't exis...
You'll see this error if the *directory* containing the file you're trying to open does not exist, even when trying to open the file in "w" mode. Since you're opening the file with a relative path, it's possible that you're confused about exactly what that directory is. Try putting a quick print to check: ``` import ...
In Python, can I single line a for loop over iterator with an IF filter?
2,401,785
24
2010-03-08T14:03:33Z
2,401,831
16
2010-03-08T14:08:46Z
[ "python" ]
Silly question: I have a simple for loop followed by a simple if statement: ``` for airport in airports: if airport.is_important: ``` and I was wondering if I can write this as a single line somehow. So, yes, I can do this: ``` for airport in (airport for airport in airports if airport.is_important): ``` bu...
You could do ``` for airport in filter(lamdba x: x.is_important, airports): # do stuff... ```
In Python, can I single line a for loop over iterator with an IF filter?
2,401,785
24
2010-03-08T14:03:33Z
2,401,855
42
2010-03-08T14:14:31Z
[ "python" ]
Silly question: I have a simple for loop followed by a simple if statement: ``` for airport in airports: if airport.is_important: ``` and I was wondering if I can write this as a single line somehow. So, yes, I can do this: ``` for airport in (airport for airport in airports if airport.is_important): ``` bu...
No, there is no shorter way. Usually, you will even break it into two lines : ``` important_airports = (airport for airport in airports if airport.is_important) for airport in important_airports: # do stuff ``` This is more flexible, easier to read and still don't consume much memory.
In Python, can I single line a for loop over iterator with an IF filter?
2,401,785
24
2010-03-08T14:03:33Z
2,404,419
8
2010-03-08T20:16:42Z
[ "python" ]
Silly question: I have a simple for loop followed by a simple if statement: ``` for airport in airports: if airport.is_important: ``` and I was wondering if I can write this as a single line somehow. So, yes, I can do this: ``` for airport in (airport for airport in airports if airport.is_important): ``` bu...
I'd use a negative guard on the loop. It's readable, and doesn't introduce an extra level of indentation. ``` for airport in airports: if not airport.is_important: continue <body of loop> ```
Google App Engine UI Widgets
2,402,128
5
2010-03-08T14:52:24Z
2,402,162
9
2010-03-08T14:56:25Z
[ "python", "user-interface", "google-app-engine" ]
Are there any UI widgets available to the python side of Google App Engine? I'd like something like the collapsed/expanded views of Google Groups threads. Are these type things limited to the GWT side?
Why not simply use [**jQueryUI**](http://jqueryui.com/)? It's a tested and very solid library, and will be easier to pick up than anything else at the current stage. Cheers
Convert list in tuple to numpy array?
2,402,575
17
2010-03-08T15:53:38Z
2,402,604
38
2010-03-08T15:57:17Z
[ "python", "arrays", "numpy", "scipy", "tuples" ]
I have tuple of lists. One of these lists is a list of scores. I want to convert the list of scores to a numpy array to take advantage of the pre-built stats that scipy provides. In this case the tuple is called 'data' ``` In [12]: type data[2] -------> type(data[2]) Out[12]: <type 'list'> In [13]: type data[2][1] -...
The command [`numpy.asarray`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html) will turn a number of pre-set iterable containers (list, tuple, etc) into a numpy array.
Python - Initializing Multiple Lists/Line
2,402,646
15
2010-03-08T16:03:11Z
2,402,653
56
2010-03-08T16:04:10Z
[ "python", "list", "initialization" ]
This is terribly ugly: ``` psData = [] nsData = [] msData = [] ckData = [] mAData = [] RData = [] pData = [] ``` Is there a way to declare these variables on a single line?
``` alist, blist, clist, dlist, elist = ([] for i in range(5)) ``` The downside of above approach is, you need to count the number of names on the left of `=` and have exactly the same number of empty lists (e.g. via the `range` call, or more explicitly) on the right hand side. The main thing is, **don't** use someth...
Python instances and attributes: is this a bug or i got it totally wrong?
2,402,887
5
2010-03-08T16:37:56Z
2,402,912
14
2010-03-08T16:41:51Z
[ "python", "class", "attributes", "instance" ]
Suppose you have something like this: ``` class intlist: def __init__(self,l = []): self.l = l def add(self,a): self.l.append(a) def appender(a): obj = intlist() obj.add(a) print obj.l if __name__ == "__main__": for i in range(5): ...
Ah, you've hit one of the common Python gotchas: default values are computed once, then re-used. So, every time `__init__` is called, the *same* list is being used. This is the Pythonic way of doing what you want: ``` def __init__(self, l=None): self.l = [] if l is None else l ``` For a bit more information, che...
Applying style sheets in pyqt
2,404,317
4
2010-03-08T20:03:07Z
2,418,726
9
2010-03-10T16:43:54Z
[ "python", "qt4", "pyqt", "stylesheet", "pyqt4" ]
If i apply a property to a parent widget it is automatically applied for child widgets too.. Is there any way of preventing this?? For example if i set background color as white in a dialog the button,combo boxes and scroll bars looks white as it lacks it native look(have to say it's unpleasant & ugly).. Is there any w...
Found a solution.. Instead of using ``` self.groupBox.setStyleSheet("background-color: rgb(255, 255, 255);\n" "border:1px solid rgb(255, 170, 255);") ``` use specifically using selector types.. ``` self.groupBox.setStyleSheet("QGroupBox { background-color: rgb(255, 255,\ 255); bo...
Does filehandle get closed automatically in Python after it goes out of scope?
2,404,430
17
2010-03-08T20:18:51Z
2,404,471
17
2010-03-08T20:23:18Z
[ "python", "file", "scope" ]
If I do the following, does filehandle get closed automatically as it goes out of scope in Python: ``` def read_contents(file_path): return file(file_path).read() ``` If it doesn't, how can I write this function to close the scope automatically?
It should close the file handle in the file's `__del__` statement, but a better approach would be to use a `with` block: ``` def read_contents(file_path): with open(file_path, 'r') as f: return f.read() ``` See <http://docs.python.org/library/stdtypes.html#file.close> for more information.
Does filehandle get closed automatically in Python after it goes out of scope?
2,404,430
17
2010-03-08T20:18:51Z
2,404,671
23
2010-03-08T20:55:52Z
[ "python", "file", "scope" ]
If I do the following, does filehandle get closed automatically as it goes out of scope in Python: ``` def read_contents(file_path): return file(file_path).read() ``` If it doesn't, how can I write this function to close the scope automatically?
To expand on FogleBird's answer, if you do not explicitly close it then the file will be closed automatically when the file object is destroyed. In CPython this will happen as soon as there are no more references to it, e.g. if it is a local variable in a function and the function ends. However if an exception is throw...
Vectorization of index operation for a scipy.sparse matrix
2,404,437
6
2010-03-08T20:19:50Z
2,404,797
7
2010-03-08T21:14:23Z
[ "python", "indexing", "scipy", "sparse-matrix" ]
The following code runs too slowly even though everything seems to be vectorized. ``` from numpy import * from scipy.sparse import * n = 100000; i = xrange(n); j = xrange(n); data = ones(n); A=csr_matrix((data,(i,j))); x = A[i,j] ``` The problem seems to be that the indexing operation is implemented as a python fu...
You can use `A.diagonal()` to retrieve the diagonal much more quickly (0.0009 seconds vs. 3.8 seconds on my machine) . However, if you want to do arbitary indexing then that is a more complicated question because you aren't using slices so much as a list of indices. The \_get\_single\_element function is being called 1...
How to check if text is "empty" (spaces, tabs, newlines) in Python?
2,405,292
78
2010-03-08T22:29:25Z
2,405,300
130
2010-03-08T22:30:44Z
[ "python", "text", "newline", "tabs", "space" ]
How can I test if the string is empty in Python? For example, `"<space><space><space>"` is empty, so is `"<space><tab><space><newline><space>"`, so is `"<newline><newline><newline><tab><newline>"`, etc.
``` yourString.isspace() ``` "Return true if there are only whitespace characters in the string and there is at least one character, false otherwise." Combine that with a special case for handling the empty string. Alternatively, you could use ``` strippedString = yourString.strip() ``` And then check if strippedS...
How to check if text is "empty" (spaces, tabs, newlines) in Python?
2,405,292
78
2010-03-08T22:29:25Z
2,405,306
17
2010-03-08T22:31:15Z
[ "python", "text", "newline", "tabs", "space" ]
How can I test if the string is empty in Python? For example, `"<space><space><space>"` is empty, so is `"<space><tab><space><newline><space>"`, so is `"<newline><newline><newline><tab><newline>"`, etc.
[`isspace`](http://docs.python.org/3.1/library/stdtypes.html#str.isspace)
How to check if text is "empty" (spaces, tabs, newlines) in Python?
2,405,292
78
2010-03-08T22:29:25Z
2,405,774
19
2010-03-09T00:19:22Z
[ "python", "text", "newline", "tabs", "space" ]
How can I test if the string is empty in Python? For example, `"<space><space><space>"` is empty, so is `"<space><tab><space><newline><space>"`, so is `"<newline><newline><newline><tab><newline>"`, etc.
``` >>> tests = ['foo', ' ', '\r\n\t', '', None] >>> [bool(not s or s.isspace()) for s in tests] [False, True, True, True, True] >>> ```
How do I override __getattr__ in Python without breaking the default behavior?
2,405,590
130
2010-03-08T23:29:32Z
2,405,617
200
2010-03-08T23:35:42Z
[ "python" ]
I want to override the `__getattr__` method on a class to do something fancy but I don't want to break the default behavior. What's the correct way to do this?
Overriding `__getattr__` should be fine -- `__getattr__` is only called as a last resort i.e. if there are no attributes in the instance that match the name. For instance, if you access `foo.bar`, then `__getattr__` will only be called if `foo` has no attribute called `bar`. If the attribute is one you don't want to ha...
How do I override __getattr__ in Python without breaking the default behavior?
2,405,590
130
2010-03-08T23:29:32Z
2,405,667
26
2010-03-08T23:50:51Z
[ "python" ]
I want to override the `__getattr__` method on a class to do something fancy but I don't want to break the default behavior. What's the correct way to do this?
``` class A(object): def __init__(self): self.a = 42 def __getattr__(self, attr): if attr in ["b", "c"]: return 42 raise AttributeError("%r object has no attribute %r" % (self.__class__, attr)) # exception text copied from Python2.6 ``` --- ``` >>> a = A() >>> a.a 4...
Python: Indexing list for element in nested list
2,405,928
10
2010-03-09T00:53:06Z
2,405,951
12
2010-03-09T00:57:39Z
[ "python", "indexing", "list", "nested" ]
I know what I'm looking for. I want python to tell me which list it's in. Here's some pseudocode: ``` item = "a" nested_list = [["a", "b"], ["c", "d"]] list.index(item) #obviously this doesn't work ``` here I would want python to return 0 (because "a" is an element in the first sub-list in the bigger list). I don'...
In Python 2.6 or better, ``` next((i for i, sublist in enumerate(nested_list) if "a" in sublist), -1) ``` assuming e.g. you want a `-1` result if `'a'` is present in none of the sublists. Of course it can be done in older versions of Python, too, but not quite as handily, and since you don't specify which Python ver...
Python Naming Conventions for Dictionaries/Maps/Hashes
2,405,958
24
2010-03-09T00:58:38Z
29,093,203
7
2015-03-17T07:08:24Z
[ "python", "dictionary", "naming-conventions", "mapping" ]
While other questions have tackled the broader category of [sequences](http://stackoverflow.com/questions/659415/python-sequence-naming-convention) and [modules](http://stackoverflow.com/questions/711884/python-naming-conventions-for-modules), I ask this very specific question: **"What naming convention do you use for...
`key_to_value`, for example `surname_to_salary` may be useful when there are closely interrelated maps in code: a to b, b to a, c to b etc.
Get the last '/' or '\\' character in Python
2,406,032
2
2010-03-09T01:19:18Z
2,406,041
7
2010-03-09T01:21:39Z
[ "python", "string" ]
If I have a string that looks like either ``` ./A/B/c.d ``` OR ``` .\A\B\c.d ``` How do I get just the "./A/B/" part? The direction of the slashes can be the same as they are passed. This problem kinda boils down to: How do I get the last of a specific character in a string? Basically, I want the path of a file w...
Normally [`os.path.dirname()`](http://docs.python.org/library/os.path.html#os.path.dirname) is used for this.
Implementing a Patricia Trie for use as a dictionary
2,406,416
9
2010-03-09T03:20:46Z
2,412,468
9
2010-03-09T20:51:45Z
[ "java", "python", "trie", "patricia-trie", "radix" ]
I'm attempting to implement a Patricia Trie with the methods `addWord()`, `isWord()`, and `isPrefix()` as a means to store a large dictionary of words for quick retrieval (including prefix search). I've read up on the concepts but they just aren't clarifying into an implementation. I want to know (in Java or Python cod...
Someone else asked a question about Patricia tries a while ago and I thought about making a Python implementation then, but this time I decided to actually give it a shot (Yes, this is way overboard, but it seemed like a nice little project). What I have made is perhaps not a pure Patricia trie implementation, but I li...
Django formsets: make first required?
2,406,537
28
2010-03-09T03:52:21Z
2,422,221
9
2010-03-11T02:57:37Z
[ "python", "django", "django-forms" ]
These formsets are exhibiting exactly the *opposite* behavior that I want. My view is set up like this: ``` def post(request): # TODO: handle vehicle formset VehicleFormSetFactory = formset_factory(VehicleForm, extra=1) if request.POST: vehicles_formset = VehicleFormSetFactory(request.POST) else: ...
Well... this makes the first form required. ``` class RequiredFormSet(BaseFormSet): def clean(self): if any(self.errors): return if not self.forms[0].has_changed(): raise forms.ValidationError('Please add at least one vehicle.') ``` Only "problem" is that if there are 0 for...
Django formsets: make first required?
2,406,537
28
2010-03-09T03:52:21Z
4,951,032
63
2011-02-09T22:00:41Z
[ "python", "django", "django-forms" ]
These formsets are exhibiting exactly the *opposite* behavior that I want. My view is set up like this: ``` def post(request): # TODO: handle vehicle formset VehicleFormSetFactory = formset_factory(VehicleForm, extra=1) if request.POST: vehicles_formset = VehicleFormSetFactory(request.POST) else: ...
Found a better solution: ``` class RequiredFormSet(BaseFormSet): def __init__(self, *args, **kwargs): super(RequiredFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False ``` Then create your formset like this: ``` MyFormSet = formset_factory(MyF...
Django formsets: make first required?
2,406,537
28
2010-03-09T03:52:21Z
29,954,622
14
2015-04-29T21:09:49Z
[ "python", "django", "django-forms" ]
These formsets are exhibiting exactly the *opposite* behavior that I want. My view is set up like this: ``` def post(request): # TODO: handle vehicle formset VehicleFormSetFactory = formset_factory(VehicleForm, extra=1) if request.POST: vehicles_formset = VehicleFormSetFactory(request.POST) else: ...
New in Django 1.7: you can specify this behaviour with your formset\_factory <https://docs.djangoproject.com/en/1.8/topics/forms/formsets/#validate-min> ``` VehicleFormSetFactory = formset_factory(VehicleForm, min_num=1, validate_min=True, extra=1) ```
Preferred way of defining properties in Python: property decorator or lambda?
2,406,567
32
2010-03-09T04:00:43Z
2,406,592
20
2010-03-09T04:05:22Z
[ "python", "lambda", "properties", "decorator" ]
Which is the preferred way of defining class properties in Python and why? Is it Ok to use both in one class? ``` @property def total(self): return self.field_1 + self.field_2 ``` or ``` total = property(lambda self: self.field_1 + self.field_2) ```
The decorator form is probably best in the case you've shown, where you want to turn the method into a read-only property. The second case is better when you want to provide a setter/deleter/docstring as well as the getter or if you want to add a property that has a different name to the method it derives its value fro...
Preferred way of defining properties in Python: property decorator or lambda?
2,406,567
32
2010-03-09T04:00:43Z
2,407,006
49
2010-03-09T06:11:05Z
[ "python", "lambda", "properties", "decorator" ]
Which is the preferred way of defining class properties in Python and why? Is it Ok to use both in one class? ``` @property def total(self): return self.field_1 + self.field_2 ``` or ``` total = property(lambda self: self.field_1 + self.field_2) ```
For read-only properties I use the decorator, else I usually do something like this: ``` class Bla(object): def sneaky(): def fget(self): return self._sneaky def fset(self, value): self._sneaky = value return locals() sneaky = property(**sneaky()) ``` **update:*...
Accented characters in Matplotlib
2,406,700
17
2010-03-09T04:37:12Z
2,408,847
14
2010-03-09T12:13:12Z
[ "python", "unicode", "matplotlib" ]
Is there a way to get Matplotlib to render accented chars (é,ã,â,etc)? For instance, I'm trying to use accented characters on `set_yticklabels()` and Matplotlib renders squares instead, and when I use `unicode()` it renders the wrong characters. Is there a way to make this work? It turns out you can use u"éã", ...
Prefix the strings with `u` to tell Python that they are Unicode strings: ``` ax.set_yticklabels([u'é', u'ã', u'â']) ```
Why does concatenating a boolean value return an integer?
2,406,959
8
2010-03-09T05:55:01Z
2,406,969
7
2010-03-09T05:57:01Z
[ "python" ]
In python, you can concatenate boolean values, and it would return an integer. Example: ``` >>> True True >>> True + True 2 >>> True + False 1 >>> True + True + True 3 >>> True + True + False 2 >>> False + False 0 ``` Why? Why does this make sense? I understand that `True` is often represented as `1`, whereas `False...
Replace "concatenate" with "add" and `True`/`False` with `1`/`0`, as you've said, and it makes perfect sense. > To sum up True and False in a sentence: they're alternative ways to spell the integer values 1 and 0, with the single difference that str() and repr() return the strings 'True' and 'False' instead of '1' and...
Why does concatenating a boolean value return an integer?
2,406,959
8
2010-03-09T05:55:01Z
2,406,973
21
2010-03-09T05:58:41Z
[ "python" ]
In python, you can concatenate boolean values, and it would return an integer. Example: ``` >>> True True >>> True + True 2 >>> True + False 1 >>> True + True + True 3 >>> True + True + False 2 >>> False + False 0 ``` Why? Why does this make sense? I understand that `True` is often represented as `1`, whereas `False...
Because In Python, `bool` is the subclass/subtype of `int`. ``` >>> issubclass(bool,int) True ``` **Update**: From [**boolobject.c**](http://svn.python.org/projects/python/trunk/Objects/boolobject.c) ``` /* Boolean type, a subtype of int */ /* We need to define bool_print to override int_print */ bool_print fp...
Python urllib2 Basic Auth Problem
2,407,126
57
2010-03-09T06:50:59Z
2,955,687
149
2010-06-02T07:18:38Z
[ "python", "authentication", "urllib2" ]
Update: based on Lee's comment I decided to condense my code to a really simple script and run it from the command line: ``` import urllib2 import sys username = sys.argv[1] password = sys.argv[2] url = sys.argv[3] print("calling %s with %s:%s\n" % (url, username, password)) passman = urllib2.HTTPPasswordMgrWithDefa...
The problem could be that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the Foursquare servers don't do "totally standard authentication" then the libraries won't work. Try using headers to do authen...
Python - merge items of two lists into a list of tuples
2,407,398
108
2010-03-09T07:51:46Z
2,407,405
166
2010-03-09T07:52:50Z
[ "python", "list", "tuples" ]
What's the pythonic way of achieving the following? ``` list_a = [1, 2, 3, 4] list_b = [5, 6, 7, 8] #Need to create a of tuples from list_a and list_b list_c = [(1,5), (2,6), (3,7), (4,8)] ``` Each member of list\_c is a tuple, whose first member is from list\_a and the second is from list\_b.
``` >>> list_a = [1, 2, 3, 4] >>> list_b = [5, 6, 7, 8] >>> zip(list_a, list_b) [(1, 5), (2, 6), (3, 7), (4, 8)] ```
Python - merge items of two lists into a list of tuples
2,407,398
108
2010-03-09T07:51:46Z
2,407,425
7
2010-03-09T07:55:50Z
[ "python", "list", "tuples" ]
What's the pythonic way of achieving the following? ``` list_a = [1, 2, 3, 4] list_b = [5, 6, 7, 8] #Need to create a of tuples from list_a and list_b list_c = [(1,5), (2,6), (3,7), (4,8)] ``` Each member of list\_c is a tuple, whose first member is from list\_a and the second is from list\_b.
Youre looking for the builtin function [zip](http://docs.python.org/library/functions.html#zip).
Python - merge items of two lists into a list of tuples
2,407,398
108
2010-03-09T07:51:46Z
5,146,593
33
2011-02-28T19:26:30Z
[ "python", "list", "tuples" ]
What's the pythonic way of achieving the following? ``` list_a = [1, 2, 3, 4] list_b = [5, 6, 7, 8] #Need to create a of tuples from list_a and list_b list_c = [(1,5), (2,6), (3,7), (4,8)] ``` Each member of list\_c is a tuple, whose first member is from list\_a and the second is from list\_b.
In python 3.0 zip returns a zip object. You can get a list out of it by calling `list(zip(a, b))`.
What does the term "blocking" mean in programming?
2,407,589
17
2010-03-09T08:38:07Z
2,407,601
19
2010-03-09T08:40:07Z
[ "python", "api", "blocking" ]
Could someone provide a layman definition and use case?
"Blocking" means that the caller waits until the callee finishes its processing. For instance, a "blocking read" from a socket waits until there is data to return; a "non-blocking" read does not, it just returns an indication (usually a count) of whether there was something read. You hear the term mostly around APIs t...
Python nonblocking console input
2,408,560
24
2010-03-09T11:17:05Z
2,409,034
23
2010-03-09T12:41:32Z
[ "python", "windows", "input" ]
I am trying to make a simple IRC client in Python (as kind of a project while I learn the language). I have a loop that I use to receive and parse what the IRC server sends me, but if I use `raw_input` to input stuff, it stops the loop dead in its tracks until I input something (obviously). How can I input something ...
For Windows, console only, use the [`msvcrt`](http://www.python.org/doc/2.5.2/lib/msvcrt-console.html) module: ``` import msvcrt num = 0 done = False while not done: print num num += 1 if msvcrt.kbhit(): print "you pressed",msvcrt.getch(),"so now i will quit" done = True ``` For Linux, t...
Python nonblocking console input
2,408,560
24
2010-03-09T11:17:05Z
19,655,992
7
2013-10-29T10:45:01Z
[ "python", "windows", "input" ]
I am trying to make a simple IRC client in Python (as kind of a project while I learn the language). I have a loop that I use to receive and parse what the IRC server sends me, but if I use `raw_input` to input stuff, it stops the loop dead in its tracks until I input something (obviously). How can I input something ...
Here a solution that runs under linux and windows using a seperate thread: ``` import sys import threading import time import Queue def add_input(input_queue): while True: input_queue.put(sys.stdin.read(1)) def foobar(): input_queue = Queue.Queue() input_thread = threading.Thread(target=add_inpu...
Python nonblocking console input
2,408,560
24
2010-03-09T11:17:05Z
22,085,679
11
2014-02-28T03:36:50Z
[ "python", "windows", "input" ]
I am trying to make a simple IRC client in Python (as kind of a project while I learn the language). I have a loop that I use to receive and parse what the IRC server sends me, but if I use `raw_input` to input stuff, it stops the loop dead in its tracks until I input something (obviously). How can I input something ...
This is the most awesome [solution](http://home.wlu.edu/~levys/software/kbhit.py)1 I've ever seen. Pasted here in case link goes down: ``` #!/usr/bin/env python ''' A Python class implementing KBHIT, the standard keyboard-interrupt poller. Works transparently on Windows and Posix (Linux, Mac OS X). Doesn't work with ...
why does python.subprocess hang after proc.communicate()?
2,408,650
5
2010-03-09T11:35:21Z
2,408,670
19
2010-03-09T11:38:22Z
[ "python", "subprocess" ]
I've got an interactive program called `my_own_exe`. First, it prints out `alive`, then you input `S\n` and then it prints out `alive` again. Finally you input `L\n`. It does some processing and exits. However, when I call it from the following python script, the program seemed to hang after printing out the first 'al...
From the [docs for `communicate`](http://docs.python.org/library/subprocess#subprocess.Popen.communicate): > Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. **Wait for process to terminate.** So after `communicate()` runs, the process has been **terminated**....
Python: How expensive is to create a small list many times?
2,409,472
9
2010-03-09T13:56:31Z
2,409,523
16
2010-03-09T14:03:04Z
[ "python" ]
I encounter the following small annoying dilemma over and over again in Python: Option 1: cleaner but slower(?) if called many times since a\_list get re-created for each call of do\_something() ``` def do_something(): a_list = ["any", "think", "whatever"] # read something from a_list ``` Option 2: Ugl...
What's ugly about it? Are the contents of the list always constants, as in your example? If so: recent versions of Python (since 2.4) will optimise that by evaluating the constant expression and keeping the result but only if it's a tuple. So you could change it to being a tuple. Or you could stop worrying about small...
How can I produce student-style graphs using matplotlib?
2,409,774
6
2010-03-09T14:37:21Z
2,410,136
8
2010-03-09T15:24:22Z
[ "python", "matplotlib", "wxpython" ]
I am experimenting with matplotlib at the moment. Some time ago I used Excel VBA code to produce images such as the one attached. You will notice it is not presented in a scientific/research style but rather as if produced by a school-student on graph paper - with three different grid-line styles. Is there a fairly s...
Yes, you can use [spines](http://matplotlib.sourceforge.net/examples/pylab_examples/spine_placement_demo.html) for this. ``` import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, FormatStrFormatter import numpy as np fig = plt.figure(1) ax = fig.add_subplot(111) # set up axis ax.spines['left...
Should we use Pylons or PHP for our webapp?
2,409,812
4
2010-03-09T14:42:54Z
2,409,852
9
2010-03-09T14:48:39Z
[ "php", "python", "pylons" ]
My friend and I are planning on building a sort of a forum type of webapp. We've used the major PHP frameworks but we're really thinking about using Python specifically the Pylons framework for our app. Although we're competent PHP programmers, we're somewhat noobs at Python (We could create practical scripts and such)...
Decide what you want to put your focus on, being productive or learning a new language: * If you want to **learn** Pylons and Python, use Pylon and Python. * If you want to **deliver** a stable forum software, use PHP, because that's what you're competent at. Note: I should add that this is not meant to imply that yo...
Adding up time durations in Python
2,410,454
2
2010-03-09T16:04:54Z
2,410,613
9
2010-03-09T16:26:25Z
[ "python", "datetime", "time" ]
I would like to add up a series of splits in Python. The times begin as strings like "00:08:30.291". I can't seem to find the right way to use the Python objects or API to make this convenient/elegant. It seems that the time object doesn't use microseconds, so I'm using datetime's strptime to parse the strings, success...
What you're working with is time differences, that's why using [`datetime.timedelta`](https://docs.python.org/2/library/datetime.html#timedelta-objects) is only appropriate here: ``` >>> import datetime >>> d1 = datetime.datetime.strptime("00:08:30.291", "%H:%M:%S.%f") >>> d1 datetime.datetime(1900, 1, 1, 0, 8, 30, 29...
Python - file contents to nested list
2,410,619
3
2010-03-09T16:27:12Z
2,410,699
8
2010-03-09T16:38:47Z
[ "python", "file", "list", "newline", "tabs" ]
I have a file in tab delimited format with trailing newline characters, e.g., ``` 123 abc 456 def 789 ghi ``` I wish to write function to convert the contents of the file into a nested list. To date I have tried: ``` def ls_platform_ann(): keyword = [] for line in open( "file", "r" ).readlines(): ...
You want the [`csv`](http://docs.python.org/library/csv.html) module. ``` import csv source = "123\tabc\n456\tdef\n789\tghi" lines = source.split("\n") reader = csv.reader(lines, delimiter='\t') print [word for word in [row for row in reader]] ``` Output: ``` [['123', 'abc'], ['456', 'def'], ['789', 'ghi']] ``` ...
side effect gotchas in python/numpy? horror stories and narrow escapes wanted
2,411,459
7
2010-03-09T18:19:54Z
2,411,680
9
2010-03-09T18:53:22Z
[ "python", "matlab", "functional-programming", "side-effects" ]
I am considering moving from Matlab to Python/numpy for data analysis and numerical simulations. I have used Matlab (and SML-NJ) for years, and am very comfortable in the functional environment without side effects (barring I/O), but am a little reluctant about the side effects in Python. Can people share their favorit...
Confusing references to the same (mutable) object with references to separate objects is indeed a "gotcha" (suffered by all non-functional languages, ones which have mutable objects and, of course, references). A frequently seen bug in beginners' Python code is misusing a default value which is mutable, e.g.: ``` def ...
Function to create in-memory zip file and return as http response
2,411,514
6
2010-03-09T18:28:16Z
2,411,540
11
2010-03-09T18:32:21Z
[ "python", "zip", "stringio" ]
I am avoiding the creation of files on disk, this is what I have got so far: ``` def get_zip(request): import zipfile, StringIO i = open('picture.jpg', 'rb').read() o = StringIO.StringIO() zf = zipfile.ZipFile(o, mode='w') zf.writestr('picture.jpg', i) zf.close() o.seek(0) response = Ht...
For `StringIO` you should generally use `o.getvalue()` to get the result. Also, if you want to add a normal file to the zip file, you can use `zf.write('picture.jpg')`. You don't need to manually read it.
Python Socket Send Buffer Vs. Str
2,411,864
9
2010-03-09T19:17:38Z
2,411,981
18
2010-03-09T19:36:34Z
[ "python", "string", "sockets", "send" ]
I am trying to get a basic server (copied from Beginning Python) to send a str. The error: ``` c.send( "XXX" ) TypeError: must be bytes or buffer, not str ``` It seems to work when pickling an object. All of the examples I found, seem to be able to send a string no problem. Any help would be appreciated, Stephen ...
It seems you try to use Python 2.x examples in Python 3 and you hit one of the main differences between those Python version. For Python < 3 'strings' are in fact binary strings and 'unicode objects' are the right text objects (as they can contain any Unicode characters). In Python 3 unicode strings are the 'regular ...
Python Socket Send Buffer Vs. Str
2,411,864
9
2010-03-09T19:17:38Z
2,412,100
11
2010-03-09T19:54:27Z
[ "python", "string", "sockets", "send" ]
I am trying to get a basic server (copied from Beginning Python) to send a str. The error: ``` c.send( "XXX" ) TypeError: must be bytes or buffer, not str ``` It seems to work when pickling an object. All of the examples I found, seem to be able to send a string no problem. Any help would be appreciated, Stephen ...
To add to Jacek Konieczny's answer: You can also use [str.encode()](http://docs.python.org/3.1/library/stdtypes.html#str.encode) to get bytes from a string. If you have the string in a variable instead of a literal, you can call encode and it will return an equivalent series of bytes.
Serializing a suds object in python
2,412,486
11
2010-03-09T20:54:08Z
15,678,861
27
2013-03-28T10:01:06Z
[ "python", "soap", "pickle", "suds" ]
Ok I'm working on getting better with python, so I'm not sure this is the right way to go about what I'm doing to begin with, but here's my current problem... I need to get some information via a SOAP method, and only use part of the information now but store the entire result for future uses (we need to use the servi...
I have been using following approach to convert Suds object into JSON: ``` from suds.sudsobject import asdict def recursive_asdict(d): """Convert Suds object into serializable format.""" out = {} for k, v in asdict(d).iteritems(): if hasattr(v, '__keylist__'): out[k] = recursive_asdict...
Good ways to sort a queryset? - Django
2,412,770
54
2010-03-09T21:37:57Z
2,412,831
95
2010-03-09T21:48:45Z
[ "python", "django", "django-models" ]
what I'm trying to do is this: * get the 30 Authors with highest score ( `Author.objects.order_by('-score')[:30]` ) * order the authors by `last_name` --- Any suggestions?
What about ``` import operator auths = Author.objects.order_by('-score')[:30] ordered = sorted(auths, key=operator.attrgetter('last_name')) ``` In Django 1.4 and newer you can order by providing multiple fields. Reference: <https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by> **order\_by(\*fields...
Good ways to sort a queryset? - Django
2,412,770
54
2010-03-09T21:37:57Z
2,413,908
7
2010-03-10T01:28:54Z
[ "python", "django", "django-models" ]
what I'm trying to do is this: * get the 30 Authors with highest score ( `Author.objects.order_by('-score')[:30]` ) * order the authors by `last_name` --- Any suggestions?
I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones. At first I thought that because Django's `QuerySet.objects.order_by` method accepts multiple arguments, you could easily chain them: ``` ordered_authors = Author.objects.order_by('-score', 'last_name')[:30] ``` But, it do...
Circular import issues with Django apps that have dependencies on each other
2,412,995
5
2010-03-09T22:16:34Z
2,413,109
7
2010-03-09T22:33:41Z
[ "python", "django", "design-patterns", "import" ]
I am writing a couple of django apps wich by design is coupled together. But i get sircular import problems. I know it might be bad design, so please give examples of better solutions, but i cant seem to find a better suited design. So if there isnt a better design, how to solve this one? It is basically two django ap...
Both models do not need many-to-many fields. Do not put both sides of a many-to-many relationship in your model. When you put in one many-to-many relationship, *Django inserts the other side of the relationship for you*. <http://docs.djangoproject.com/en/1.1/topics/db/queries/#many-to-many-relationships> > Both end...
timedelta convert to time or int and store it in GAE (python) datastore
2,413,144
4
2010-03-09T22:37:50Z
2,416,049
12
2010-03-10T10:20:29Z
[ "python", "google-app-engine" ]
It looks like this has been covered somewhat in other questions, but I'm still fairly confused on how to actually do this. My lack of experience isn't helping much with that. I have two DateTimeProperties - StartTime and EndTime. I'm subtracting StartTime from EndTime to get the Duration. From my previous question (th...
To make this as easy as possible to work with, there's two steps: Converting the timedelta to an int or a float, and storing it in the datastore. First things first, converting a timedelta to a microtime: ``` def timedelta_to_microtime(td): return td.microseconds + (td.seconds + td.days * 86400) * 1000000 ``` You d...
how to convert a timedelta object into a datetime object
2,413,391
7
2010-03-09T23:22:45Z
2,413,400
17
2010-03-09T23:25:01Z
[ "python", "datetime", "timedelta" ]
What is the proper way to convert a timedelta object into a datetime object? I immediately think of something like `datetime(0)+deltaObj` but that's not very nice... isn't there a `toDateTime()` function or something of the sort?
It doesn't make sense to convert a timedelta into a datetime, but it does make sense to pick an initial or starting datetime and add or subtract a timedelta from that. ``` >>> import datetime >>> today = datetime.datetime.today() >>> today datetime.datetime(2010, 3, 9, 18, 25, 19, 474362) >>> today + datetime.timedelt...
Weighted standard deviation in NumPy?
2,413,522
36
2010-03-09T23:53:36Z
2,415,343
57
2010-03-10T08:07:16Z
[ "python", "numpy", "weighted", "standard-deviation" ]
`numpy.average()` has a weights option, but `numpy.std()` does not. Does anyone have suggestions for a workaround?
How about the following short "manual calculation"? ``` def weighted_avg_and_std(values, weights): """ Return the weighted average and standard deviation. values, weights -- Numpy ndarrays with the same shape. """ average = numpy.average(values, weights=weights) variance = numpy.average((value...
Stream a file to the HTTP response in Pylons
2,413,707
6
2010-03-10T00:35:20Z
2,413,943
7
2010-03-10T01:35:25Z
[ "python", "http", "pylons" ]
I have a Pylons controller action that needs to return a file to the client. (The file is outside the web root, so I can't just link directly to it.) The simplest way is, of course, this: ``` with open(filepath, 'rb') as f: response.write(f.read()) ``` That works, but it's obviously inefficient for large ...
The correct tool to use is shutil.copyfileobj, which copies from one to the other a chunk at a time. Example usage: ``` import shutil with open(filepath, 'r') as f: shutil.copyfileobj(f, response) ``` This will not result in very large memory usage, and does not require implementing the code yourself. The usual...
Would it be possible to integrate Python or Perl with Ruby?
2,413,878
10
2010-03-10T01:20:36Z
2,414,056
7
2010-03-10T02:06:05Z
[ "python", "ruby", "perl" ]
Would it be possible to integrate Python (and/or Perl) and Ruby? I've looked at <http://www.goto.info.waseda.ac.jp/~fukusima/ruby/python/doc/> and <http://code.google.com/p/ruby-perl/> , but they both seem rather outdated. Has someone generated a Ruby interface for Python's C API? Edit: Python can be integrated with ...
My school (Georgia Tech), along with Bryn Mawr and Microsoft Research, are doing a project right now called [Pyjama](http://wiki.roboteducation.org/Pyjama). Basically, it uses the Microsoft DLR to allow you to freely mix Python and Ruby. I haven't tried it, but it sounds pretty cool. Here's an example from the website...
How do I make this sorting case insensitive?
2,414,201
2
2010-03-10T02:58:29Z
2,414,253
7
2010-03-10T03:10:24Z
[ "python", "list", "sorting", "dictionary" ]
``` def sortProfiles(p): return sorted(p, key=itemgetter('first_name')) ``` I have a list with dictionaries. This function allows me to sort them by their first\_name. However, it's case-sensitive.
``` >>> from operator import itemgetter >>> p = [{'fn':'bill'}, {'fn':'Bob'}, {'fn':'bobby'}] >>> sorted(p, key=itemgetter('fn')) [{'fn': 'Bob'}, {'fn': 'bill'}, {'fn': 'bobby'}] >>> sorted(p, key=lambda x: x['fn'].lower()) [{'fn': 'bill'}, {'fn': 'Bob'}, {'fn': 'bobby'}] >>> ```
Python string class like StringBuilder in C#?
2,414,667
43
2010-03-10T05:08:42Z
2,414,675
37
2010-03-10T05:11:29Z
[ "python", "string" ]
Is there some string class in Python like `StringBuilder` in C#?
There is no one-to-one correlation. For a really good article please see [Efficient String Concatenation in Python](https://waymoot.org/home/python_string/): > Building long strings in the Python > progamming language can sometimes > result in very slow running code. In > this article I investigate the > computational...
Python string class like StringBuilder in C#?
2,414,667
43
2010-03-10T05:08:42Z
2,414,916
7
2010-03-10T06:21:54Z
[ "python", "string" ]
Is there some string class in Python like `StringBuilder` in C#?
Python has several things that fulfill similar purposes: * One common way to build large strings from pieces is to grow a list of strings and join it when you are done. This is a frequently-used Python idiom. + To build strings incorporating data with formatting, you would do the formatting separately. * For inserti...
Python string class like StringBuilder in C#?
2,414,667
43
2010-03-10T05:08:42Z
13,345,099
19
2012-11-12T14:02:54Z
[ "python", "string" ]
Is there some string class in Python like `StringBuilder` in C#?
I have used the code of Oliver Crow (link given by Andrew Hare) and adapted it a bit to tailor Python 2.7.3. (by using timeit package). I ran on my personal computer, Lenovo T61, 6GB RAM, Debian GNU/Linux 6.0.6 (squeeze). Here is the result for 10,000 iterations: ``` method1: 0.0538418292999 secs process size 4800 k...
Python string class like StringBuilder in C#?
2,414,667
43
2010-03-10T05:08:42Z
19,742,456
7
2013-11-02T13:37:50Z
[ "python", "string" ]
Is there some string class in Python like `StringBuilder` in C#?
Using method 5 from above (The Pseudo File) we can get very good perf and flexibility ``` from cStringIO import StringIO class StringBuilder: _file_str = None def __init__(self): self._file_str = StringIO() def Append(self, str): self._file_str.write(str) def __str__(self): ...
Concepts and tools required to scale up algorithms
2,414,915
5
2010-03-10T06:21:50Z
2,415,028
9
2010-03-10T06:49:57Z
[ "python", "multithreading", "concurrency", "hadoop" ]
I'd like to begin thinking about how I can scale up my algorithms that I write for data analysis so that they can be applied to arbitrarily large sets of data. I wonder what are the relevant concepts (threads, concurrency, immutable data structures, recursion) and tools (Hadoop/MapReduce, Terracota, and Eucalyptus) to ...
While languages and associated technologies/frameworks are important for scaling, they tend to pale in comparison to the importance of the algorithms, data structure, and architectures. Forget threads: the number of cores you can exploit that way is just too limited -- you want separate processes exchanging messages, s...
Find element with attribute with minidom
2,415,115
8
2010-03-10T07:11:21Z
2,415,154
12
2010-03-10T07:19:52Z
[ "python", "xml", "minidom" ]
Given ``` <field name="frame.time_delta_displayed" showname="Time delta from previous displayed frame: 0.000008000 seconds" size="0" pos="0" show="0.000008000"/> <field name="frame.time_relative" showname="Time since reference or first frame: 0.000008000 seconds" size="0" pos="0" show="0.000008000"/> <field name="fram...
I don't think you can. From the parent `element`, you need to ``` for subelement in element.GetElementsByTagName("field"): if subelement.hasAttribute("frame.len"): do_something() ``` Reacting to your comment from March 11, if the structure of your documents is stable and free of nasty surprises (like ang...
Iterating through two lists in Django templates
2,415,865
18
2010-03-10T09:51:09Z
2,415,934
9
2010-03-10T10:02:28Z
[ "python", "django", "django-templates" ]
I want to do the below list iteration in django templates: ``` foo = ['foo', 'bar']; moo = ['moo', 'loo']; for (a, b) in zip(foo, moo): print a, b ``` django code: ``` {%for a, b in zip(foo, moo)%} {{a}} {{b}} {%endfor%} ``` I get the below error when I try this: ``` File "/base/python_lib/versions/third_...
It's possible to do ``` {% for ab in mylist %} {{ab.0}} {{ab.1}} {% endfor %} ``` but you cannot make a call to `zip` within the `for` structure. You'll have to store the zipped list in another variable first, then iterate over it.
Iterating through two lists in Django templates
2,415,865
18
2010-03-10T09:51:09Z
4,238,261
30
2010-11-21T14:09:58Z
[ "python", "django", "django-templates" ]
I want to do the below list iteration in django templates: ``` foo = ['foo', 'bar']; moo = ['moo', 'loo']; for (a, b) in zip(foo, moo): print a, b ``` django code: ``` {%for a, b in zip(foo, moo)%} {{a}} {{b}} {%endfor%} ``` I get the below error when I try this: ``` File "/base/python_lib/versions/third_...
You can use a zip in your view: ``` list = zip(list1, list2) return render_to_response('template.html', {'list': list, ... } ``` and in your template use ``` {% for item1, item2 in list %} ``` to iterate through both lists.
Iterating through two lists in Django templates
2,415,865
18
2010-03-10T09:51:09Z
14,857,664
16
2013-02-13T16:02:14Z
[ "python", "django", "django-templates" ]
I want to do the below list iteration in django templates: ``` foo = ['foo', 'bar']; moo = ['moo', 'loo']; for (a, b) in zip(foo, moo): print a, b ``` django code: ``` {%for a, b in zip(foo, moo)%} {{a}} {{b}} {%endfor%} ``` I get the below error when I try this: ``` File "/base/python_lib/versions/third_...
Simply define zip as a [template filter](https://docs.djangoproject.com/en/dev/howto/custom-template-tags/): ``` @register.filter(name='zip') def zip_lists(a, b): return zip(a, b) ``` Then, in your template: ``` {%for a, b in first_list|zip:second_list %} {{a}} {{b}} {%endfor%} ```
How to join the same table in sqlalchemy
2,416,454
12
2010-03-10T11:30:41Z
2,416,990
7
2010-03-10T12:59:35Z
[ "python", "sqlalchemy" ]
I'm trying to join the same table in sqlalchemy. This is a minimial version of what I tried: ``` #!/usr/bin/env python import sqlalchemy as sa from sqlalchemy import create_engine from sqlalchemy.orm import mapper, sessionmaker, aliased engine = create_engine('sqlite:///:memory:', echo=True) metadata = sa.MetaData()...
For query.[outer]join, you specify as list of joins (which is different to expression.[outer]join.) So I needed to put the 2 elements of the join, the table and the onclause in a tuple, like this: ``` q = db_session.query(Device, ParentDevice)\ .outerjoin( (ParentDevice, Device.parent_device_id==...
How to create a password entry field using Tkinter
2,416,486
15
2010-03-10T11:35:46Z
2,416,513
26
2010-03-10T11:39:06Z
[ "python", "tkinter" ]
I am trying to code a login window using Tkinter but I'm not able to hide the password text in asterisk format. This means the password entry is plain text, which has to be avoided. Any idea how to do it?
A quick google search yelded this ``` widget = Entry(parent, show="*", width=15) ``` where: `widget` is the text field, `parent` is the parent widget (a window, a frame, whatever), `show` is the character to echo (that is the character shown in the `Entry`) and `width` is the widget's width.
How to create a password entry field using Tkinter
2,416,486
15
2010-03-10T11:35:46Z
23,282,994
8
2014-04-25T02:03:46Z
[ "python", "tkinter" ]
I am trying to code a login window using Tkinter but I'm not able to hide the password text in asterisk format. This means the password entry is plain text, which has to be avoided. Any idea how to do it?
If you don't want to create a brand new Entry widget, you can do this: ``` myEntry.config(show="*"); ``` To make it back to normal again, do this: ``` myEntry.config(show=""); ``` I discovered this by examining the previous answer, and using the help function in the Python interpreter (e.g. help(tkinter.Entry) afte...
How to get the content of a Html page in Python
2,416,823
4
2010-03-10T12:32:20Z
2,416,841
12
2010-03-10T12:35:10Z
[ "python", "html", "parsing" ]
I have downloaded the web page into an html file. I am wondering what's the simplest way to get the content of that page. By content, I mean I need the strings that a browser would display. To be clear: Input: ``` <html><head><title>Page title</title></head> <body><p id="firstpara" align="center">This is para...
Parse the HTML with [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup). To get all the text, without the tags, try: ``` ''.join(soup.findAll(text=True)) ```
How to get the content of a Html page in Python
2,416,823
4
2010-03-10T12:32:20Z
2,419,998
7
2010-03-10T19:43:26Z
[ "python", "html", "parsing" ]
I have downloaded the web page into an html file. I am wondering what's the simplest way to get the content of that page. By content, I mean I need the strings that a browser would display. To be clear: Input: ``` <html><head><title>Page title</title></head> <body><p id="firstpara" align="center">This is para...
Personally, I use lxml because it's a swiss-army knife... ``` from lxml import html print html.parse('http://someurl.at.domain').xpath('//body')[0].text_content() ``` This tells lxml to retrieve the page, locate the `<body>` tag then extract and print all the text. I do a lot of page parsing and a regex is the wron...
How to check with python if a table is empty?
2,417,545
3
2010-03-10T14:22:18Z
2,417,593
7
2010-03-10T14:27:17Z
[ "python", "mysql" ]
Using python and MySQLdb, how can I check if there are any records in a mysql table (innodb)?
Just select a single row. If you get nothing back, it's empty! (Example from the MySQLdb site) ``` import MySQLdb db = MySQLdb.connect(passwd="moonpie", db="thangs") results = db.query("""SELECT * from mytable limit 1""") if not results: print "This table is empty!" ```
How to make the angles in a matplotlib polar plot go clockwise with 0° at the top?
2,417,794
21
2010-03-10T14:53:13Z
2,433,287
17
2010-03-12T14:20:07Z
[ "python", "numpy", "matplotlib", "plot" ]
I am using matplotlib and numpy to make a polar plot. Here is some sample code: ``` import numpy as N import matplotlib.pyplot as P angle = N.arange(0, 360, 10, dtype=float) * N.pi / 180.0 arbitrary_data = N.abs(N.sin(angle)) + 0.1 * (N.random.random_sample(size=angle.shape) - 0.5) P.clf() P.polar(angle, arbitrary_d...
I found it out -- matplotlib allows you to create custom projections. I created one that inherits from `PolarAxes`. ``` import numpy as N import matplotlib.pyplot as P from matplotlib.projections import PolarAxes, register_projection from matplotlib.transforms import Affine2D, Bbox, IdentityTransform class NorthPola...
How to make the angles in a matplotlib polar plot go clockwise with 0° at the top?
2,417,794
21
2010-03-10T14:53:13Z
8,302,530
24
2011-11-28T21:24:34Z
[ "python", "numpy", "matplotlib", "plot" ]
I am using matplotlib and numpy to make a polar plot. Here is some sample code: ``` import numpy as N import matplotlib.pyplot as P angle = N.arange(0, 360, 10, dtype=float) * N.pi / 180.0 arbitrary_data = N.abs(N.sin(angle)) + 0.1 * (N.random.random_sample(size=angle.shape) - 0.5) P.clf() P.polar(angle, arbitrary_d...
Updating this question, in Matplotlib 1.1, there are now two methods in `PolarAxes` for setting the theta direction (CW/CCW) and location for theta=0. Check out <http://matplotlib.sourceforge.net/devel/add_new_projection.html#matplotlib.projections.polar.PolarAxes> Specifically, see `set_theta_direction()` and `set_t...
How to make the angles in a matplotlib polar plot go clockwise with 0° at the top?
2,417,794
21
2010-03-10T14:53:13Z
11,475,973
10
2012-07-13T18:09:50Z
[ "python", "numpy", "matplotlib", "plot" ]
I am using matplotlib and numpy to make a polar plot. Here is some sample code: ``` import numpy as N import matplotlib.pyplot as P angle = N.arange(0, 360, 10, dtype=float) * N.pi / 180.0 arbitrary_data = N.abs(N.sin(angle)) + 0.1 * (N.random.random_sample(size=angle.shape) - 0.5) P.clf() P.polar(angle, arbitrary_d...
To expand klimaat's answer with an example: ``` import math angle=[0.,5.,10.,15.,20.,25.,30.,35.,40.,45.,50.,55.,60.,65.,70.,75.,\ 80.,85.,90.,95.,100.,105.,110.,115.,120.,125.] angle = [math.radians(a) for a in angle] lux=[12.67,12.97,12.49,14.58,12.46,12.59,11.26,10.71,17.74,25.95,\ 15.07,7.43,6.30,6....
Can I use the variable name "type" as function argument in Python?
2,417,979
11
2010-03-10T15:13:20Z
2,418,007
21
2010-03-10T15:16:09Z
[ "python" ]
Can I use `type` as a name for a python function argument? ``` def fun(name, type): .... ```
You can, but you shouldn't. It's not a good habit to use names of built-ins because they will override the name of the built-in in that scope. If you must use that word, modify it slightly for the given context. While it probably won't matter for a small project that is not using `type`, it's better to stay out of the...
Can I use the variable name "type" as function argument in Python?
2,417,979
11
2010-03-10T15:13:20Z
2,418,044
8
2010-03-10T15:20:05Z
[ "python" ]
Can I use `type` as a name for a python function argument? ``` def fun(name, type): .... ```
You can, and that's fine. Even though the advice not to shadow builtins is important, it applies more strongly if an identifier is common, as it will increase confusion and collision. It does not appear *type* will cause confusion here (but you'll know about that more than anyone else), and I could use exactly what you...