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 - Intersection of two lists
642,763
271
2009-03-13T13:42:44Z
642,992
21
2009-03-13T14:35:58Z
[ "python", "list", "intersection" ]
I know how to get an intersection of two flat lists: ``` b1 = [1,2,3,4,5,9,11,15] b2 = [4,5,6,7,8] b3 = [val for val in b1 if val in b2] ``` or ``` def intersect(a, b): return list(set(a) & set(b)) print intersect(b1, b2) ``` But when I have to find intersection for nested lists then my problems starts: ``` c...
### Pure list comprehension version ``` >>> c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63] >>> c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]] >>> c1set = frozenset(c1) ``` Flatten variant: ``` >>> [n for lst in c2 for n in lst if n in c1set] [13, 32, 7, 13, 28, 1, 6] ``` Nested variant: ``` >>>...
Python - Intersection of two lists
642,763
271
2009-03-13T13:42:44Z
1,404,146
14
2009-09-10T08:50:21Z
[ "python", "list", "intersection" ]
I know how to get an intersection of two flat lists: ``` b1 = [1,2,3,4,5,9,11,15] b2 = [4,5,6,7,8] b3 = [val for val in b1 if val in b2] ``` or ``` def intersect(a, b): return list(set(a) & set(b)) print intersect(b1, b2) ``` But when I have to find intersection for nested lists then my problems starts: ``` c...
The functional approach: ``` input_list = [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] result = reduce(set.intersection, map(set, input_list)) ``` and it can be applied to the more general case of 1+ lists
Python - Intersection of two lists
642,763
271
2009-03-13T13:42:44Z
1,875,493
39
2009-12-09T17:26:06Z
[ "python", "list", "intersection" ]
I know how to get an intersection of two flat lists: ``` b1 = [1,2,3,4,5,9,11,15] b2 = [4,5,6,7,8] b3 = [val for val in b1 if val in b2] ``` or ``` def intersect(a, b): return list(set(a) & set(b)) print intersect(b1, b2) ``` But when I have to find intersection for nested lists then my problems starts: ``` c...
For people just looking to find the intersection of two lists, the Asker provided two methods: > ``` > b1 = [1,2,3,4,5,9,11,15] > b2 = [4,5,6,7,8] > b3 = [val for val in b1 if val in b2] > ``` > > and > > ``` > def intersect(a, b): > return list(set(a) & set(b)) > > print intersect(b1, b2) > ``` But there is a h...
How can I use numpy.correlate to do autocorrelation?
643,699
52
2009-03-13T17:07:53Z
676,302
57
2009-03-24T06:09:02Z
[ "python", "math", "numpy", "numerical-methods" ]
I need to do auto-correlation of a set of numbers, which as I understand it is just the correlation of the set with itself. I've tried it using numpy's correlate function, but I don't believe the result, as it almost always gives a vector where the first number is *not* the largest, as it ought to be. So, this questi...
To answer your first question, `numpy.correlate(a, v, mode)` is performing the convolution of `a` with the reverse of `v` and giving the results clipped by the specified mode. The [definition of convolution](http://mathworld.wolfram.com/Convolution.html), C(t)=∑ -∞ < i < ∞ aivt+i where -∞ < t < ∞, allows for...
How can I use numpy.correlate to do autocorrelation?
643,699
52
2009-03-13T17:07:53Z
7,981,132
10
2011-11-02T13:27:37Z
[ "python", "math", "numpy", "numerical-methods" ]
I need to do auto-correlation of a set of numbers, which as I understand it is just the correlation of the set with itself. I've tried it using numpy's correlate function, but I don't believe the result, as it almost always gives a vector where the first number is *not* the largest, as it ought to be. So, this questi...
Auto-correlation comes in two versions: statistical and convolution. They both do the same, except for a little detail: The former is normalized to be on the interval [-1,1]. Here is an example of how you do the statistical one: ``` def acf(x, length=20): return numpy.array([1]+[numpy.corrcoef(x[:-i], x[i:]) \ ...
How can I use numpy.correlate to do autocorrelation?
643,699
52
2009-03-13T17:07:53Z
17,090,200
7
2013-06-13T14:52:10Z
[ "python", "math", "numpy", "numerical-methods" ]
I need to do auto-correlation of a set of numbers, which as I understand it is just the correlation of the set with itself. I've tried it using numpy's correlate function, but I don't believe the result, as it almost always gives a vector where the first number is *not* the largest, as it ought to be. So, this questi...
As I just ran into the same problem, I would like to share a few lines of code with you. In fact there are several rather similar posts about autocorrelation in stackoverflow by now. If you define the autocorrelation as `a(x, L) = sum(k=0,N-L-1)((xk-xbar)*(x(k+L)-xbar))/sum(k=0,N-1)((xk-xbar)**2)` [this is the definiti...
How can I use numpy.correlate to do autocorrelation?
643,699
52
2009-03-13T17:07:53Z
21,863,139
10
2014-02-18T19:10:37Z
[ "python", "math", "numpy", "numerical-methods" ]
I need to do auto-correlation of a set of numbers, which as I understand it is just the correlation of the set with itself. I've tried it using numpy's correlate function, but I don't believe the result, as it almost always gives a vector where the first number is *not* the largest, as it ought to be. So, this questi...
Using the `numpy.corrcoef` function instead of `numpy.correlate` to calculate the statistical correlation for a lag of t: ``` def autocorr(x, t=1): numpy.corrcoef(numpy.array([x[0:len(x)-t], x[t:len(x)]])) ```
Python - list transformation
643,823
13
2009-03-13T17:41:29Z
643,825
13
2009-03-13T17:42:44Z
[ "python", "list" ]
Does anyone knows what magic I have to use to change x list: > x = [1,2,3,4,5,11] into y list? > y = ['01','02','03','04','05','11'] Thank you all in advance for helping me...
You want to use the built-in [`map`](http://docs.python.org/library/functions.html#map) function: ``` >>> x = [1,2,3,4,5] >>> x [1, 2, 3, 4, 5] >>> y = map(str, x) >>> y ['1', '2', '3', '4', '5'] ``` **EDIT** You changed the requirements on me! To make it display leading zeros, you do this: ``` >>> x = [1,2,3,4,5,11...
Python - list transformation
643,823
13
2009-03-13T17:41:29Z
643,830
29
2009-03-13T17:45:20Z
[ "python", "list" ]
Does anyone knows what magic I have to use to change x list: > x = [1,2,3,4,5,11] into y list? > y = ['01','02','03','04','05','11'] Thank you all in advance for helping me...
You can use a list comprehension (Python 2.6+): ``` y = ["{0:0>2}".format(v) for v in x] ``` Or for Python prior to 2.6: ``` y = ["%02d" % v for v in x] ``` Edit: Missed the fact that you wanted zero-padding...
Using "like" in a cursor/query with a parameter in python (django)
643,930
4
2009-03-13T18:14:21Z
644,043
7
2009-03-13T18:32:31Z
[ "python", "sql", "django", "cursor", "like" ]
I know this may be something stupid but I decided to ask any way. I've been trying to query something like: ``` cursor.execute("select col1, col2 \ from my_tablem \ where afield like '%%s%' and secondfield = %s order by 1 desc " % (var...
First, why aren't you using the Django ORM for this? ``` MyClass.objects.filter( aField__contains=var1, secondField__exact=var2 ) ``` Second, be sure you're getting the SQL you expect. ``` stmt= "select... afield like '%%%s%%' and secondfield = '%s'..." % ( var1, var2 ) print stmt cursor.execute( stmt ) ``` Third, ...
How do I rewrite $x = $hash{blah} || 'default' in Python?
643,950
3
2009-03-13T18:16:50Z
643,960
9
2009-03-13T18:19:21Z
[ "python" ]
How do I pull an item out of a Python dictionary without triggering a KeyError? In Perl, I would do: ``` $x = $hash{blah} || 'default' ``` What's the equivalent Python?
Use the [`get(key, default)`](http://docs.python.org/library/stdtypes.html#dict.get) method: ``` >>> dict().get("blah", "default") 'default' ```
How do I rewrite $x = $hash{blah} || 'default' in Python?
643,950
3
2009-03-13T18:16:50Z
644,007
7
2009-03-13T18:26:11Z
[ "python" ]
How do I pull an item out of a Python dictionary without triggering a KeyError? In Perl, I would do: ``` $x = $hash{blah} || 'default' ``` What's the equivalent Python?
If you're going to be doing this a lot, it's better to use [collections.defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict): ``` import collections # Define a little "factory" function that just builds the default value when called. def get_default_value(): return 'default' # Crea...
How does Python sort a list of tuples?
644,170
45
2009-03-13T19:09:17Z
644,183
8
2009-03-13T19:12:54Z
[ "python" ]
Empirically, it seems that Python's default list sorter, when passed a list of tuples, will sort by the first element in each tuple. Is that correct? If not, what's the right way to sort a list of tuples by their first elements?
Yes, this is the default. In fact, this is the basis of the classic "DSU" (Decorate-Sort-Undecorate) idiom in Python. See [Code Like a Pythonista](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html).
How does Python sort a list of tuples?
644,170
45
2009-03-13T19:09:17Z
644,189
57
2009-03-13T19:13:49Z
[ "python" ]
Empirically, it seems that Python's default list sorter, when passed a list of tuples, will sort by the first element in each tuple. Is that correct? If not, what's the right way to sort a list of tuples by their first elements?
It automatically sorts a list of tuples by the first elements in the tuples, then by the second elements and so on tuple([1,2,3]) will go before tuple([1,2,4]). If you want to override this behaviour pass a callable as the second argument to the sort method. This callable should return 1, -1, 0.
How do I re-map python dict keys
644,178
11
2009-03-13T19:11:21Z
644,314
14
2009-03-13T19:43:15Z
[ "python", "dictionary" ]
I am working on a program that (among other things) reads a CSV file in (it gets stored as an array of dicts in the form `[{col1:data1a,col2:data2a},{col1:data1b,col2:data2b}]` ). For each row, as part of other processing, I need to remap those keys to user entered values, which are provided in another dict so they can...
``` name_map = {'oldcol1': 'newcol1', 'oldcol2': 'newcol2', 'oldcol3': 'newcol3'...} for row in rows: # Each row is a dict of the form: {'oldcol1': '...', 'oldcol2': '...'} row = dict((name_map[name], val) for name, val in row.iteritems()) ... ``` Or in Python2.7+ with [Dict Comprehensions](http://www.pyt...
Converting from mod_python to mod_wsgi
644,767
11
2009-03-13T21:56:15Z
644,774
9
2009-03-13T22:00:40Z
[ "python", "mod-wsgi", "mod-python" ]
My website is written in Python and currently runs under mod\_python with Apache. Lately I've had to put in a few ugly hacks that make me think it might be worth converting the site to mod\_wsgi. But I've gotten used to using some of mod\_python's utility classes, especially `FieldStorage` and `Session` (and sometimes ...
Look at [Werkzeug](http://werkzeug.pocoo.org/). You may have to do some rewriting. You will probably be pleased with the results of imposing the WSGI world-view on your application.
Python: How to run unittest.main() for all source files in a subdirectory?
644,821
41
2009-03-13T22:20:31Z
644,844
18
2009-03-13T22:29:58Z
[ "python", "unit-testing" ]
I am developing a Python module with several source files, each with its own test class derived from [unittest](http://docs.python.org/library/unittest.html) right in the source. Consider the directory structure: ``` dirFoo\ test.py dirBar\ __init__.py Foo.py Bar.py ``` To test either ...
I knew there was an obvious solution: ``` dirFoo\ __init__.py test.py dirBar\ Foo.py Bar.py ``` Contents of dirFoo/test.py ``` from dirBar import * import unittest if __name__ == "__main__": unittest.main() ``` Run the tests: ``` $ python test.py ........... ----------------------...
Python: How to run unittest.main() for all source files in a subdirectory?
644,821
41
2009-03-13T22:20:31Z
644,987
15
2009-03-13T23:35:04Z
[ "python", "unit-testing" ]
I am developing a Python module with several source files, each with its own test class derived from [unittest](http://docs.python.org/library/unittest.html) right in the source. Consider the directory structure: ``` dirFoo\ test.py dirBar\ __init__.py Foo.py Bar.py ``` To test either ...
You should try [nose](http://nose.readthedocs.io/en/latest/). It's a library to help create tests and it integrates with `unittest` or `doctest`. All you need to do is run `nosetests` and it'll find all your unittests for you. ``` % nosetests # finds all tests in all subdirectories % nosetests tests/ # find all tests ...
Python: How to run unittest.main() for all source files in a subdirectory?
644,821
41
2009-03-13T22:20:31Z
9,407,536
43
2012-02-23T05:12:03Z
[ "python", "unit-testing" ]
I am developing a Python module with several source files, each with its own test class derived from [unittest](http://docs.python.org/library/unittest.html) right in the source. Consider the directory structure: ``` dirFoo\ test.py dirBar\ __init__.py Foo.py Bar.py ``` To test either ...
As of Python 2.7, test discovery is automated in the unittest package. From the [docs](http://docs.python.org/library/unittest.html): > Unittest supports simple test discovery. In order to be compatible > with test discovery, all of the test files must be modules or packages > importable from the top-level directory o...
Python: How to run unittest.main() for all source files in a subdirectory?
644,821
41
2009-03-13T22:20:31Z
13,533,236
18
2012-11-23T17:02:19Z
[ "python", "unit-testing" ]
I am developing a Python module with several source files, each with its own test class derived from [unittest](http://docs.python.org/library/unittest.html) right in the source. Consider the directory structure: ``` dirFoo\ test.py dirBar\ __init__.py Foo.py Bar.py ``` To test either ...
Here is my test discovery code that seems to do the job. I wanted to make sure I can extend the tests easily without having to list them in any of the involved files, but also avoid writing all tests in one single Übertest file. So the structure is ``` myTests.py testDir\ __init__.py testA.py testB.py ``...
What is the quickest way to HTTP GET in Python?
645,312
267
2009-03-14T03:44:22Z
645,318
386
2009-03-14T03:48:24Z
[ "python", "http", "networking" ]
What is the quickest way to HTTP GET in Python if I know the Content will be a string? I am searching the docs for a quick one-liner like: ``` contents = url.get("http://example.com/foo/bar") ``` But all I can find using Google are `httplib` and `urllib` - and I am unable to find a shortcut in those libraries. Does ...
Python 2.x: ``` import urllib2 urllib2.urlopen("http://example.com/foo/bar").read() ``` Python 3.x: ``` import urllib.request urllib.request.urlopen("http://example.com/foo/bar").read() ``` Documentation for [urllib.request](https://docs.python.org/3.5/library/urllib.request.html) and [read](https://docs.python.org...
What is the quickest way to HTTP GET in Python?
645,312
267
2009-03-14T03:44:22Z
646,159
13
2009-03-14T16:13:13Z
[ "python", "http", "networking" ]
What is the quickest way to HTTP GET in Python if I know the Content will be a string? I am searching the docs for a quick one-liner like: ``` contents = url.get("http://example.com/foo/bar") ``` But all I can find using Google are `httplib` and `urllib` - and I am unable to find a shortcut in those libraries. Does ...
Have a look at [httplib2](http://code.google.com/p/httplib2/), which - next to a lot of very useful features - provides exactly what you want. ``` import httplib2 resp, content = httplib2.Http().request("http://example.com/foo/bar") ``` Where content would be the response body (as a string), and resp would contain t...
What is the quickest way to HTTP GET in Python?
645,312
267
2009-03-14T03:44:22Z
646,213
27
2009-03-14T16:40:06Z
[ "python", "http", "networking" ]
What is the quickest way to HTTP GET in Python if I know the Content will be a string? I am searching the docs for a quick one-liner like: ``` contents = url.get("http://example.com/foo/bar") ``` But all I can find using Google are `httplib` and `urllib` - and I am unable to find a shortcut in those libraries. Does ...
If you want solution with httplib2 to be oneliner consider instatntinating anonymous Http object ``` import httplib2 resp, content = httplib2.Http().request("http://example.com/foo/bar") ```
What is the quickest way to HTTP GET in Python?
645,312
267
2009-03-14T03:44:22Z
15,869,929
153
2013-04-08T01:30:40Z
[ "python", "http", "networking" ]
What is the quickest way to HTTP GET in Python if I know the Content will be a string? I am searching the docs for a quick one-liner like: ``` contents = url.get("http://example.com/foo/bar") ``` But all I can find using Google are `httplib` and `urllib` - and I am unable to find a shortcut in those libraries. Does ...
You could use a library called [requests](http://docs.python-requests.org/en/latest/). ``` import requests r = requests.get("http://example.com/foo/bar") ``` This is quite easy. Then you can do like this: ``` >>> print r.status_code >>> print r.headers >>> print r.content ```
Discussion of multiple inheritance vs Composition for a project (+other things)
645,493
13
2009-03-14T06:04:55Z
645,819
9
2009-03-14T12:11:31Z
[ "python", "constructor", "oop", "multiple-inheritance" ]
I am writing a python platform for the simulation of distributed sensor swarms. The idea being that the end user can write a custom Node consisting of the SensorNode behaviour (communication, logging, etc) as well as implementing a number of different sensors. The example below briefly demonstrates the concept. ``` #...
The sensor architecture can be solved by using composition if you want to stick to your original map-of-data design. You seem to be new to Python so I'll try to keep idioms to a minimum. ``` class IRSensor: def read(self): return {'ir_amplitude': 12} class UltrasonicSensor: def read(self): return {'ultrasonic...
Integrating MySQL with Python in Windows
645,943
94
2009-03-14T13:53:28Z
647,469
7
2009-03-15T08:11:23Z
[ "python", "mysql", "windows" ]
I am finding it difficult to use MySQL with Python in my windows system. I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate...
I found a location were one person had successfully built mysql for python2.6, sharing the link, <http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe> ...you might see a warning while import MySQLdb which is fine and that won’t hurt anything, C:\Python26\lib\site-packages\MySQLdb\_\_init\_\_.py:34...
Integrating MySQL with Python in Windows
645,943
94
2009-03-14T13:53:28Z
817,760
14
2009-05-03T19:13:31Z
[ "python", "mysql", "windows" ]
I am finding it difficult to use MySQL with Python in my windows system. I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate...
As Python newbie learning the Python ecosystem I've just completed this. 1. Install setuptools [instructions](http://stackoverflow.com/questions/309412/how-to-setup-setuptools-for-python-2-6-on-windows) 2. Install MySQL 5.1. Download the 97.6MB MSI from [here](http://dev.mysql.com/downloads/mysql/5.1.html#win32) You c...
Integrating MySQL with Python in Windows
645,943
94
2009-03-14T13:53:28Z
847,577
124
2009-05-11T10:43:27Z
[ "python", "mysql", "windows" ]
I am finding it difficult to use MySQL with Python in my windows system. I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate...
[Download page for python-mysqldb](http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python). The page includes binaries for 32 and 64 bit versions of for Python 2.5, 2.6 and 2.7. There's also [discussion on getting rid of the deprecation warning](http://sourceforge.net/forum/message.php?msg_id=5808948). **UPDATE**: T...
Integrating MySQL with Python in Windows
645,943
94
2009-03-14T13:53:28Z
3,242,143
30
2010-07-13T22:44:36Z
[ "python", "mysql", "windows" ]
I am finding it difficult to use MySQL with Python in my windows system. I am currently using Python 2.6. I have tried to compile MySQL-python-1.2.3b1 (which is supposed to work for Python 2.6 ?) source code using the provided setup scripts. The setup script runs and it doesn't report any error but it doesn't generate...
This may read like your grandpa givin advice, but all answers here did not mention the best way: go nd install [ActivePython](http://www.activestate.com/activepython/downloads) instead of python.org windows binaries. I was really wondering for a long time why Python development on windows was such a pita - until I inst...
Python PIL: how to write PNG image to string
646,286
64
2009-03-14T17:15:17Z
646,297
129
2009-03-14T17:21:04Z
[ "python", "python-imaging-library" ]
I have generated an image using [PIL](http://www.pythonware.com/products/pil/). How can I save it to a string in memory? The `Image.save()` method requires a file. I'd like to have several such images stored in dictionary.
You can probably use the [StringIO](http://docs.python.org/library/stringio.html) class to get a wrapper around strings that behaves like a file. The StringIO object provides the same interface as a file, but saves the contents just in memory: ``` import StringIO output = StringIO.StringIO() image.save(output) conten...
Python PIL: how to write PNG image to string
646,286
64
2009-03-14T17:15:17Z
646,339
12
2009-03-14T17:39:25Z
[ "python", "python-imaging-library" ]
I have generated an image using [PIL](http://www.pythonware.com/products/pil/). How can I save it to a string in memory? The `Image.save()` method requires a file. I'd like to have several such images stored in dictionary.
save() can take a file-like object as well as a path, so you can use an in-memory buffer like a StringIO: ``` buf= StringIO.StringIO() im.save(buf, format= 'JPEG') jpeg= buf.getvalue() ```
Python PIL: how to write PNG image to string
646,286
64
2009-03-14T17:15:17Z
5,504,072
16
2011-03-31T17:46:26Z
[ "python", "python-imaging-library" ]
I have generated an image using [PIL](http://www.pythonware.com/products/pil/). How can I save it to a string in memory? The `Image.save()` method requires a file. I'd like to have several such images stored in dictionary.
sth's solution didn't work for me because in ... > Imaging/PIL/Image.pyc line 1423 -> > raise KeyError(ext) # unknown > extension It was trying to detect the format from the extension in the filename , which doesn't exist in StringIO case You can bypass the format detection by setting the format yourself in a para...
Python PIL: how to write PNG image to string
646,286
64
2009-03-14T17:15:17Z
29,971,514
8
2015-04-30T15:16:32Z
[ "python", "python-imaging-library" ]
I have generated an image using [PIL](http://www.pythonware.com/products/pil/). How can I save it to a string in memory? The `Image.save()` method requires a file. I'd like to have several such images stored in dictionary.
For Python3 it is required to use BytesIO: <http://fadeit.dk/blog/post/python3-flask-pil-in-memory-image>
Python: How to detect debug interpreter
646,518
11
2009-03-14T19:10:14Z
647,312
12
2009-03-15T04:39:26Z
[ "python", "debugging" ]
How can I detect in my python script if its being run by the debug interpreter (ie python\_d.exe rather than python.exe)? I need to change the paths to some dlls that I pass to an extension. eg Id like to do something like this at the start of my python script: ``` #get paths to graphics dlls if debug_build: d3d9...
[Distutils use `sys.gettotalrefcount` to detect a debug python build](http://bugs.python.org/file2086/build.py.diff): ``` # ... if hasattr(sys, 'gettotalrefcount'): plat_specifier += '-pydebug' ``` * this method doesn't rely on an executable name '`*_d.exe`'. It works for any name. * this method is cross-platform....
How to get last items of a list in Python?
646,644
85
2009-03-14T20:19:44Z
646,646
43
2009-03-14T20:21:07Z
[ "python", "list", "slice" ]
I need the last 9 numbers of a list and I'm sure there is a way to do it with slicing, but I can't seem to get it. I can get the first 9 like this: ``` num_list[0:9] ``` Any help would be great.
a negative index will count from the end of the list, so: ``` num_list[-9:] ```
How to get last items of a list in Python?
646,644
85
2009-03-14T20:19:44Z
646,654
180
2009-03-14T20:22:54Z
[ "python", "list", "slice" ]
I need the last 9 numbers of a list and I'm sure there is a way to do it with slicing, but I can't seem to get it. I can get the first 9 like this: ``` num_list[0:9] ``` Any help would be great.
You can use negative integers with the slicing operator for that. Here's an example using the python CLI interpreter: ``` >>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] >>> a[-9:] [4, 5, 6, 7, 8, 9, 10, 11, 12] ``` the important line is `a[-9:]`
How to get last items of a list in Python?
646,644
85
2009-03-14T20:19:44Z
647,299
24
2009-03-15T04:27:16Z
[ "python", "list", "slice" ]
I need the last 9 numbers of a list and I'm sure there is a way to do it with slicing, but I can't seem to get it. I can get the first 9 like this: ``` num_list[0:9] ``` Any help would be great.
The last 9 elements can be read from left to right using numlist[-9:], or from right to left using numlist[:-10:-1], as you want. ``` >>> a=range(17) >>> print a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] >>> print a[-9:] [8, 9, 10, 11, 12, 13, 14, 15, 16] >>> print a[:-10:-1] [16, 15, 14, 13, 12, 11, ...
How to get last items of a list in Python?
646,644
85
2009-03-14T20:19:44Z
24,620,740
12
2014-07-07T22:10:41Z
[ "python", "list", "slice" ]
I need the last 9 numbers of a list and I'm sure there is a way to do it with slicing, but I can't seem to get it. I can get the first 9 like this: ``` num_list[0:9] ``` Any help would be great.
# Slicing Python slicing is an incredibly fast operation, and it's a handy way to quickly access parts of your data. Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this: ``` num_list[-9:] ``` When I see this, I read the part in the br...
Need a simple "Hello World" example using the Webkit library in Python
647,041
13
2009-03-15T01:00:46Z
647,121
30
2009-03-15T02:11:25Z
[ "python", "webkit" ]
Does anyone know of a simple "Hello World" example for using the Webkit library in Python? I have a GTK window, and inside I want to put Webkit. With Python/mozembed (Mozilla/Gecko), this is simple: ``` mozembed = gtkmozembed.MozEmbed() mozembed.load_url('http://google.com/') ``` ..and I have already created my brow...
Did you check the [Python bindings for the WebKit GTK+ port](http://code.google.com/p/pywebkitgtk/). In one of the directory there are demos on how to use it, including a browser: python demos/tabbed\_browser.py You could check also the slides of a FOSDEM by Alp Toker on [WebKit GTK+](http://www.atoker.com/webkit/webk...
Python xml ElementTree from a string source?
647,071
41
2009-03-15T01:24:19Z
647,082
31
2009-03-15T01:36:44Z
[ "python", "xml" ]
The ElementTree.parse reads from a file, how can I use this if I already have the XML data in a string? Maybe I am missing something here, but there must be a way to use the ElementTree without writing out the string to a file and reading it again. [xml.etree.elementtree](http://docs.python.org/library/xml.etree.elem...
If you're using `xml.etree.ElementTree.parse` to parse from a file, then you can use `xml.etree.ElementTree.fromstring` to parse from text. See [xml.etree.ElementTree](http://docs.python.org/library/xml.etree.elementtree.html)
Python xml ElementTree from a string source?
647,071
41
2009-03-15T01:24:19Z
647,084
10
2009-03-15T01:37:22Z
[ "python", "xml" ]
The ElementTree.parse reads from a file, how can I use this if I already have the XML data in a string? Maybe I am missing something here, but there must be a way to use the ElementTree without writing out the string to a file and reading it again. [xml.etree.elementtree](http://docs.python.org/library/xml.etree.elem...
You need the xml.etree.ElementTree.fromstring(text) ``` from xml.etree.ElementTree import XML, fromstring, tostring myxml = fromstring(text) ```
Python xml ElementTree from a string source?
647,071
41
2009-03-15T01:24:19Z
18,281,386
61
2013-08-16T20:09:47Z
[ "python", "xml" ]
The ElementTree.parse reads from a file, how can I use this if I already have the XML data in a string? Maybe I am missing something here, but there must be a way to use the ElementTree without writing out the string to a file and reading it again. [xml.etree.elementtree](http://docs.python.org/library/xml.etree.elem...
You can parse the text as a string, which creates an Element, and create an ElementTree using that Element. ``` import xml.etree.ElementTree as ET tree = ET.ElementTree(ET.fromstring(xmlstring)) ``` I just came across this issue and the documentation, while complete, is not very straightforward on the difference in u...
Why can I not paste the output of Pythons REPL without manual-editing?
647,142
4
2009-03-15T02:23:48Z
647,244
9
2009-03-15T03:36:36Z
[ "python", "user-interface", "read-eval-print-loop" ]
A huge amount of example Python code shows the output of the Python REPL, for example: ``` >>> class eg(object): ... def __init__(self, name): ... self.name = name ... def hi(self): ... print "Hi %s" % (self.name) ... >>> greeter = eg("Bob") >>> greeter.hi() Hi Bob >>> ``` Now, the ob...
### How to run/adopt "the output of Pythons REPL" * Use [IPython](http://ipython.scipy.org/moin/) shell ``` In [99]: %cpaste Pasting code; enter '--' alone on the line to stop. :>>> class eg(object): :... def __init__(self, name): :... self.name = name :... def hi(self): :... ...
How can I know python's path under windows?
647,515
12
2009-03-15T09:09:18Z
647,798
28
2009-03-15T13:17:29Z
[ "python", "path" ]
I want to know where is the python's installation path. For example: C:\Python25 But however, I have no idea how to do. How can I get the installation path of python? Thanks.
``` >>> import os >>> import sys >>> os.path.dirname(sys.executable) 'C:\\Python25' ```
How can I know python's path under windows?
647,515
12
2009-03-15T09:09:18Z
648,552
23
2009-03-15T21:08:54Z
[ "python", "path" ]
I want to know where is the python's installation path. For example: C:\Python25 But however, I have no idea how to do. How can I get the installation path of python? Thanks.
If you need to know the installed path under Windows **without** starting the python interpreter, have a look in the Windows registry. Each installed Python version will have a registry key in either: * `HKLM\SOFTWARE\Python\PythonCore\versionnumber\InstallPath` * `HKCU\SOFTWARE\Python\PythonCore\versionnumber\Instal...
python, regex split and special character
647,655
11
2009-03-15T11:24:44Z
647,667
16
2009-03-15T11:32:00Z
[ "python", "regex", "unicode", "split" ]
How can I split correctly a string containing a sentence with special chars using whitespaces as separator ? Using regex split method I cannot obtain the desired result. Example code: ``` # -*- coding: utf-8 -*- import re s="La felicità è tutto" # "The happiness is everything" in italian l=re.compile("(\W)").spli...
Your regex should be `(\s)` instead of `(\W)` like this: ``` l = re.compile("(\s)").split(s) ``` The code above will give you the exact output you requested. However the following line makes more sense: ``` l = re.compile("\s").split(s) ``` which splits on whitespace characters and doesn't give you all the spaces a...
Why can't Python's raw string literals end with a single backslash?
647,769
85
2009-03-15T12:54:53Z
647,787
61
2009-03-15T13:05:31Z
[ "python", "string", "literals" ]
Technically, any odd number of backslashes, as described in [the docs](http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals). ``` >>> r'\' File "<stdin>", line 1 r'\' ^ SyntaxError: EOL while scanning string literal >>> r'\\' '\\\\' >>> r'\\\' File "<stdin>", line 1 r'\\\' ...
The reason is explained in the part of that section which I highlighted in bold: > **String quotes can be escaped with a > backslash,** but the backslash remains > in the string; for example, `r"\""` is a > valid string literal consisting of two > characters: a backslash and a double > quote; `r"\"` is not a valid str...
Why can't Python's raw string literals end with a single backslash?
647,769
85
2009-03-15T12:54:53Z
647,797
13
2009-03-15T13:17:10Z
[ "python", "string", "literals" ]
Technically, any odd number of backslashes, as described in [the docs](http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals). ``` >>> r'\' File "<stdin>", line 1 r'\' ^ SyntaxError: EOL while scanning string literal >>> r'\\' '\\\\' >>> r'\\\' File "<stdin>", line 1 r'\\\' ...
That's the way it is! I see it as one of those small defects in python! I don't think there's a good reason for it, but it's definitely not parsing; it's really easy to parse raw strings with \ as a last character. The catch is, if you allow \ to be the last character in a raw string then you won't be able to put " i...
Why can't Python's raw string literals end with a single backslash?
647,769
85
2009-03-15T12:54:53Z
648,135
7
2009-03-15T16:59:09Z
[ "python", "string", "literals" ]
Technically, any odd number of backslashes, as described in [the docs](http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals). ``` >>> r'\' File "<stdin>", line 1 r'\' ^ SyntaxError: EOL while scanning string literal >>> r'\\' '\\\\' >>> r'\\\' File "<stdin>", line 1 r'\\\' ...
Since \" is allowed inside the raw string. Then it can't be used to identify the end of the string literal. Why not stop parsing the string literal when you encounter the first "? If that was the case, then \" wouldn't be allowed inside the string literal. But it is.
Why can't Python's raw string literals end with a single backslash?
647,769
85
2009-03-15T12:54:53Z
5,830,053
8
2011-04-29T08:57:03Z
[ "python", "string", "literals" ]
Technically, any odd number of backslashes, as described in [the docs](http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals). ``` >>> r'\' File "<stdin>", line 1 r'\' ^ SyntaxError: EOL while scanning string literal >>> r'\\' '\\\\' >>> r'\\\' File "<stdin>", line 1 r'\\\' ...
In order for you to end a raw string with a slash I suggest you can use this trick: ``` >>> print r"c:\test"'\\' test\ ```
Why can't Python's raw string literals end with a single backslash?
647,769
85
2009-03-15T12:54:53Z
7,986,539
11
2011-11-02T19:54:40Z
[ "python", "string", "literals" ]
Technically, any odd number of backslashes, as described in [the docs](http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals). ``` >>> r'\' File "<stdin>", line 1 r'\' ^ SyntaxError: EOL while scanning string literal >>> r'\\' '\\\\' >>> r'\\\' File "<stdin>", line 1 r'\\\' ...
Another trick is to use chr(92) as it evaluates to "\". I recently had to clean a string of backslashes and the following did the trick: ``` CleanString = DirtyString.replace(chr(92),'') ``` I realize that this does not take care of the "why" but the thread attracts many people looking for a solution to an immediate...
Why can't Python's raw string literals end with a single backslash?
647,769
85
2009-03-15T12:54:53Z
19,654,184
14
2013-10-29T09:24:45Z
[ "python", "string", "literals" ]
Technically, any odd number of backslashes, as described in [the docs](http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals). ``` >>> r'\' File "<stdin>", line 1 r'\' ^ SyntaxError: EOL while scanning string literal >>> r'\\' '\\\\' >>> r'\\\' File "<stdin>", line 1 r'\\\' ...
The whole misconception about python's raw strings is that most of people think that backslash (within a raw string) is just a regular character as all others. It is NOT. The key to understand is this python's tutorial sequence: > When an '**r**' or '**R**' prefix is present, a character following a > backslash is inc...
Trapping MySQL Warnings In Python
647,805
13
2009-03-15T13:25:52Z
647,811
14
2009-03-15T13:32:39Z
[ "python", "mysql" ]
I would like to catch and log MySQL warnings in Python. For example, MySQL issues a warning to standard error if you submit `'DROP DATABASE IF EXISTS database_of_armaments'` when no such database exists. I would like to catch this and log it, but even in the try/else syntax the warning message still appears. The try/e...
Follow these steps. 1. Run it with `except Exception, e: print repr(e)`. 2. See what exception you get. 3. Change the `Exception` to the exception you actually got. Also, remember that the exception, e, is an object. You can print `dir(e)`, `e.__class__.__name__`, etc.to see what attributes it has. Also, you can do ...
socket trouble in python
647,813
4
2009-03-15T13:34:19Z
647,817
9
2009-03-15T13:36:36Z
[ "python", "sockets" ]
I have a server that's written in C, and I want to write a client in python. The python client will send a string "send some\_file" when it wants to send a file, followed by the file's contents, and the string "end some\_file". Here is my client code : ``` file = sys.argv[1] host = sys.argv[2] port = int(sys.argv[3]) ...
With socket programming, even if you do 2 independent sends, it doesn't mean that the other side will receive them as 2 independent recvs. One simple solution that works for both strings and binary data is to: First send the number of bytes in the message, then send the message. Here is what you should do for each me...
File handling in Django when posting image from service call
647,888
7
2009-03-15T14:23:25Z
648,050
9
2009-03-15T16:08:11Z
[ "python", "django", "flex", "pyamf" ]
I am using [PyAMF](http://pyamf.org/) to transfer a dynamically generated large image from Flex to Django. On the Django side i receive the encodedb64 data as a parameter: My Item model as an imagefield. What i have trouble to do is saving the data as the File Django Field. ``` def save_item(request, uname, data): ...
In `django.core.files.base` you can find the class `ContentFile`. That class extends the basic Django `File` class, so you do not need StringIO (which ContentFile though uses internally). The modified save method looks like this: ``` from django.core.files.base import ContentFile def save_item(request, uname, data): ...
Python - test that succeeds when exception is not raised
647,900
11
2009-03-15T14:33:34Z
647,919
18
2009-03-15T14:48:33Z
[ "python", "unit-testing", "exception", "exception-handling" ]
I know about `unittest` Python module. I know about `assertRaises()` method of `TestCase` class. I would like to write a test that succeeds when an exception is **not** raised. Any hints please?
``` def runTest(self): try: doStuff() except: self.fail("Encountered an unexpected exception.") ``` UPDATE: As liw.fi mentions, the default result is a success, so the example above is something of an antipattern. You should probably only use it if you want to do something special before failin...
Python - test that succeeds when exception is not raised
647,900
11
2009-03-15T14:33:34Z
647,949
12
2009-03-15T15:03:50Z
[ "python", "unit-testing", "exception", "exception-handling" ]
I know about `unittest` Python module. I know about `assertRaises()` method of `TestCase` class. I would like to write a test that succeeds when an exception is **not** raised. Any hints please?
The test runner will catch all exceptions you didn't assert would be raised. Thus: ``` doStuff() self.assert_(True) ``` This should work fine. You can leave out the self.assert\_ call, since it doesn't really do anything. I like to put it there to document that I didn't forget an assertion.
How to make a list comprehension with the group() method in python?
648,276
3
2009-03-15T18:21:24Z
648,287
7
2009-03-15T18:27:53Z
[ "python", "list", "group", "list-comprehension" ]
I'm trying to write a little script to clean my directories. In fact I have: ``` pattern = re.compile(format[i]) ... current_f.append(pattern.search(str(ls))) ``` and I want to use a list comprehension but when I try: ``` In [25]: [i for i in current_f.group(0)] ``` I get: ``` AttributeError: 'list' object has no ...
Are you trying to do this?: ``` [f.group(0) for f in current_f] ```
A trivial Python SWIG error question
648,482
5
2009-03-15T20:27:49Z
2,909,020
7
2010-05-25T22:36:08Z
[ "python", "swig" ]
I am trying to get Python running with swig to do C/C++. I am running the tutorial [here](http://www.swig.org/tutorial.html), 'building a python module'. When I do the call ``` gcc -c example.c example_wrap.c -I /my_correct_path/python2.5 ``` I get an error: ``` my_correct_path/python2.5/pyport.h:761:2: error: #erro...
I found this thread looking for an answer for the same "LONGBIT" error while installing python readline for 32bit python on 64bit centos. The link doesn't have the direct answer, so I had to google further for the answer (which might be straight-forward for seasoned linux users/devs). For future reference, the solution...
Use case for nested/multiple list comprehensions or generator expressions. When is it more elegant?
648,675
9
2009-03-15T22:22:52Z
648,724
11
2009-03-15T22:41:50Z
[ "python", "list-comprehension", "generator-expression" ]
I see this kind of thing sometimes: ``` (k for k in (j for j in (i for i in xrange(10)))) ``` Now this really bends my brain, and I would rather it wasn't presented in this way. Are there any use-cases, or examples of having used these nested expressions where it was more elegant and more readable than if it had bee...
If you're worried about too much complexity on one line, you could split it: ``` (k for k in (j for j in (i for i in xrange(10)))) ``` I've always found line continuations to look a little weird in Python, but this does make it easier to see what each one is looping over. Since an extra assignment/looku...
Use case for nested/multiple list comprehensions or generator expressions. When is it more elegant?
648,675
9
2009-03-15T22:22:52Z
648,886
16
2009-03-16T00:39:51Z
[ "python", "list-comprehension", "generator-expression" ]
I see this kind of thing sometimes: ``` (k for k in (j for j in (i for i in xrange(10)))) ``` Now this really bends my brain, and I would rather it wasn't presented in this way. Are there any use-cases, or examples of having used these nested expressions where it was more elegant and more readable than if it had bee...
Check [PEP 202](http://www.python.org/dev/peps/pep-0202/) which was where list comprehensions syntax was introduced to the language. For understanding your example, there is a simple rule from Guido himself: * The form [... for x... for y...] nests, with the last index varying fastest, just like nested for loops. ...
Print out list of function parameters in Python
648,679
4
2009-03-15T22:24:37Z
648,689
17
2009-03-15T22:27:58Z
[ "python" ]
Is there a way to print out a function's parameter list? For example: ``` def func(a, b, c): pass print_func_parametes(func) ``` Which will produce something like: ``` ["a", "b", "c"] ```
Use the inspect module. ``` >>> import inspect >>> inspect.getargspec(func) (['a', 'b', 'c'], None, None, None) ``` The first part of returned tuple is what you're looking for.
Iterability in Python
649,549
4
2009-03-16T07:20:51Z
649,566
9
2009-03-16T07:38:39Z
[ "iterator", "python" ]
I am trying to understand Iterability in Python. As I understand, `__iter__()` should return an object that has `next()` method defined which must return a value or raise `StopIteration` exception. Thus I wrote this class which satisfies both these conditions. But it doesn't seem to work. What is wrong? ``` class It...
Your Iterator class is correct. You just have a typo in this statement: ``` if __name__ ==' __main__': ``` There's a leading whitespace in the ' \_\_main\_\_' string. That's why your code is not executed at all.
Do Python lists have an equivalent to dict.get?
650,340
7
2009-03-16T13:04:46Z
650,350
12
2009-03-16T13:07:46Z
[ "python", "list" ]
I have a list of integers. I want to know whether the number 13 appears in it and, if so, where. Do I have to search the list twice, as in the code below? ``` if 13 in intList: i = intList.index(13) ``` In the case of dictionaries, there's a `get` function which will ascertain membership and perform look-up with t...
You answered it yourself, with the `index()` method. That will throw an exception if the index is not found, so just catch that: ``` def getIndexOrMinusOne(a, x): try: return a.index(x) except ValueError: return -1 ```
Do Python lists have an equivalent to dict.get?
650,340
7
2009-03-16T13:04:46Z
650,359
7
2009-03-16T13:10:07Z
[ "python", "list" ]
I have a list of integers. I want to know whether the number 13 appears in it and, if so, where. Do I have to search the list twice, as in the code below? ``` if 13 in intList: i = intList.index(13) ``` In the case of dictionaries, there's a `get` function which will ascertain membership and perform look-up with t...
It looks like you'll just have to catch the exception... ``` try: i = intList.index(13) except ValueError: i = some_default_value ```
Rotation based on end points
650,646
2
2009-03-16T14:25:00Z
651,089
8
2009-03-16T16:12:37Z
[ "python", "geometry", "pygame" ]
I'm using pygame to draw a line between two arbitrary points. I also want to append arrows at the end of the lines that face outward in the directions the line is traveling. It's simple enough to stick an arrow image at the end, but I have no clue how the calculate the degrees of rotation to keep the arrows pointing i...
Here is the complete code to do it. Note that when using pygame, the y co-ordinate is measured from the top, and so we take the negative when using math functions. ``` import pygame import math import random pygame.init() screen=pygame.display.set_mode((300,300)) screen.fill((255,255,255)) pos1=random.randrange(300)...
Concurrency: Are Python extensions written in C/C++ affected by the Global Interpreter Lock?
651,048
16
2009-03-16T16:00:10Z
651,078
7
2009-03-16T16:08:21Z
[ "c++", "python", "c", "multithreading" ]
One of Python's strongest points is the ease of writing C and C++ extensions to speed up processor intensive parts of the code. Can these extensions avoid the Global Interpreter Lock or are they also restricted by the GIL? If not, then this "ease of extension" is even more of a killer feature than I previously realized...
C/C++ extensions to Python are not bound by the GIL. However, you really need to know what you're doing. [From <http://docs.python.org/c-api/init.html>](http://docs.python.org/c-api/init.html): > The global interpreter lock is used to protect the pointer to the current thread state. When releasing the lock and saving ...
Concurrency: Are Python extensions written in C/C++ affected by the Global Interpreter Lock?
651,048
16
2009-03-16T16:00:10Z
651,238
15
2009-03-16T16:51:08Z
[ "c++", "python", "c", "multithreading" ]
One of Python's strongest points is the ease of writing C and C++ extensions to speed up processor intensive parts of the code. Can these extensions avoid the Global Interpreter Lock or are they also restricted by the GIL? If not, then this "ease of extension" is even more of a killer feature than I previously realized...
Yes, calls to C extensions (C routines called from Python) are still subject to the GIL. However, you can *manually* release the GIL inside your C extension, so long as you are careful to re-assert it before returning control to the Python VM. For information, take a look at the `Py_BEGIN_ALLOW_THREADS` and `Py_END_A...
Concurrency: Are Python extensions written in C/C++ affected by the Global Interpreter Lock?
651,048
16
2009-03-16T16:00:10Z
652,452
7
2009-03-16T22:56:36Z
[ "c++", "python", "c", "multithreading" ]
One of Python's strongest points is the ease of writing C and C++ extensions to speed up processor intensive parts of the code. Can these extensions avoid the Global Interpreter Lock or are they also restricted by the GIL? If not, then this "ease of extension" is even more of a killer feature than I previously realized...
Here's a long article I wrote for python magazine that touches on the c-extension/GIL/threading thing. It's a bit long at 4000 words, but it should help. <http://jessenoller.com/2009/02/01/python-threads-and-the-global-interpreter-lock/>
A simple Python IRC client library that supports SSL?
651,053
5
2009-03-16T16:01:01Z
651,086
14
2009-03-16T16:12:07Z
[ "python", "irc" ]
A simple Python IRC client library that supports SSL?
[Twisted](http://twistedmatrix.com/trac/wiki/TwistedWords) has an IRC client (in twisted.words), and it supports SSL. There is an [example in the documentation](http://twistedmatrix.com/projects/words/documentation/examples/ircLogBot.py), just remember to do `reactor.connectSSL` instead of `reactor.connectTCP`. If yo...
Simultaneously inserting and extending a list?
652,184
5
2009-03-16T21:17:23Z
652,200
14
2009-03-16T21:23:15Z
[ "python" ]
Is there a better way of simultaneously inserting and extending a list? Here is an ugly example of how I'm currently doing it. (lets say I want to insert '2.4' and '2.6' after the '2' element): ``` >>> a = ['1', '2', '3', '4'] >>> b = a[:a.index('2')+1] + ['2.4', '2.6'] + a[a.index('2'):] >>> b <<< ['1', '2', '2.4', '...
``` >>> a = ['1', '2', '3', '4'] >>> a ['1', '2', '3', '4'] >>> i = a.index('2') + 1 # after the item '2' >>> a[i:i] = ['2.4', '2.6'] >>> a ['1', '2', '2.4', '2.6', '3', '4'] >>> ```
Is it possible to create anonymous objects in Python?
652,276
27
2009-03-16T21:50:45Z
652,299
15
2009-03-16T21:59:28Z
[ "python", "anonymous-types" ]
I'm debugging some Python that takes, as input, a list of objects, each with some attributes. I'd like to hard-code some test values -- let's say, a list of four objects whose "foo" attribute is set to some number. Is there a more concise way than this? ``` x1.foo = 1 x2.foo = 2 x3.foo = 3 x4.foo = 4 myfunc([x1, x2,...
Have a look at this: ``` class MiniMock(object): def __new__(cls, **attrs): result = object.__new__(cls) result.__dict__ = attrs return result def print_foo(x): print x.foo print_foo(MiniMock(foo=3)) ```
Is it possible to create anonymous objects in Python?
652,276
27
2009-03-16T21:50:45Z
652,417
34
2009-03-16T22:40:38Z
[ "python", "anonymous-types" ]
I'm debugging some Python that takes, as input, a list of objects, each with some attributes. I'd like to hard-code some test values -- let's say, a list of four objects whose "foo" attribute is set to some number. Is there a more concise way than this? ``` x1.foo = 1 x2.foo = 2 x3.foo = 3 x4.foo = 4 myfunc([x1, x2,...
I like Tetha's solution, but it's unnecessarily complex. Here's something simpler: ``` >>> class MicroMock(object): ... def __init__(self, **kwargs): ... self.__dict__.update(kwargs) ... >>> def print_foo(x): ... print x.foo ... >>> print_foo(MicroMock(foo=3)) 3 ```
Is it possible to create anonymous objects in Python?
652,276
27
2009-03-16T21:50:45Z
29,480,317
14
2015-04-06T21:54:38Z
[ "python", "anonymous-types" ]
I'm debugging some Python that takes, as input, a list of objects, each with some attributes. I'd like to hard-code some test values -- let's say, a list of four objects whose "foo" attribute is set to some number. Is there a more concise way than this? ``` x1.foo = 1 x2.foo = 2 x3.foo = 3 x4.foo = 4 myfunc([x1, x2,...
I found this: <http://www.hydrogen18.com/blog/python-anonymous-objects.html>, and in my limited testing it seems like it works: ``` >>> obj = type('',(object,),{"foo": 1})() >>> obj.foo 1 ```
sorting a list of dictionary values by date in python
652,291
15
2009-03-16T21:56:51Z
652,347
35
2009-03-16T22:14:17Z
[ "python", "django" ]
I have a list and I am appending a dictionary to it as I loop through my data...and I would like to sort by one of the dictionary keys. ex: ``` data = "data from database" list = [] for x in data: dict = {'title':title, 'date': x.created_on} list.append(dict) ``` I want to sort the list in reverse order by...
You can do it this way: ``` list.sort(key=lambda item:item['date'], reverse=True) ```
sorting a list of dictionary values by date in python
652,291
15
2009-03-16T21:56:51Z
652,463
13
2009-03-16T23:01:22Z
[ "python", "django" ]
I have a list and I am appending a dictionary to it as I loop through my data...and I would like to sort by one of the dictionary keys. ex: ``` data = "data from database" list = [] for x in data: dict = {'title':title, 'date': x.created_on} list.append(dict) ``` I want to sort the list in reverse order by...
``` from operator import itemgetter your_list.sort(key=itemgetter('date'), reverse=True) ``` ### Related notes * don't use `list`, `dict` as variable names, they are builtin names in Python. It makes your code hard to read. * you might need to replace dictionary by `tuple` or [`collections.namedtuple`](http://docs.p...
Separating Models and Request Handlers In Google App Engine
652,449
2
2009-03-16T22:55:07Z
652,458
7
2009-03-16T22:59:44Z
[ "python", "google-app-engine", "model" ]
I'd like to move my models to a separate directory, similar to the way it's done with Rails to cut down on code clutter. Is there any way to do this easily? Thanks, Collin
I assume you're using the basic webkit and not Django or something fancy. In that case just create a subdirectory called models. Put any python files you use for your models in here. Create also one blank file in this folder called \_\_init\_\_.py. Then in your main.py or "controller" or what have you, put: ``` impor...
How to create a Python decorator that can be used either with or without parameters?
653,368
41
2009-03-17T08:10:19Z
653,478
27
2009-03-17T09:13:19Z
[ "python", "decorator" ]
I'd like to create a Python decorator that can be used either with parameters: ``` @redirect_output("somewhere.log") def foo(): .... ``` or without them (for instance to redirect the output to stderr by default): ``` @redirect_output def foo(): .... ``` Is that at all possible? Note that I'm not looking fo...
Using keyword arguments with default values (as suggested by kquinn) is a good idea, but will require you to include the parenthesis: ``` @redirect_output() def foo(): ... ``` If you would like a version that works without the parenthesis on the decorator you will have to account both scenarios in your decorator ...
How to create a Python decorator that can be used either with or without parameters?
653,368
41
2009-03-17T08:10:19Z
653,511
11
2009-03-17T09:25:42Z
[ "python", "decorator" ]
I'd like to create a Python decorator that can be used either with parameters: ``` @redirect_output("somewhere.log") def foo(): .... ``` or without them (for instance to redirect the output to stderr by default): ``` @redirect_output def foo(): .... ``` Is that at all possible? Note that I'm not looking fo...
You need to detect both cases, for example using the type of the first argument, and accordingly return either the wrapper (when used without parameter) or a decorator (when used with arguments). ``` from functools import wraps import inspect def redirect_output(fn_or_output): def decorator(fn): @wraps(fn...
How to create a Python decorator that can be used either with or without parameters?
653,368
41
2009-03-17T08:10:19Z
653,553
8
2009-03-17T09:41:39Z
[ "python", "decorator" ]
I'd like to create a Python decorator that can be used either with parameters: ``` @redirect_output("somewhere.log") def foo(): .... ``` or without them (for instance to redirect the output to stderr by default): ``` @redirect_output def foo(): .... ``` Is that at all possible? Note that I'm not looking fo...
A python decorator is called in a fundamentally different way depending on whether you give it arguments or not. The decoration is actually just a (syntactically restricted) expression. In your first example: ``` @redirect_output("somewhere.log") def foo(): .... ``` the function `redirect_output` is called with ...
How to create a Python decorator that can be used either with or without parameters?
653,368
41
2009-03-17T08:10:19Z
14,412,901
17
2013-01-19T09:24:01Z
[ "python", "decorator" ]
I'd like to create a Python decorator that can be used either with parameters: ``` @redirect_output("somewhere.log") def foo(): .... ``` or without them (for instance to redirect the output to stderr by default): ``` @redirect_output def foo(): .... ``` Is that at all possible? Note that I'm not looking fo...
I know this question is old, but some of the comments are new, and while all of the viable solutions are essentially the same, most of them aren't very clean or easy to read. Like thobe's answer says, the only way to handle both cases is to check for both scenarios. The easiest way is simply to check to see if there i...
How can I profile a multithread program in Python?
653,419
38
2009-03-17T08:45:24Z
653,497
14
2009-03-17T09:21:43Z
[ "python", "multithreading", "profiling" ]
I'm developing an inherently multithreaded module in Python, and I'd like to find out where it's spending its time. cProfile only seems to profile the main thread. Is there any way of profiling all threads involved in the calculation?
Instead of running one `cProfile`, you could run separate `cProfile` instance in each thread, then combine the stats. `Stats.add()` does this automatically.
How can I profile a multithread program in Python?
653,419
38
2009-03-17T08:45:24Z
1,658,540
23
2009-11-01T22:09:51Z
[ "python", "multithreading", "profiling" ]
I'm developing an inherently multithreaded module in Python, and I'd like to find out where it's spending its time. cProfile only seems to profile the main thread. Is there any way of profiling all threads involved in the calculation?
Please see [yappi](https://pypi.python.org/pypi/yappi/) (Yet Another Python Profiler).
How can I cluster a graph in Python?
653,496
13
2009-03-17T09:21:07Z
653,539
7
2009-03-17T09:37:00Z
[ "python", "sorting", "graph", "matrix", "cluster-analysis" ]
Let G be a graph. So G is a set of nodes and set of links. I need to find a fast way to partition the graph. The graph I am now working has only 120\*160 nodes, but I might soon be working on an equivalent problem, in another context (not medicine, but website development), with millions of nodes. So, what I did was t...
In SciPy you can use [sparse matrices](http://docs.scipy.org/doc/scipy/reference/sparse.html). Also note, that there are more efficient ways of multiplying matrix by itself. Anyway, what you're trying to do can by done by SVD decomposition. [Introduction with useful links](http://expertvoices.nsdl.org/cornell-cs322/20...
How can I cluster a graph in Python?
653,496
13
2009-03-17T09:21:07Z
653,724
12
2009-03-17T10:50:17Z
[ "python", "sorting", "graph", "matrix", "cluster-analysis" ]
Let G be a graph. So G is a set of nodes and set of links. I need to find a fast way to partition the graph. The graph I am now working has only 120\*160 nodes, but I might soon be working on an equivalent problem, in another context (not medicine, but website development), with millions of nodes. So, what I did was t...
Why not use a real graph library, like [Python-Graph](http://code.google.com/p/python-graph/)? It has a [function to determine connected components](http://www.linux.ime.usp.br/~matiello/python-graph/docs/graph.algorithms.accessibility-module.html#connected_components) (though no example is provided). I'd imagine a ded...
Django Forms, set an initial value to request.user
653,735
13
2009-03-17T10:53:00Z
1,188,305
29
2009-07-27T13:58:31Z
[ "python", "django-forms" ]
Is there some way to make the following possible, or should it be done elsewhere? ``` class JobRecordForm(forms.ModelForm): supervisor = forms.ModelChoiceField( queryset = User.objects.filter(groups__name='Supervisors'), widget = forms.RadioSelect, initial = request.user # is t...
If you do this in your view.py instead: ``` form = JobRecordForm( initial={'supervisor':request.user} ) ``` Then you won't trigger the validation. See <http://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values>
Equivalent for LinkedHashMap in Python
653,887
11
2009-03-17T11:46:11Z
653,902
10
2009-03-17T11:50:44Z
[ "python" ]
[LinkedHashMap](http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashMap.html) is the Java implementation of a Hashtable like data structure (dict in Python) with predictable iteration order. That means that during a traversal over all keys, they are ordered by insertion. This is done by an additional linked lis...
Although you can do the same thing by maintaining a list to keep track of insertion order, [Python 2.7](https://docs.python.org/2/library/collections.html) and [Python >=3.1](https://docs.python.org/3/library/collections.html) have an OrderedDict class in the collections module. Before 2.7, you can subclass `dict` [fo...
Python file modes detail
654,499
12
2009-03-17T14:32:48Z
654,518
16
2009-03-17T14:38:28Z
[ "python", "file-io" ]
In Python, the following statements do not work: ``` f = open("ftmp", "rw") print >> f, "python" ``` I get the error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 9] Bad file descriptor ``` But with the following code it works: ``` g = open("ftmp", "r+") print >> g, ...
Better yet, let the documentation do it for you: <http://docs.python.org/library/functions.html#open>. Your issue in the question is that there is no "rw" mode... you probably want 'r+' as you wrote (or 'a+' if the file does not yet exist).
Python file modes detail
654,499
12
2009-03-17T14:32:48Z
656,289
10
2009-03-17T22:30:32Z
[ "python", "file-io" ]
In Python, the following statements do not work: ``` f = open("ftmp", "rw") print >> f, "python" ``` I get the error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 9] Bad file descriptor ``` But with the following code it works: ``` g = open("ftmp", "r+") print >> g, ...
As an addition to [@Jarret Hardie's answer](http://stackoverflow.com/questions/654499/python-file-modes-detail/654518#654518) here's how Python check file mode in the function [fileio\_init()](http://hg.python.org/cpython/file/3.2/Modules/_io/fileio.c#l286): ``` s = mode; while (*s) { switch (*s++) { case 'r':...
How do I create a unique value for each key using dict.fromkeys?
654,646
9
2009-03-17T15:06:46Z
654,686
12
2009-03-17T15:15:24Z
[ "python", "dictionary", "fromkeys" ]
First, I'm new to Python, so I apologize if I've overlooked something, but I would like to use `dict.fromkeys` (or something similar) to create a dictionary of lists, the keys of which are provided in another list. I'm performing some timing tests and I'd like for the key to be the input variable and the list to contai...
Check out [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict) (requires Python 2.5 or greater). ``` from collections import defaultdict def benchmark(input): ... return time_taken runs = 10 inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55) results = defaultdict(list) # Creates a dic...
How do I create a unique value for each key using dict.fromkeys?
654,646
9
2009-03-17T15:06:46Z
654,689
9
2009-03-17T15:16:09Z
[ "python", "dictionary", "fromkeys" ]
First, I'm new to Python, so I apologize if I've overlooked something, but I would like to use `dict.fromkeys` (or something similar) to create a dictionary of lists, the keys of which are provided in another list. I'm performing some timing tests and I'd like for the key to be the input variable and the list to contai...
The problem is that in ``` results = dict.fromkeys(inputs, []) ``` [] is evaluated only once, right there. I'd rewrite this code like that: ``` runs = 10 inputs = (1, 2, 3, 5, 8, 13, 21, 34, 55) results = {} for run in range(runs): for i in inputs: results.setdefault(i,[]).append(benchmark(i)) ``` Oth...
How to configure IPython to use gvim on Windows?
655,530
7
2009-03-17T18:33:24Z
655,642
8
2009-03-17T19:14:33Z
[ "python", "windows", "vim", "ipython" ]
This really looks like something I should be able to find on Google, but for some reason I can't make heads or tails of it. There's the EDITOR environment variable, the ipy\_user\_conf.py file, the ipythonrc file, some weird thing about running gvim in server mode and a bunch of other stuff I can't wrap my head around ...
Setting the EDITOR environment variable to 'gvim -f' seems to work. ``` set EDITOR=gvim -f ```
Why did Python 2.6 add a global next() function?
656,155
14
2009-03-17T21:42:39Z
656,184
18
2009-03-17T21:52:54Z
[ "python", "python-2.6" ]
I noticed that Python2.6 added a next() to it's [list of global functions](http://docs.python.org/library/functions.html). > [`next(iterator[, default])`](http://docs.python.org/library/functions.html#next) > > ``` > Retrieve the next item from the iterator by calling its next() method. > ``` > > If `default` is given...
It's just for consistency with functions like `len()`. I believe `next(i)` calls `i.__next__()` internally. See <http://www.python.org/dev/peps/pep-3114/>
Why did Python 2.6 add a global next() function?
656,155
14
2009-03-17T21:42:39Z
656,555
10
2009-03-18T00:31:36Z
[ "python", "python-2.6" ]
I noticed that Python2.6 added a next() to it's [list of global functions](http://docs.python.org/library/functions.html). > [`next(iterator[, default])`](http://docs.python.org/library/functions.html#next) > > ``` > Retrieve the next item from the iterator by calling its next() method. > ``` > > If `default` is given...
Note that in Python 3.0+ the `next` method has been renamed to `__next__`. This is because of consistency. `next` is a special method and special methods are named by convention (PEP 8) with double leading and trailing underscore. Special methods are not meant to be called directly, that's why the `next` built in funct...
python time + timedelta equivalent
656,297
37
2009-03-17T22:32:43Z
656,394
71
2009-03-17T23:14:34Z
[ "python" ]
I'm trying to do something like this: ``` time() + timedelta(hours=1) ``` however, [Python doesn't allow it](http://bugs.python.org/issue1487389), apparently for good reason. Does anyone have a simple work around? ### Related: * [Python - easy way to add N seconds to a datetime.time?](http://stackoverflow.com/ques...
The solution is in [the link that you provided](http://bugs.python.org/issue1487389) in your question: ``` datetime.combine(date.today(), time()) + timedelta(hours=1) ``` Full example: ``` from datetime import date, datetime, time, timedelta dt = datetime.combine(date.today(), time(23, 55)) + timedelta(minutes=30) ...
python time + timedelta equivalent
656,297
37
2009-03-17T22:32:43Z
6,838,994
7
2011-07-27T02:58:22Z
[ "python" ]
I'm trying to do something like this: ``` time() + timedelta(hours=1) ``` however, [Python doesn't allow it](http://bugs.python.org/issue1487389), apparently for good reason. Does anyone have a simple work around? ### Related: * [Python - easy way to add N seconds to a datetime.time?](http://stackoverflow.com/ques...
If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends `datetime.time` with the ability to do arithmetic. If you go past midnight, it just wraps around: ``` >>> from nptime import nptime >>> from datetime import timedelta >>> afternoon = nptime(12, 24) + time...
PyWinAuto still useful?
656,779
9
2009-03-18T02:34:01Z
657,105
8
2009-03-18T05:51:04Z
[ "python", "pywinauto" ]
I've been playing with PyWinAuto today and having fun automating all sorts GUI tests. I was wondering if it is still state of the art or if there might be something else (also free) which does windows rich client automation better.
pywinauto is great because it's Python. Perhaps a bit more full featured is [AutoIT](http://www.autoitscript.com/autoit3/index.shtml), which has a COM server that you can automate (from Python using win32com), and some cool tools, like a "[Window Info](http://www.autoitscript.com/autoit3/docs/intro/au3spy.htm)" utilit...
PyWinAuto still useful?
656,779
9
2009-03-18T02:34:01Z
1,653,008
7
2009-10-31T00:49:55Z
[ "python", "pywinauto" ]
I've been playing with PyWinAuto today and having fun automating all sorts GUI tests. I was wondering if it is still state of the art or if there might be something else (also free) which does windows rich client automation better.
I used to do test automation on our projects with AutoIt but switched over to pywinauto 3 months ago and have been very happy with that decision. There are some rough edges, but I've been able to fill them in with my own supplementary test functions. In addition I find that coding tests and support code in Python is *m...
Communicating with a running python daemon
656,933
44
2009-03-18T04:09:31Z
656,956
18
2009-03-18T04:22:00Z
[ "python", "daemon" ]
I wrote a small Python application that runs as a daemon. It utilizes threading and queues. I'm looking for general approaches to altering this application so that I can communicate with it while it's running. Mostly I'd like to be able to monitor its health. In a nutshell, I'd like to be able to do something like th...
What about having it run an http server? It seems crazy but running a simple web server for administrating your server requires just a few lines using web.py You can also consider creating a unix pipe.
Communicating with a running python daemon
656,933
44
2009-03-18T04:09:31Z
657,031
9
2009-03-18T05:04:08Z
[ "python", "daemon" ]
I wrote a small Python application that runs as a daemon. It utilizes threading and queues. I'm looking for general approaches to altering this application so that I can communicate with it while it's running. Mostly I'd like to be able to monitor its health. In a nutshell, I'd like to be able to do something like th...
I would use twisted with a named pipe or just open up a socket. Take a look at the echo server and client [examples](http://twistedmatrix.com/projects/core/documentation/examples/). You would need to modify the echo server to check for some string passed by the client and then respond with whatever requested info. Bec...