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
Is it possible to convert a list-type into a generator without iterating through?
5,933,966
14
2011-05-09T07:42:08Z
5,933,992
27
2011-05-09T07:45:59Z
[ "python", "list", "generator" ]
I know that it's possible to convert generators into lists at a "low-level" (eg. `list(i for i in xrange(10))`), but is it possible to do the reverse *without* iterating through the list first (eg. `(i for i in range(10))`)? **Edit:** removed the word `cast` for clarity in what I'm trying to achieve. **Edit 2:** Actu...
Try this: `an_iterator = iter(a_list)` ... [docs here](http://docs.python.org/library/functions.html#iter). Is that what you want?
Is it possible to convert a list-type into a generator without iterating through?
5,933,966
14
2011-05-09T07:42:08Z
5,934,045
8
2011-05-09T07:51:51Z
[ "python", "list", "generator" ]
I know that it's possible to convert generators into lists at a "low-level" (eg. `list(i for i in xrange(10))`), but is it possible to do the reverse *without* iterating through the list first (eg. `(i for i in range(10))`)? **Edit:** removed the word `cast` for clarity in what I'm trying to achieve. **Edit 2:** Actu...
You can take a list out of an iterator by using the built-in function `list(...)` and an iterator out of a list by using `iter(...)`: ``` mylist = list(myiterator) myiterator = iter(mylist) ``` Indeed, your syntax **is** an iterator: ``` iter_10 = (i for i in range(10)) ``` instead of using `[...]` which gives a li...
How can django sql queries use case insensitive and contains at the same time?
5,935,447
20
2011-05-09T10:15:18Z
5,935,468
34
2011-05-09T10:17:52Z
[ "python", "django" ]
Suppose I have two users with username 'AbA' and 'aBa' in the database. My query word is 'ab'. I used `User.objects.filter(username__contains='ab')` and `User.objects.filter(username__iexact='ab')` These two queries get empty result. However, I want to use something like `username__contains__iexact='ab'` that can ...
Use: ``` User.objects.filter(username__icontains='ab') ```
How can django sql queries use case insensitive and contains at the same time?
5,935,447
20
2011-05-09T10:15:18Z
5,935,474
9
2011-05-09T10:18:30Z
[ "python", "django" ]
Suppose I have two users with username 'AbA' and 'aBa' in the database. My query word is 'ab'. I used `User.objects.filter(username__contains='ab')` and `User.objects.filter(username__iexact='ab')` These two queries get empty result. However, I want to use something like `username__contains__iexact='ab'` that can ...
`icontains` is case-insensitive - [http://docs.djangoproject.com/en/dev/ref/models/querysets/#std:fieldlookup-icontains](http://docs.djangoproject.com/en/dev/ref/models/querysets/#std%3afieldlookup-icontains)
Autocomplete Textbox Example in python + Google app engine
5,935,638
5
2011-05-09T10:34:02Z
5,936,103
8
2011-05-09T11:15:19Z
[ "python", "ajax", "google-app-engine", "autocomplete" ]
For my google app engine application, I need to include a autocompleter Textbox which will show the name starting with the textbox value.And the name will retrieve from the google app engine datastore. Any good tutorial or sample code please. **Update: Please Answer for this** I created a sample HTML code : [dl.drop...
You can have a look at the jquery auto complete [here](http://docs.jquery.com/Plugins/autocomplete) **HTML :** ``` $("#search_users").autocomplete(/search/search_manager); ``` **python-controller**: jquery autocomplete plugin by default uses variable q ``` class search_user(webapp.RequestHandler): q = ...
Writing Python 2.7 code that is as close to Python 3.x syntax as possible
5,937,251
43
2011-05-09T13:03:08Z
5,937,363
17
2011-05-09T13:12:39Z
[ "python", "python-3.x" ]
Since Django doesn't yet support Python 3.x, I'm using Python 2.7. However, I'd like to go ahead and start familiarizing myself with the new Python 3.x syntax as much as possible. Which leads me to the question: * What is the best way to write Python 2.7 code that will be as compatible as possible with Python 3.x? I ...
Many modules these days get rewritten in a way that allows execution on both Python 2 and Python 3. This turns out to be not very hard at all, and in the future it will be very easy to just drop Python 2 support. Take a look at the [six](http://packages.python.org/six/) module that helps with this task, encapsulating ...
Writing Python 2.7 code that is as close to Python 3.x syntax as possible
5,937,251
43
2011-05-09T13:03:08Z
5,939,006
8
2011-05-09T15:22:52Z
[ "python", "python-3.x" ]
Since Django doesn't yet support Python 3.x, I'm using Python 2.7. However, I'd like to go ahead and start familiarizing myself with the new Python 3.x syntax as much as possible. Which leads me to the question: * What is the best way to write Python 2.7 code that will be as compatible as possible with Python 3.x? I ...
You also need to use the new exception syntaxes, ie no more ``` try: raise Exception, "Message" except Exception, e: pass ``` instead you should do: ``` try: raise Exception("Message") except Exception as e: pass ``` Also make sure you prefix all your binary strings with a b, ie: b'This is a bi...
Writing Python 2.7 code that is as close to Python 3.x syntax as possible
5,937,251
43
2011-05-09T13:03:08Z
14,011,857
8
2012-12-23T14:42:55Z
[ "python", "python-3.x" ]
Since Django doesn't yet support Python 3.x, I'm using Python 2.7. However, I'd like to go ahead and start familiarizing myself with the new Python 3.x syntax as much as possible. Which leads me to the question: * What is the best way to write Python 2.7 code that will be as compatible as possible with Python 3.x? I ...
Many Python IDE's can be of big help here. [PyCharm](http://www.jetbrains.com/pycharm/), for example, can be configured to check for compatibility with any range of versions, ![enter image description here](http://i.stack.imgur.com/Lhkll.png) and report issues at any level of severity: ![enter image description her...
Writing Python 2.7 code that is as close to Python 3.x syntax as possible
5,937,251
43
2011-05-09T13:03:08Z
19,212,681
8
2013-10-06T18:58:33Z
[ "python", "python-3.x" ]
Since Django doesn't yet support Python 3.x, I'm using Python 2.7. However, I'd like to go ahead and start familiarizing myself with the new Python 3.x syntax as much as possible. Which leads me to the question: * What is the best way to write Python 2.7 code that will be as compatible as possible with Python 3.x? I ...
Put the following code into a `py3k.py` module and import it like this: `from py3k import *`. You need to put it in every file though, but you can even leave it there if nobody uses Python 2.x anymore or you could just search & replace the import line with whitespace and then remove the file. ``` try: from future_...
Building Python with SSL support in non-standard location
5,937,337
18
2011-05-09T13:10:47Z
5,939,170
16
2011-05-09T15:37:28Z
[ "python", "openssl", "compilation" ]
I need to install several Python modules on a RHEL where I don't have root access. At least one of the modules also needs access to `Python.h`. In this case I find that the best thing is to install python and it dependencies in `~/local`. It usually just works, but this time Python fails to build the SSL module (see d...
You need to edit `Modules/Setup.dist` to specify the location of OpenSSL if it is not in the standard location. From [Getting SSL Support in Python 2.5.1](http://paltman.com/2007/nov/15/getting-ssl-support-in-python-251/): > If you find yourself on a linux box needing ssl support in python (to > use a client in things...
Converting a nested dictionary to a list
5,938,125
3
2011-05-09T14:15:25Z
5,938,216
8
2011-05-09T14:22:54Z
[ "python", "django", "django-templates", "django-views" ]
I know there are many dict to list questions on here but I can't quite find the information I need for my situation so I'm asking a new quetion. Some background: I'm using a hierarchical package for my models and the built-in function which generates the tree structure outputs a nested loop to indicate parents, childr...
I think recursion can be your friend : ``` top = {"<Part: 1.1>": {"<Part: 1.1.1>": {"<Part: 1.1.1.1>": {}}, "<Part: 1.1.2>": {}}, "<Part: 1.2>": {"<Part: 1.2.1>": {}, "<Part: 1.2.2>": {}}, "<Part: 1.3>": {}} def grab_children(father): local_list = [] for key, value in father.iteritems(): local_list.a...
Combining plt.plot(x,y) with plt.boxplot()
5,938,459
9
2011-05-09T14:41:29Z
5,941,619
12
2011-05-09T19:38:15Z
[ "python", "numpy", "matplotlib", "plot", "boxplot" ]
I'm trying to combine a normal matplotlib.pyplot `plt.plot(x,y)` with variable `y` as a function of variable `x` with a boxplot. However, I only want a boxplot on certain (variable) locations of `x` but this does not seem to work in matplotlib?
Are you wanting something like this? The `positions` kwarg to `boxplot` allows you to place the boxplots at arbitrary positions. ``` import matplotlib.pyplot as plt import numpy as np # Generate some data... data = np.random.random((100, 5)) y = data.mean(axis=0) x = np.random.random(y.size) * 10 x -= x.min() x.sort(...
Not able call a local method from setUpClass
5,938,517
5
2011-05-09T14:45:30Z
5,938,612
10
2011-05-09T14:52:36Z
[ "python", "unit-testing" ]
My code: ``` class TestSystemPromotion(unittest2.TestCase): @classmethod def setUpClass(self): ... self.setup_test_data() .. def test_something(self): ... def setup_test_data(self): ... if __name__ == '__main__': unittest2.main() ``` Error which I'm getting is: ``` TypeError: unboun...
You can't call instance methods from class methods. Either consider using `setUp` instead, or make `setup_test_data` a class method too. Also, it's better if you called the argument `cls` instead of `self` to avoid the confusion - the first argument to the class method is the class, not the instance. The instance (`sel...
How would you zip an unknown number of lists in Python?
5,938,786
12
2011-05-09T15:06:06Z
5,938,825
24
2011-05-09T15:08:52Z
[ "python", "list", "zip" ]
Let's say I have the following lists: ``` assignment = ['Title', 'Project1', 'Project2', 'Project3'] grades = [ ['Jim', 45, 50, 55], \ ['Joe', 55, 50, 45], \ ['Pat', 55, 60, 65] ] ``` I could zip the lists using the following code: ``` zip(assignment, grades[0], grades[1], grades[2]) ``` How w...
You can use `*` to [unpack](http://docs.python.org/dev/tutorial/controlflow.html#unpacking-argument-lists) a list into positional parameters: ``` zip(assignment, *grades) ```
Setting different reply-to message in Python email/smtplib
5,938,890
14
2011-05-09T15:14:34Z
6,062,741
21
2011-05-19T17:49:06Z
[ "python", "email", "smtplib" ]
I am using Python email and smtplib to send an email from Python. I am doing this via the Gmail SMTP server using my Gmail credentials. This works fine, however I would like to specify a `Reply-to` email address different from the `from` address, so that replies go to a separate address (non-Gmail.) I have tried creat...
Here's my take on it. I believe that the "Reply-To" header should be set explicitly. The likely reason is that it's less commonly used than headers such as "Subject", "To", and "From". ``` python Python 2.6.6 (r266:84292, May 10 2011, 11:07:28) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyr...
Python, default keyword arguments after variable length positional arguments
5,940,180
54
2011-05-09T17:09:17Z
5,940,226
43
2011-05-09T17:14:14Z
[ "python", "named-parameters", "default-parameters", "variable-length-arguments" ]
I thought I could use named parameters after variable-length positional parameters in a function call, but I get a syntax error when importing a python class I'm writing with the following "get" method, for example: ``` class Foo(object): def __init__(self): print "You have created a Foo." def get(sel...
It does work, but only in Python 3. See PEP [3102](http://www.python.org/dev/peps/pep-3102/). From glancing over the "what's new" documents, it seems that there is no 2.x backport, so you're out of luck. You'll have to accept any keyword arguments (`**kwargs`) and manually parse it (you can use `d.get(k, default)` to e...
Python, default keyword arguments after variable length positional arguments
5,940,180
54
2011-05-09T17:09:17Z
5,940,228
35
2011-05-09T17:14:38Z
[ "python", "named-parameters", "default-parameters", "variable-length-arguments" ]
I thought I could use named parameters after variable-length positional parameters in a function call, but I get a syntax error when importing a python class I'm writing with the following "get" method, for example: ``` class Foo(object): def __init__(self): print "You have created a Foo." def get(sel...
Python's syntax doesn't allow variable args in function and keyword arguments with default value at the same time. If you must have keyword arguments along with arbitrary number of positional arguments, you need to allow arbitrary number of keyword arguments as well. This is a common pattern to provide default values ...
How to make FileField in django optional?
5,940,308
12
2011-05-09T17:22:23Z
5,940,364
27
2011-05-09T17:28:45Z
[ "python", "django", "django-forms" ]
I have form with a textbox and filefield in django. It should let the use either paste the text into that box or upload a file. If the user has pasted the text into the box, I needn't check the fileField. How do I make the forms.FileField() optional?
If you're using a `forms.FileField()` in a `forms.Form` derived class, you can set: ``` class form(forms.Form): file = forms.FileField(required=False) ``` If you're using a `models.FileField()` and have a `forms.ModelForm` assigned to that model, you can use ``` class amodel(models.Model): file = models.File...
Python decorator with parameters, to run the functions multiple times?
5,940,402
6
2011-05-09T17:32:32Z
5,940,516
11
2011-05-09T17:45:16Z
[ "python" ]
I want to write a python decorator to decorate a test function of a unittest.TestCase, to decide the target host this function should run against. See this example: ``` class MyTestCase(unittest.TestCase): @target_host(["host1.com", "host2.com"]) def test_my_command(self): #do something here against th...
You can return exactly one object (so technically, you could return a collections of functions). If you want to avoid astonishing everyone and if you want to call the result, you better return a single function though. But that function may very well call several other function in a loop... do you see where this leads ...
Compress a series of 1s and 0s into the shortest possible ascii string
5,940,416
6
2011-05-09T17:33:46Z
5,941,361
7
2011-05-09T19:14:36Z
[ "python", "compression", "base64", "coffeescript" ]
How could you convert a series of `1`s and `0`s into the shortest possible form consisting of URL safe ascii characters? eg. ``` s = '00100101000101111010101' compress(s) ``` **Resulting in something like:** `Ysi8aaU` **And obviously:** `decompress(compress(s)) == s` (I ask this question purely out of curiousity...
Here's the solution I came up with (+ far too many comments): ``` # A set of 64 characters, which allows a maximum chunk length of 6 .. because # int('111111', 2) == 63 (plus zero) charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' def encode(bin_string): # Split the string of 1s and 0s ...
Print to UTF-8 encoded file, with platform-dependent newlines?
5,941,988
11
2011-05-09T20:15:11Z
5,943,589
10
2011-05-09T23:24:58Z
[ "python", "text", "utf-8", "newline", "codec" ]
In Python, what is the best way to write to a UTF-8 encoded file with platform-dependent newlines? the solution would ideally work quite transparently in a program that does a lot of printing in Python 2. (Information about Python 3 is welcome too!) In fact, the standard way of writing to a UTF-8 file seems to be [cod...
Presuming Python 2.7.1 (that's the docs that you quoted): The 'wt' mode is not documented (the ONLY mode documented is 'r'), and does not work -- the codecs module appends 'b' to the mode, which causes it to fail: ``` >>> f = codecs.open('bar.txt', 'wt', encoding='utf8') Traceback (most recent call last): File "<std...
Python CSV to SQLite
5,942,402
15
2011-05-09T20:55:54Z
5,942,463
22
2011-05-09T21:01:20Z
[ "python", "csv", "sqlite3" ]
I am "converting" a large (~1.6GB) CSV file and inserting specific fields of the CSV into a SQLite database. Essentially my code looks like: ``` import csv, sqlite3 conn = sqlite3.connect( "path/to/file.db" ) conn.text_factory = str #bugger 8-bit bytestrings cur = conn.cur() cur.execute('CREATE TABLE IF NOT EXISTS m...
It's possible to import the CSV directly: ``` sqlite> .separator "," sqlite> .import filecsv.txt mytable ``` <http://www.sqlite.org/cvstrac/wiki?p=ImportingFiles>
Python CSV to SQLite
5,942,402
15
2011-05-09T20:55:54Z
7,137,270
13
2011-08-21T08:43:18Z
[ "python", "csv", "sqlite3" ]
I am "converting" a large (~1.6GB) CSV file and inserting specific fields of the CSV into a SQLite database. Essentially my code looks like: ``` import csv, sqlite3 conn = sqlite3.connect( "path/to/file.db" ) conn.text_factory = str #bugger 8-bit bytestrings cur = conn.cur() cur.execute('CREATE TABLE IF NOT EXISTS m...
*Chris* is right - use transactions; divide the data into chunks and then store it. "*... Unless already in a transaction, each SQL statement has a new transaction started for it. This is very expensive, since it requires reopening, writing to, and closing the journal file for each statement. This can be avoided by wr...
Python CSV to SQLite
5,942,402
15
2011-05-09T20:55:54Z
9,913,925
12
2012-03-28T18:54:45Z
[ "python", "csv", "sqlite3" ]
I am "converting" a large (~1.6GB) CSV file and inserting specific fields of the CSV into a SQLite database. Essentially my code looks like: ``` import csv, sqlite3 conn = sqlite3.connect( "path/to/file.db" ) conn.text_factory = str #bugger 8-bit bytestrings cur = conn.cur() cur.execute('CREATE TABLE IF NOT EXISTS m...
As it's been said (Chris and Sam), transactions do improve a lot insert performance. Please, let me recommend another option, to use a suite of Python utilities to work with CSV, [csvkit](https://github.com/onyxfish/csvkit). To install: ``` pip install csvkit ``` To solve your problem ``` csvsql --db sqlite:///pat...
Pyside, webkit basic question
5,942,487
9
2011-05-09T21:04:43Z
5,942,940
13
2011-05-09T21:52:58Z
[ "python", "qt", "webkit", "pyside" ]
I am currently running this code, and although the web browser appears, the web inspector doesn't seem to display anything, am i doing something incorrectly? ``` import sys from PySide.QtCore import * from PySide.QtGui import * from PySide.QtWebKit import * app = QApplication(sys.argv) web = QWebView() web.load(QUrl...
It is in the [Qt Documentation](http://doc.qt.nokia.com/4.7-snapshot/qwebinspector.html): > Note: A QWebInspector will display a > blank widget if either: page() is null > QWebSettings::DeveloperExtrasEnabled > is false You must enable it, like this: ``` import sys from PySide.QtCore import * from PySide.QtGui impor...
best place to clear cache when restarting django server
5,942,759
18
2011-05-09T21:35:13Z
5,943,293
41
2011-05-09T22:35:21Z
[ "python", "django", "memcached" ]
I want memcached to be flushed on every restart/reload of django server. I use cherrypy for production and builtin server for development. I would add this to settings.py, right after CACHES: ``` from django.core.cache import cache cache.clear() ``` but it makes a recursive import: ``` Error: Can't find the file 's...
It's bad practice to put code in `settings.py` other than assignments. It's better suited as a management command: ``` from django.core.management.base import BaseCommand from django.core.cache import cache class Command(BaseCommand): def handle(self, *args, **kwargs): cache.clear() self.stdout.wr...
Python - converting textfile contents into dictionary values/keys easily
5,942,874
3
2011-05-09T21:46:24Z
5,942,916
10
2011-05-09T21:50:19Z
[ "python", "dictionary", "formatting", "key" ]
Let's say I have a text file with the following: ``` line = "this is line 1" line2 = "this is the second line" line3 = "here is another line" line4 = "yet another line!" ``` And I want to quickly convert these into dictionary keys/values with " line\* " being the key and the text in quotes as the value while also rem...
``` f = open(filepath, 'r') answer = {} for line in f: k, v = line.strip().split('=') answer[k.strip()] = v.strip() f.close() ``` Hope this helps
Python argparse and controlling/overriding the exit status code
5,943,249
24
2011-05-09T22:29:20Z
5,943,381
22
2011-05-09T22:49:58Z
[ "python", "argparse" ]
Apart from tinkering with the `argparse` source, is there any way to control the exit status code should there be a problem when `parse_args()` is called, for example, a missing required switch?
I'm not aware of any mechanism to specify an exit code on a per-argument basis. You can catch the `SystemExit` exception raised on `.parse_args()` but I'm not sure how you would then ascertain what *specifically* caused the error. **EDIT:** For anyone coming to this looking for a practical solution, the following is t...
Python argparse and controlling/overriding the exit status code
5,943,249
24
2011-05-09T22:29:20Z
5,943,389
19
2011-05-09T22:50:38Z
[ "python", "argparse" ]
Apart from tinkering with the `argparse` source, is there any way to control the exit status code should there be a problem when `parse_args()` is called, for example, a missing required switch?
Perhaps catching the `SystemExit` exception would be a simple workaround: ``` import argparse parser = argparse.ArgumentParser() parser.add_argument('foo') try: args = parser.parse_args() except SystemExit: print("do something else") ``` Works for me, even in an interactive session. **Edit:** Looks like @Rob...
Python argparse and controlling/overriding the exit status code
5,943,249
24
2011-05-09T22:29:20Z
16,942,165
14
2013-06-05T14:08:50Z
[ "python", "argparse" ]
Apart from tinkering with the `argparse` source, is there any way to control the exit status code should there be a problem when `parse_args()` is called, for example, a missing required switch?
All the answers nicely explain the details of **argparse** implementation. Indeed, as proposed in [PEP](http://www.python.org/dev/peps/pep-0389/#discussion-sys-stderr-and-sys-exit) (and pointed by Rob Cowie) one should inherit *ArgumentParser* and override the behavior of **error** or **exit** methods. In my case I j...
Learning python and having trouble with 1st program
5,943,282
2
2011-05-09T22:33:49Z
5,943,318
7
2011-05-09T22:38:03Z
[ "python" ]
I wrote this code and it is failing at line 11 on the "target\_dir" command with invalid syntax I have a vm ubuntu and I just copy and pasted the code and it worked there but not in my win7 and I am not sure why. I was reading another question with similar code but it had a different error and noticed that someone said...
`source = ['"D:\\Warlock"', 'C:\\Druid'` is missing an end bracket. Should be `source = ['"D:\\Warlock"', 'C:\\Druid']`. **Edit**: Also, ``` zip_commnad = "7z a -tzip {0} {1}" .format(target, ' '.join(source)) print(zip_command) ``` should be ``` zip_command = "7z a -tzip {0} {1}" .format(target, ' '.join(sourc...
Chronic stale results using MySQLdb in Python
5,943,418
19
2011-05-09T22:56:13Z
5,943,518
18
2011-05-09T23:10:29Z
[ "python", "mysql", "caching" ]
My Python program queries a set of tables in a MySQL DB, sleeps for 30 seconds, then queries them again, etc. The tables in question are continuously updated by a third-party, and (obviously) I would like to see the new results every 30 seconds. Let's say my query looks like this: ``` "select * from A where A.key > %...
[This website](http://sourceforge.net/projects/mysql-python/forums/forum/70461/topic/1653833) and [this website](http://mysql-python.sourceforge.net/FAQ.html#id3) contain information on the same problem. In order to keep your tables up to date, you must commit your transactions. Use `db.commit()` to do this. As mentio...
Chronic stale results using MySQLdb in Python
5,943,418
19
2011-05-09T22:56:13Z
16,009,279
9
2013-04-15T06:51:04Z
[ "python", "mysql", "caching" ]
My Python program queries a set of tables in a MySQL DB, sleeps for 30 seconds, then queries them again, etc. The tables in question are continuously updated by a third-party, and (obviously) I would like to see the new results every 30 seconds. Let's say my query looks like this: ``` "select * from A where A.key > %...
You may want to check the transaction isolation level of your database. The behavior you describe is what you may expect if it is set to REPEATABLE-READ. You may want to change it to READ-COMMITTED. Since the original poster of the problem mentions that he is merely querying the database, it cannot be a commit that wa...
Is there a dataset in python similar to structs in C++?
5,943,425
9
2011-05-09T22:56:48Z
5,943,442
16
2011-05-09T22:58:54Z
[ "c++", "python", "types", "struct" ]
Is there a dataset in python similar to structs in C++? I like the struct feature `myStruct.someName`. I know, that classes have this, but I don't want to write a class everytime I need a "container" for some data. =)
Why not? Classes are fine for that. If you want to save some memory, you might also want to use `__slots__` so the objects don't have a `__dict__`. See <http://docs.python.org/reference/datamodel.html#slots> for details and [Python \_\_slots\_\_](http://stackoverflow.com/questions/472000/python-slots) for some useful ...
Is there a dataset in python similar to structs in C++?
5,943,425
9
2011-05-09T22:56:48Z
5,943,661
7
2011-05-09T23:38:46Z
[ "c++", "python", "types", "struct" ]
Is there a dataset in python similar to structs in C++? I like the struct feature `myStruct.someName`. I know, that classes have this, but I don't want to write a class everytime I need a "container" for some data. =)
In addition to the dict type, there is a [namedtuple](http://docs.python.org/dev/library/collections.html#collections.namedtuple) type that behaves somewhat like a struct. ``` MyStruct = namedtuple('MyStruct', ['someName', 'anotherName']) aStruct = MyStruct('aValue', 'anotherValue') print aStruct.someName, aStruct.an...
Is there a way to find out the name of the file stdout is redirected to in Python
5,943,778
6
2011-05-10T00:04:51Z
5,943,826
10
2011-05-10T00:14:58Z
[ "python", "python-2.7" ]
I know how to detect if my Python script's `stdout` is being redirected (`>`) using `sys.stdout.isatty()` but is there a way to discover what it's being redirected to? For example: ``` python my.py > somefile.txt ``` Is there a way to discover the name `somefile.txt` on both Windows and Linux?
I doubt you can do that in a system-independent way. On Linux, the following works: ``` import os my_output_file = os.readlink('/proc/%d/fd/1' % os.getpid()) ```
Django: why are Django model fields class attributes?
5,943,846
8
2011-05-10T00:18:58Z
5,943,870
14
2011-05-10T00:22:19Z
[ "python", "django", "django-models" ]
In Django a model's fields are defined as class attributes. So that would mean all instances of a model would share the same values for those fields, no? Say I have a model ``` class Tag(models.Model): name = models.CharField(max_length=30) ``` And I have a form in which users can submit tags. Say a user submit...
No, for the same reason as this: ``` >>> class Foo(object): ... bar = 'Foo attribute' ... >>> f = Foo() >>> f.bar 'Foo attribute' >>> Foo.bar 'Foo attribute' >>> f.bar = 'instance attribute' >>> f.bar 'instance attribute' >>> Foo.bar 'Foo attribute' ``` When you assign an attribute to an object, a class attribute...
Python build using wrong version of GCC on OS X
5,944,228
6
2011-05-10T01:23:04Z
5,944,497
15
2011-05-10T02:19:59Z
[ "python", "osx", "gcc" ]
I am attempting to build the python package pycrypto. OS X has gcc-4.2 installed and not gcc-4.0, but python continues to attempt to use gcc-4.0. How can I get it to use gcc-4.2? Or should I go about this a different way. I am getting the following error: ``` bash-3.2$ bash-3.2$ sudo python setup.py build running bu...
Based on the path shown (`/Library/Frameworks/Python.framework/Versions/2.6`), it appears you have installed a 32-bit-only Python 2.6, perhaps using a python.org installer. When you build a Python package that includes a C extension module, the Python Distutils included with that Python instance will attempt to use the...
Broken Pipe error when using pip to install pycrypto on Mac OS X
5,944,332
29
2011-05-10T01:43:18Z
5,944,375
65
2011-05-10T01:54:51Z
[ "python", "osx", "gcc", "pip", "pycrypto" ]
I am attempting to install pycrypto (version 2.3) on OS X via pip. I am getting a "Broken pipe" error when the compiler attempts to compile MD2.c. I get a very similar error when using easy\_install. Here is the error that I am getting: ``` bash-3.2$ bash-3.2$ sudo pip install pycrypto Password: Downloading/unpackin...
If you have installed Xcode 4, try setting `ARCHFLAGS` before calling `pip` or `easy_install`: ``` sudo bash export ARCHFLAGS='-arch i386 -arch x86_64' pip ... ``` The problem is that Xcode 4 has removed support for `-arch ppc` but the system Python 2.6 on Mac OS X 10.6 expects to build universal C extension modules ...
sort a list of dicts by x then by y
5,944,630
3
2011-05-10T02:50:42Z
5,944,671
9
2011-05-10T02:56:23Z
[ "python", "list", "sorting" ]
I want to sort this info(name, points, and time): ``` list = [ {'name':'JOHN', 'points' : 30, 'time' : '0:02:2'}, {'name':'KARL','points':50,'time': '0:03:00'} ] ``` so, what I want is the list sorted first by points made, then by time played (in my example, matt go first because of his less time. any help? ...
Your example works for me. I would advise you not to use `list` as a variable name, since it is a builtin type. You could try doing something like this also: ``` list.sort(key=lambda item: (item['points'], item['time'])) ```
Python, forcing a list to a fixed size
5,944,708
32
2011-05-10T03:04:47Z
5,944,754
60
2011-05-10T03:12:18Z
[ "python", "list" ]
In Python(3) I want to create a list that will contain the last 5 variables entered into it. Here is an example: ``` >>>l = [] >>>l.append('apple') >>>l.append('orange') >>>l.append('grape') >>>l.append('banana') >>>l.append('mango') >>>print(l) ['apple','orange','grape','banana','mango'] >>>l.append('kiwi') >>>print(...
You might want to use a [collections.deque](http://docs.python.org/library/collections.html#deque-objects) object with the maxlen constructor argument instead: ``` >>>l = collections.deque(maxlen=5) >>>l.append('apple') >>>l.append('orange') >>>l.append('grape') >>>l.append('banana') >>>l.append('mango') >>>print(l) d...
Python, forcing a list to a fixed size
5,944,708
32
2011-05-10T03:04:47Z
5,944,763
10
2011-05-10T03:14:31Z
[ "python", "list" ]
In Python(3) I want to create a list that will contain the last 5 variables entered into it. Here is an example: ``` >>>l = [] >>>l.append('apple') >>>l.append('orange') >>>l.append('grape') >>>l.append('banana') >>>l.append('mango') >>>print(l) ['apple','orange','grape','banana','mango'] >>>l.append('kiwi') >>>print(...
You could subclass `list` ``` >>> class L(list): ... def append(self, item): ... list.append(self, item) ... if len(self) > 5: self[:1]=[] ... >>> l = L() >>> l.append('apple') >>> l.append('orange') >>> l.append('grape') >>> l.append('banana') >>> l.append('mango') >>> print(l) ['apple', 'orange'...
How to log exceptions in appengine?
5,944,775
6
2011-05-10T03:16:07Z
5,945,514
7
2011-05-10T05:22:07Z
[ "python", "google-app-engine", "logging", "error-handling", "error-logging" ]
``` try: #do something that raises an exception... except: logging.error('Error Message') ``` I want more than just "Error Message" to show in the logs. I want to see the traceback, or at least what the exception was, in the logs as well. How do I do that? Thanks!
This is what I use to log the entire stack trace: ``` import traceback try: # your code except: stacktrace = traceback.format_exc() logging.error("%s", stacktrace) ```
Python: why can't descriptors be instance variables?
5,944,800
4
2011-05-10T03:20:09Z
5,944,821
8
2011-05-10T03:22:59Z
[ "python", "scope", "descriptor" ]
Say I define this descriptor: ``` class MyDescriptor(object): def __get__(self, instance, owner): return self._value def __set__(self, instance, value): self._value = value def __delete__(self, instance): del(self._value) ``` And I use it in this: ``` class MyClass1(object): ...
You're ignoring the `instance` parameter in your implementation of `MyDescriptor`. That is why it *appears* to be a class attribute. Perhaps you want something like this: ``` class MyDescriptor(object): def __get__(self, instance, owner): return instance._value def __set__(self, instance, value): ...
When processing a file, how do I obtain the current line number?
5,944,908
8
2011-05-10T03:42:06Z
5,944,917
9
2011-05-10T03:44:40Z
[ "python", "line-numbers" ]
When I am looping over a file using the construct below, I also want the current line number. ``` with codecs.open(filename, 'rb', 'utf8' ) as f: retval = [] for line in f: process(line) ``` Does something akin to this exist ? ``` for line, lineno in f: ```
``` for lineno, line in enumerate(f, start=1): ``` If you are stuck on a version of Python that doesn't allow you to set the starting number for `enumerate` (this feature was added in Python 2.6), and you want to use this feature, the best solution is probably to provide an implementation that does, rather than adjust...
How to get the difference of two querysets in Django
5,945,912
9
2011-05-10T06:09:31Z
5,945,990
8
2011-05-10T06:20:03Z
[ "python", "django", "django-queryset" ]
I have to querysets. alllists and subscriptionlists ``` alllists = List.objects.filter(datamode = 'A') subscriptionlists = Membership.objects.filter(member__id=memberid, datamode='A') ``` I need a queryset called unsubscriptionlist, which possess all records in alllists except the records in subscription lists. How t...
Well I see two options here. # 1. Filter things manually (quite ugly) ``` diff = [] for all in alllists: found = False for sub in subscriptionlists: if sub.id == all.id: found = True break if not found: diff.append(all) ``` # 2. Just make another query ``` diff =...
How to get the difference of two querysets in Django
5,945,912
9
2011-05-10T06:09:31Z
5,946,384
9
2011-05-10T07:06:39Z
[ "python", "django", "django-queryset" ]
I have to querysets. alllists and subscriptionlists ``` alllists = List.objects.filter(datamode = 'A') subscriptionlists = Membership.objects.filter(member__id=memberid, datamode='A') ``` I need a queryset called unsubscriptionlist, which possess all records in alllists except the records in subscription lists. How t...
You should be able to use the set operation difference to help: ``` set(alllists).difference(set(subscriptionlists)) ```
How to merge multiple dicts with same key?
5,946,236
25
2011-05-10T06:50:04Z
5,946,322
30
2011-05-10T07:00:07Z
[ "python", "dictionary", "merge" ]
I have multiple dicts/key-value pairs like this: ``` d1 = {key1: x1, key2: y1) d2 = {key1: x2, key2: y2) ``` I want the result to be a new dict (in most efficient way, if possible): ``` d = {key1: (x1, x2), key2: (y1, y2)} ``` Actually, I want result d to be: ``` d = {key1: (x1.x1attrib, x2.x2attrib), key2: (y1....
Here's a general solution that will handle an arbitraty amount of dictionaries, with cases when keys are in only some of the dictionaries: ``` from collections import defaultdict d1 = {1: 2, 3: 4} d2 = {1: 6, 3: 7} dd = defaultdict(list) for d in (d1, d2): # you can list as many input dicts as you want here for...
How to get the common name for a pytz timezone eg. EST/EDT for America/New_York
5,946,499
18
2011-05-10T07:17:30Z
5,946,616
26
2011-05-10T07:28:24Z
[ "python", "django", "timezone", "pytz" ]
Given a pytz timezone for a particular user(calculated from his offset), i want to display the common name for that timezone. I'm assuming people are more accustomed to seeing **EST** or **PST** instead of spelled out like **America/NewYork**. Does pytz give me those standard names somewhere, or will i have to manuall...
> Given a pytz timezone for a particular user(calculated from his offset), i want to display the common name for that timezone. I'm assuming people are more accustomed to seeing EST or PST instead of spelled out like America/NewYork. If you need this derived from a `datetime` object localized with `pytz`... ``` >>> i...
Deleting a line from a file in Python
5,947,833
9
2011-05-10T09:14:43Z
5,947,880
10
2011-05-10T09:18:43Z
[ "python", "string", "file", "line" ]
I'm trying to delete a specific line that contains a specific string. I've a file called **numbers.txt** with the following content: > peter > tom > tom1 > yan What I want to delete is that **tom** from the file, so I made this function: ``` def deleteLine(): fn = 'numbers.txt' f = open(fn) output = [] for li...
change the line: ``` if not "tom" in line: ``` to: ``` if "tom" != line.strip(): ```
How can I force a dictionary in python to only have unique keys?
5,947,950
4
2011-05-10T09:26:00Z
5,948,050
12
2011-05-10T09:33:55Z
[ "python", "dictionary" ]
is it possible to design a dictionary in python in a way that is bound to have unique keys and if by mistake a key which is already in the dictionary is added gets rejected. thanks
You can always create your own dictionary ``` class UniqueDict(dict): def __setitem__(self, key, value): if key not in self: dict.__setitem__(self, key, value) else: raise KeyError("Key already exists") ```
Python generators and coroutines
5,948,643
6
2011-05-10T10:25:36Z
8,088,242
16
2011-11-11T00:24:48Z
[ "python", "generator", "coroutine" ]
I am studying coroutines and generators in various programming languages. I was wondering if there is a cleaner way to combine together two coroutines implemented via generators than yielding back at the caller whatever the callee yields? Let's say that we are using the following convention: all yields apart from the...
*Edit: I recommend using [Greenlet](http://pypi.python.org/pypi/greenlet). But if you're interested in a pure Python approach, read on.* This is addressed in [PEP 342](http://python.org/dev/peps/pep-0342), but it's somewhat tough to understand at first. I'll try to explain simply how it works. First, let me sum up wh...
How to unittest command line arguments?
5,949,181
4
2011-05-10T11:18:40Z
5,949,388
7
2011-05-10T11:34:38Z
[ "python", "unit-testing", "command-line-arguments" ]
I am trying to supply command line arguments to Python `unittest` and facing some issues. I have searched on internet and found a way to supply arguments as ``` unittest.main(argv=[myArg]) ``` The issue is this works fine for single command line argument but fails for more than one arguments. ``` unittest.main(argv=...
Why not just take out the command line arguments before running `unittest.main`, and then give it `[sys.argv[0]]` for *its* `argv`? Something like: ``` if __name__ == '__main__': # do stuff with sys.argv unittest.main(argv=[sys.argv[0]]) ``` Note that when given `argv=None`, `unittest.main` actually takes this...
How to save a list as numpy array in python?
5,951,135
29
2011-05-10T13:51:38Z
5,951,180
10
2011-05-10T13:56:08Z
[ "python", "list", "numpy" ]
I need to know if it is possible to save a python list as a numPy array.
you mean something like this ? ``` from numpy import array a = array( your_list ) ```
How to save a list as numpy array in python?
5,951,135
29
2011-05-10T13:51:38Z
5,951,187
39
2011-05-10T13:57:01Z
[ "python", "list", "numpy" ]
I need to know if it is possible to save a python list as a numPy array.
If you look here, it might tell you what you need to know. <http://www.scipy.org/Tentative_NumPy_Tutorial#head-d3f8e5fe9b903f3c3b2a5c0dfceb60d71602cf93> Basically, you can create an array from a sequence. ``` from numpy import array a = array( [2,3,4] ) ``` Or from a sequence of sequences. ``` from numpy import ar...
How to save a list as numpy array in python?
5,951,135
29
2011-05-10T13:51:38Z
5,951,368
9
2011-05-10T14:10:35Z
[ "python", "list", "numpy" ]
I need to know if it is possible to save a python list as a numPy array.
You want to save it as a file? ``` import numpy as np myList = [1, 2, 3] np.array(myList).dump(open('array.npy', 'wb')) ``` ... and then read: ``` myArray = np.load(open('array.npy', 'rb')) ```
How to know the system is Debian or CentOS in Python?
5,951,930
5
2011-05-10T14:49:16Z
5,952,060
9
2011-05-10T14:56:32Z
[ "python", "debian", "centos", "yum", "apt" ]
I want to write some install scripts by python, it should know the OS to choose either **apt** command or **yum** command. It seems **sys.platform** can tell **'win32'** or the others, but how to know it is working on Debian or CentOS in Python?
The [platform module](http://docs.python.org/library/platform.html) in the standard library has what you want. ``` import platform print platform.linux_distribution() ```
How do I format a string using a dictionary in python-3.x?
5,952,344
80
2011-05-10T15:15:36Z
5,952,407
12
2011-05-10T15:19:52Z
[ "python", "string", "dictionary", "python-3.x" ]
I am a big fan of using dictionaries to format strings. It helps me read the string format I am using as well as let me take advantage of existing dictionaries. For example: ``` class MyClass: def __init__(self): self.title = 'Title' a = MyClass() print 'The title is %(title)s' % a.__dict__ path = '/path...
``` print("{latitude} {longitude}".format(**geopoint)) ```
How do I format a string using a dictionary in python-3.x?
5,952,344
80
2011-05-10T15:15:36Z
5,952,429
48
2011-05-10T15:21:42Z
[ "python", "string", "dictionary", "python-3.x" ]
I am a big fan of using dictionaries to format strings. It helps me read the string format I am using as well as let me take advantage of existing dictionaries. For example: ``` class MyClass: def __init__(self): self.title = 'Title' a = MyClass() print 'The title is %(title)s' % a.__dict__ path = '/path...
To unpack a dictionary into keyword arguments, use `**`. Also,, new-style formatting supports referring to attributes of objects and items of mappings: ``` '{0[latitude]} {0[longitude]}'.format(geopoint) 'The title is {0.title}s'.format(a) # the a from your first example ```
How do I format a string using a dictionary in python-3.x?
5,952,344
80
2011-05-10T15:15:36Z
5,952,472
164
2011-05-10T15:25:34Z
[ "python", "string", "dictionary", "python-3.x" ]
I am a big fan of using dictionaries to format strings. It helps me read the string format I am using as well as let me take advantage of existing dictionaries. For example: ``` class MyClass: def __init__(self): self.title = 'Title' a = MyClass() print 'The title is %(title)s' % a.__dict__ path = '/path...
Is this good for you? ``` geopoint = {'latitude':41.123,'longitude':71.091} print('{latitude} {longitude}'.format(**geopoint)) ```
decorating decorators: try to get my head around understanding it
5,952,641
14
2011-05-10T15:36:56Z
5,952,807
16
2011-05-10T15:48:24Z
[ "python", "decorator" ]
I'm trying to understand decorating decorators, and wanted to try out the following: Let's say I have two decorators and apply them to the function hello: ``` def wrap(f): def wrapper(): return " ".join(f()) return wrapper def upper(f): def uppercase(*args, **kargs): a,b = f(*args, **kar...
``` def upper(f): @wrap def uppercase(*args, **kargs): a,b = f(*args, **kargs) return a.upper(), b.upper() return uppercase ``` --- A decorator in Python ``` @foo def bar(...): ... ``` is just equivalent to ``` def bar(...): ... bar = foo(bar) ``` You want to get the effect of ```...
Why are there no sorted containers in Python's standard libraries?
5,953,205
43
2011-05-10T16:24:24Z
5,958,960
44
2011-05-11T03:39:17Z
[ "python", "sortedset", "sortedmap" ]
Is there a Python design decision (PEP) that precludes a sorted container from being added to Python? (`OrderedDict` is not a sorted container since it is ordered by insertion order.)
It's a conscious design decision on Guido's part (he was even somewhat reluctant regarding the addition of the `collections` module). His goal is to preserve "one obvious way to do it" when it comes to the selection of data types for applications. The basic concept is that if a user is sophisticated enough to realise ...
Why are there no sorted containers in Python's standard libraries?
5,953,205
43
2011-05-10T16:24:24Z
10,814,225
9
2012-05-30T10:10:48Z
[ "python", "sortedset", "sortedmap" ]
Is there a Python design decision (PEP) that precludes a sorted container from being added to Python? (`OrderedDict` is not a sorted container since it is ordered by insertion order.)
There is also the [blist](http://pypi.python.org/pypi/blist) module that contains a [sortedset](http://stutzbachenterprises.com/blist/sortedset.html) data type: ``` sortedset(iterable=(), key=None) >>> from blist import sortedset >>> my_set = sortedset([3,7,2,2]) sortedset([2, 3, 7] ```
Why are there no sorted containers in Python's standard libraries?
5,953,205
43
2011-05-10T16:24:24Z
22,567,430
40
2014-03-21T19:04:15Z
[ "python", "sortedset", "sortedmap" ]
Is there a Python design decision (PEP) that precludes a sorted container from being added to Python? (`OrderedDict` is not a sorted container since it is ordered by insertion order.)
There's also a python [sortedcontainers](http://grantjenks.com/docs/sortedcontainers/) module that implements sorted list, dict, and set types. It's very similar to blist but implemented in **pure-Python** and in most cases [faster](http://grantjenks.com/docs/sortedcontainers/performance.html). ``` >>> from sortedcont...
How to calculate a packet checksum without sending it?
5,953,371
13
2011-05-10T16:37:30Z
6,067,275
9
2011-05-20T03:51:28Z
[ "python", "scapy" ]
I'm using scapy, and I want to create a packet and calculate its' checksum without sending it. Is there a way to do it? Thanks.
You need to delete the `.chksum` value from the packet after you create it; then call `.show2()` ``` >>> from scapy.layers.inet import IP >>> from scapy.layers.inet import ICMP >>> from scapy.layers.inet import TCP >>> target = "10.9.8.7" >>> ttl = 64 >>> id = 32711 >>> sport = 2927 >>> dport = 80 >>> pak = IP(dst=tar...
How to calculate a packet checksum without sending it?
5,953,371
13
2011-05-10T16:37:30Z
11,648,093
17
2012-07-25T10:51:27Z
[ "python", "scapy" ]
I'm using scapy, and I want to create a packet and calculate its' checksum without sending it. Is there a way to do it? Thanks.
I've also tried to avoid show2() because it print the packet. I've found in the source a better solution: ``` del packet.chksum packet = packet.__class__(str(packet)) ``` This code regenerate the packet with the correct checksum without any print and actually is what show2() run in the background before printing.
How to Split Image Into Multiple Pieces in Python
5,953,373
3
2011-05-10T16:37:33Z
7,051,075
8
2011-08-13T14:37:25Z
[ "python", "image", "split", "python-imaging-library", "crop" ]
I'm trying to split a photo into multiple pieces using PIL. ``` def crop(Path,input,height,width,i,k,x,y,page): im = Image.open(input) imgwidth = im.size[0] imgheight = im.size[1] for i in range(0,imgheight-height/2,height-2): print i for j in range(0,imgwidth-width/2,width-2): ...
``` from PIL import Image import Image def crop(Path,input,height,width,i,k,page,area): im = Image.open(input) imgwidth, imgheight = im.size for i in range(0,imgheight,height): for j in range(0,imgwidth,width): box = (j, i, j+width, i+height) a = im.crop(box) try...
Using a class' __new__ method as a Factory: __init__ gets called twice
5,953,759
24
2011-05-10T17:11:00Z
5,953,974
35
2011-05-10T17:29:54Z
[ "python", "design-patterns", "inheritance", "class-design" ]
I encountered a strange bug in python where using the `__new__` method of a class as a factory would lead to the `__init__` method of the instantiated class to be called twice. The idea was originally to use the `__new__` method of the mother class to return a specific instance of one of her children depending on the ...
When you construct an object Python calls its `__new__` method to create the object then calls `__init__` on the object that is returned. When you create the object from inside `__new__` by calling `Triangle()` that will result in further calls to `__new__` and `__init__`. What you should do is: ``` class Shape(objec...
Using a class' __new__ method as a Factory: __init__ gets called twice
5,953,759
24
2011-05-10T17:11:00Z
5,961,102
7
2011-05-11T08:07:05Z
[ "python", "design-patterns", "inheritance", "class-design" ]
I encountered a strange bug in python where using the `__new__` method of a class as a factory would lead to the `__init__` method of the instantiated class to be called twice. The idea was originally to use the `__new__` method of the mother class to return a specific instance of one of her children depending on the ...
After posting my question, I continued searching for a solution an found a way to solve the problem that looks like a bit of a hack. It is inferior to Duncan's solution, but I thought it could be interesting to mention none the less. The `Shape`class becomes: ``` class ShapeFactory(type): def __call__(cls, desc): ...
Default substituting %s in python scripts
5,954,260
7
2011-05-10T17:54:58Z
5,954,279
8
2011-05-10T17:57:13Z
[ "python", "string", "substitution" ]
Sometimes in Python scripts I see lines like: ``` cmd = "%s/%s_tb -cm cond+line+fsm -ucli -do \"%s\"" ``` Where is the `%s` in the above line substituted? Does Python have some stack of strings and it pops them and replaces `%s`?
**Basics of python string formatting** Not a specific answer to your line of code, but since you said you're new to python I thought I'd use this as an example to share some joy ;) Simple Example Inline With a List: ``` >>> print '%s %s %s'%('python','is','fun') python is fun ``` Simple Example Using a Dictionary: ...
Default substituting %s in python scripts
5,954,260
7
2011-05-10T17:54:58Z
5,954,306
12
2011-05-10T17:58:51Z
[ "python", "string", "substitution" ]
Sometimes in Python scripts I see lines like: ``` cmd = "%s/%s_tb -cm cond+line+fsm -ucli -do \"%s\"" ``` Where is the `%s` in the above line substituted? Does Python have some stack of strings and it pops them and replaces `%s`?
That would be later used in something like: ``` print cmd % ('foo','boo','bar') ``` What you're seeing is just a string assignment with fields in it which will later be filled in.
Default substituting %s in python scripts
5,954,260
7
2011-05-10T17:54:58Z
5,954,355
7
2011-05-10T18:03:02Z
[ "python", "string", "substitution" ]
Sometimes in Python scripts I see lines like: ``` cmd = "%s/%s_tb -cm cond+line+fsm -ucli -do \"%s\"" ``` Where is the `%s` in the above line substituted? Does Python have some stack of strings and it pops them and replaces `%s`?
It's being used for string interpolation. The `%s` is replaced by a string. You use the modulo operator (`%`) to do string interpolation. The string will be on the left side, the values to substitute for the various `%s` are on the right, in a tuple. ``` >>> s = '%s and %s' >>> s % ('cats', 'dogs' ) <<< 'cats and dog...
Transposing a NumPy array
5,954,603
63
2011-05-10T18:24:30Z
5,954,747
93
2011-05-10T18:36:43Z
[ "python", "numpy", "transpose" ]
I use Python and NumPy and have some problems with "transpose": ``` a=array([5,4]) print a print a.T ``` Invoking `a.T` is not transposing the array. If `a` is for example `[[],[]]` then it transposes correctly, but I need the transpose of `[...,...,...]`.
It's working exactly as it's supposed to. The transpose of a *1D* array is still a *1D* array! (If you're used to matlab, it fundamentally doesn't have a concept of a 1D array. Matlab's "1D" arrays are 2D.) If you want to turn your 1D vector into a 2D array and then transpose it, just slice it with `np.newaxis` (or `N...
Transposing a NumPy array
5,954,603
63
2011-05-10T18:24:30Z
10,546,291
44
2012-05-11T06:12:55Z
[ "python", "numpy", "transpose" ]
I use Python and NumPy and have some problems with "transpose": ``` a=array([5,4]) print a print a.T ``` Invoking `a.T` is not transposing the array. If `a` is for example `[[],[]]` then it transposes correctly, but I need the transpose of `[...,...,...]`.
Use two bracket pairs instead of one. This creates a 2D array, which can be transposed, unlike the 1D array you create if you use one bracket pair. ``` import numpy as np a = np.array([[5, 4]]) a.T ``` More thorough example: ``` >>> a = [3,6,9] >>> b = np.array(a) >>> b.T array([3, 6, 9]) #Here it didn't...
Transposing a NumPy array
5,954,603
63
2011-05-10T18:24:30Z
14,845,814
11
2013-02-13T03:13:49Z
[ "python", "numpy", "transpose" ]
I use Python and NumPy and have some problems with "transpose": ``` a=array([5,4]) print a print a.T ``` Invoking `a.T` is not transposing the array. If `a` is for example `[[],[]]` then it transposes correctly, but I need the transpose of `[...,...,...]`.
You can convert an existing vector into a matrix by wrapping it in an extra set of square brackets... ``` from numpy import * v=array([5,4]) ## create a numpy vector array([v]).T ## transpose a vector into a matrix ``` numpy also has a [`matrix`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html) ...
In Python difference in __dict__ between object() and class myClass(object)
5,954,717
10
2011-05-10T18:34:08Z
5,954,902
8
2011-05-10T18:51:47Z
[ "python" ]
I was messing around with dynamic attributes and I noticed I could not use the \_\_dict\_\_ attribute if I created the object directly from the object() class but if I create a new class that is a direct descendent of object I can access the \_\_dict\_\_ attribute. Why the difference? Examples: > ``` > # This gives a...
`object` is implemented in C and doesn't have a `__dict__` attribute. (Not all Python objects have it either; look up [`__slots__`](http://docs.python.org/reference/datamodel.html?highlight=__slots__#slots)).
Python error: list indices must be integers, not unicode
5,955,516
4
2011-05-10T19:38:31Z
5,955,558
10
2011-05-10T19:42:19Z
[ "python", "file-io", "tkinter" ]
there is my problem: i'm trying to get all numbers from a Tkinter's text widget(get's the text from a file) this way: ``` text = self.text_field.get(1.0, 'end') s = re.findall("\d+", text) ``` ***s*** returns something like this: ``` [u'0', u'15', u'320', u'235', u'1', u'1', u'150', u'50', u'2', u'2', u'20'] ```...
In Python when you do ``` for x in L: ... ``` inside the body loop `x` is already the list element, not the index. In your case the correction needed is simply to use `% i` instead of `% s[i]`. If in other cases you need both the list element and the index number the common Python idiom is: ``` for index, elem...
Using git to manage virtualenv state: will this cause problems?
5,955,690
17
2011-05-10T19:54:39Z
6,012,590
8
2011-05-16T02:00:38Z
[ "python", "git", "virtualenv" ]
I currently have git and virtualenv set up in a way which exactly suits my needs and, so far, hasn't caused any problems. However I'm aware that my setup is non-standard and I'm wondering if anyone more familiar with virtualenv's internals can point out if, and where, it's likely to go wrong. ### My setup My virtuale...
This is an interesting question. I think the other two answers (thus far) raise good specific points. Clearly you've thought this through and have arrived at a solution you like, but I'll note that there does seem to be a philosophical split here among virtualenv users. One camp, to which I'd guess you belong, feels t...
Python Matrix multiplication; numpy array
5,955,851
2
2011-05-10T20:10:18Z
5,961,915
7
2011-05-11T09:18:34Z
[ "python", "arrays", "matrix", "numpy" ]
I have some problem with matrix multiplication: I want to multiplicate for example a and b: ``` a=array([1,3]) # a is random and is array!!! (I have no impact on that) # there is a just for example what I want to do... b=[[[1], [2]], #b is ...
Your `b` seem to have an unnecessary dimension. With proper `b` you can just use `dot(.)`, like: ``` In []: a Out[]: array([1, 3]) In []: b Out[]: array([[1, 2], [3, 2], [4, 6], [2, 3]]) In []: dot(b, a).reshape((2, -1)) Out[]: array([[ 7, 9], [22, 11]]) ```
Cannot edit text in chart exported by Matplotlib and opened in Illustrator
5,956,182
11
2011-05-10T20:39:49Z
5,956,404
16
2011-05-10T20:58:17Z
[ "python", "pdf", "matplotlib", "adobe-illustrator", "eps" ]
I am exporting charts from matplotlib and editing them in Illustrator. It's great that I can edit the lines, but the text also comes in as lines, so I cannot change fonts, edit text, etc. I've exported as EPS, PDF, and PS with the same issues. I'm using matplotlib version 1.0.1 with python 2.7.1 on OSX Snow Leaopard. ...
You can edit the text in Acrobat/Illustrator if you set `pdf.fonttype` to 42 (TrueType), and export in pdf. You can set this in your `~/matplotlib/matplotlibrc`: ``` pdf.fonttype : 42 # Output Type 3 (Type3) or Type 42 (TrueType) ``` ..or dynamically: ``` >>> import matplotlib as mpl >>> mpl.rcParams['pdf.fonttype']...
Check if string is a real number
5,956,240
3
2011-05-10T20:44:09Z
5,956,295
12
2011-05-10T20:49:18Z
[ "python", "validation", "numbers" ]
Is there a quick way to find if a string is a real number, short of reading it a character at a time and doing `isdigit()` on each character? I want to be able to test floating point numbers, for example `0.03001`.
If you mean an float as a real number this should work: ``` def isfloat(str): try: float(str) except ValueError: return False return True ``` Note that this will internally still loop your string, but this is inevitable.
Check if string is a real number
5,956,240
3
2011-05-10T20:44:09Z
5,956,309
7
2011-05-10T20:50:17Z
[ "python", "validation", "numbers" ]
Is there a quick way to find if a string is a real number, short of reading it a character at a time and doing `isdigit()` on each character? I want to be able to test floating point numbers, for example `0.03001`.
``` >>> a = "12345" # good number >>> int(a) 12345 >>> b = "12345G" # bad number >>> int(b) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '12345G' ``` You can do that: ``` def isNumber(s): try: int(s) except ValueError: ...
Converting python datetime to timestamp and back in UTC still uses local timezone
5,956,638
8
2011-05-10T21:22:56Z
5,965,472
11
2011-05-11T13:59:56Z
[ "python", "datetime", "time", "pytz" ]
I'm working with a code that gives me utc timestamps and I want to convert them to appropriate datetimes. Unfortunately when I test simple cases with pytz the datetime has an added 6 hours (the CST offset to UTC). I need to keep timezone data correct because I am calculating difference between other timezones as well. ...
Hmm I found the answer here: [How to specify time zone (UTC) when converting to Unix time? (Python)](http://stackoverflow.com/questions/1077285/how-to-specify-time-zone-utc-when-converting-to-unix-time-python) ``` In [101]: ts = calendar.timegm(datetime(2010, 7, 1, tzinfo=pytz.utc).timetuple()) In [102]: datetime.fro...
Converting python datetime to timestamp and back in UTC still uses local timezone
5,956,638
8
2011-05-10T21:22:56Z
21,952,077
22
2014-02-22T08:57:51Z
[ "python", "datetime", "time", "pytz" ]
I'm working with a code that gives me utc timestamps and I want to convert them to appropriate datetimes. Unfortunately when I test simple cases with pytz the datetime has an added 6 hours (the CST offset to UTC). I need to keep timezone data correct because I am calculating difference between other timezones as well. ...
To get a naive datetime object that represents time in UTC from "seconds since the epoch" timestamp: ``` from datetime import datetime utc_dt = datetime.utcfromtimestamp(ts) ``` If you want to get an aware datetime object for UTC timezone: ``` import pytz aware_utc_dt = utc_dt.replace(tzinfo=pytz.utc) ``` To conv...
numpy float: 10x slower than builtin in arithmetic operations?
5,956,783
35
2011-05-10T21:37:47Z
5,957,076
18
2011-05-10T22:06:10Z
[ "python", "performance", "numpy", "floating-point" ]
**EDIT:** I rerun the code under the Windows 7 x64 (Intel Core i7 930 @ 3.8GHz). Again, the code is: ``` from datetime import datetime import numpy as np START_TIME = datetime.now() # one of the following lines is uncommented before execution #s = np.float64(1) #s = np.float32(1) #s = 1.0 for i in range(10000000)...
Operating with Python objects in a heavy loop like that, whether they are `float`, `np.float32`, is always slow. NumPy is fast for operations on vectors and matrices, because all of the operations are performed on big chunks of data by parts of the library written in C, and not by the Python interpreter. Code run in th...
numpy float: 10x slower than builtin in arithmetic operations?
5,956,783
35
2011-05-10T21:37:47Z
5,958,036
11
2011-05-11T00:49:15Z
[ "python", "performance", "numpy", "floating-point" ]
**EDIT:** I rerun the code under the Windows 7 x64 (Intel Core i7 930 @ 3.8GHz). Again, the code is: ``` from datetime import datetime import numpy as np START_TIME = datetime.now() # one of the following lines is uncommented before execution #s = np.float64(1) #s = np.float32(1) #s = 1.0 for i in range(10000000)...
Perhaps, that is why you should use Numpy directly instead of using loops. ``` s1 = np.ones(10000000, dtype=np.float) s2 = np.ones(10000000, dtype=np.float32) s3 = np.ones(10000000, dtype=np.float64) np.sum(s1) <-- 17.3 ms np.sum(s2) <-- 15.8 ms np.sum(s3) <-- 17.3 ms ```
numpy float: 10x slower than builtin in arithmetic operations?
5,956,783
35
2011-05-10T21:37:47Z
6,053,175
36
2011-05-19T02:33:59Z
[ "python", "performance", "numpy", "floating-point" ]
**EDIT:** I rerun the code under the Windows 7 x64 (Intel Core i7 930 @ 3.8GHz). Again, the code is: ``` from datetime import datetime import numpy as np START_TIME = datetime.now() # one of the following lines is uncommented before execution #s = np.float64(1) #s = np.float32(1) #s = 1.0 for i in range(10000000)...
**CPython floats are allocated in chunks** The key problem with comparing numpy scalar allocations to the `float` type is that CPython always allocates the memory for `float` and `int` objects in blocks of size N. Internally, CPython maintains a linked list of blocks each large enough to hold N `float` objects. When ...
numpy float: 10x slower than builtin in arithmetic operations?
5,956,783
35
2011-05-10T21:37:47Z
10,127,579
7
2012-04-12T16:17:03Z
[ "python", "performance", "numpy", "floating-point" ]
**EDIT:** I rerun the code under the Windows 7 x64 (Intel Core i7 930 @ 3.8GHz). Again, the code is: ``` from datetime import datetime import numpy as np START_TIME = datetime.now() # one of the following lines is uncommented before execution #s = np.float64(1) #s = np.float32(1) #s = 1.0 for i in range(10000000)...
**Summary** If an arithmetic expression contains both `numpy` and built-in numbers, Python arithmetics works slower. Avoiding this conversion removes almost all of the performance degradation I reported. **Details** Note that in my original code: ``` s = np.float64(1) for i in range(10000000): s = (s + 8) * s % 2...
numpy float: 10x slower than builtin in arithmetic operations?
5,956,783
35
2011-05-10T21:37:47Z
19,923,668
7
2013-11-12T07:50:27Z
[ "python", "performance", "numpy", "floating-point" ]
**EDIT:** I rerun the code under the Windows 7 x64 (Intel Core i7 930 @ 3.8GHz). Again, the code is: ``` from datetime import datetime import numpy as np START_TIME = datetime.now() # one of the following lines is uncommented before execution #s = np.float64(1) #s = np.float32(1) #s = 1.0 for i in range(10000000)...
The answer is quite simple: the memory allocation might be part of it, but the biggest problem is that arithmetic operations for numpy scalars is done using "ufuncs" which are meant to be fast for several hundred values not just 1. There is some overhead in choosing the correct function to call and setting up the loops...
Python list confusion
5,957,341
17
2011-05-10T22:42:53Z
5,957,379
13
2011-05-10T22:48:59Z
[ "python", "list" ]
Let's say I have the following code: ``` a_list = [[0]*10]*10 ``` This generates the following list: ``` [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, ...
Your hunch about copying addresses is correct. Think about it like this: ``` sub_list = [0] * 10 a_list = [sub_list] * 10 ``` This code is actually equivalent to the code you have posted above. What this means is that you are actually changing the same list `sub_list` whenever you change any element of `a_list`. You ...
Convert structured array to regular NumPy array
5,957,380
24
2011-05-10T22:49:00Z
5,957,555
19
2011-05-10T23:16:33Z
[ "python", "numpy", "recarray" ]
The answer will be very obvious I think, but I don't see it at the moment. **How can I convert a record array back to a regular ndarray?** Suppose I have following simple structured array: ``` x = np.array([(1.0, 4.0,), (2.0, -1.0)], dtype=[('f0', '<f8'), ('f1', '<f8')]) ``` then I want to convert it to: ``` array...
``` [~] |5> x = np.array([(1.0, 4.0,), (2.0, -1.0)], dtype=[('f0', '<f8'), ('f1', '<f8')]) [~] |6> x.view(np.float64).reshape(x.shape + (-1,)) array([[ 1., 4.], [ 2., -1.]]) ```
Convert structured array to regular NumPy array
5,957,380
24
2011-05-10T22:49:00Z
10,171,321
22
2012-04-16T09:05:07Z
[ "python", "numpy", "recarray" ]
The answer will be very obvious I think, but I don't see it at the moment. **How can I convert a record array back to a regular ndarray?** Suppose I have following simple structured array: ``` x = np.array([(1.0, 4.0,), (2.0, -1.0)], dtype=[('f0', '<f8'), ('f1', '<f8')]) ``` then I want to convert it to: ``` array...
The simplest method is probably ``` x.view((float, len(x.dtype.names))) ``` (`float` must generally be replaced by the type of the elements in `x`: `x.dtype[0]`). This assumes that all the elements have the same type. This method gives you the regular `numpy.ndarray` version in a single step (as opposed to the two s...
MATLAB-style find() function in Python
5,957,470
38
2011-05-10T23:02:43Z
5,957,742
54
2011-05-10T23:49:35Z
[ "python", "matlab", "find" ]
In MATLAB it is easy to find the indices of values that meet a particular condition: ``` >> a = [1,2,3,1,2,3,1,2,3]; >> find(a > 2) % find the indecies where this condition is true [3, 6, 9] % (MATLAB uses 1-based indexing) >> a(find(a > 2)) % get the values at those locations [3, 3, 3] ``` What would b...
in numpy you have `where` : ``` >> import numpy as np >> x = np.random.randint(0, 20, 10) >> x array([14, 13, 1, 15, 8, 0, 17, 11, 19, 13]) >> np.where(x > 10) (array([0, 1, 3, 6, 7, 8, 9], dtype=int64),) ```
MATLAB-style find() function in Python
5,957,470
38
2011-05-10T23:02:43Z
5,957,813
20
2011-05-11T00:03:19Z
[ "python", "matlab", "find" ]
In MATLAB it is easy to find the indices of values that meet a particular condition: ``` >> a = [1,2,3,1,2,3,1,2,3]; >> find(a > 2) % find the indecies where this condition is true [3, 6, 9] % (MATLAB uses 1-based indexing) >> a(find(a > 2)) % get the values at those locations [3, 3, 3] ``` What would b...
You can make a function that takes a callable parameter which will be used in the condition part of your list comprehension. Then you can use a [lambda](http://docs.python.org/tutorial/controlflow.html#lambda-forms) or other function object to pass your arbitrary condition: ``` def indices(a, func): return [i for ...
Python GPU programming
5,957,554
33
2011-05-10T23:16:29Z
5,957,647
20
2011-05-10T23:31:33Z
[ "python", "cuda", "gpu" ]
I am currently working on a project in python, and I would like to make use of the GPU for some calculations. At first glance it seems like there are many tools available; at second glance, I feel like im missing something. Copperhead looks awesome but has not yet been released. It would appear that im limited to wri...
[PyCUDA](http://mathema.tician.de/software/pycuda) provides very good integration with CUDA and has several helper interfaces to make writing CUDA code easier than in the straight C api. [Here](http://wiki.tiker.net/PyCuda/Examples/2DFFT) is an example from the Wiki which does a 2D FFT without needing any C code at all...
Why I can't convert a list of str to a list of floats?
5,958,136
6
2011-05-11T01:05:39Z
5,958,152
7
2011-05-11T01:10:18Z
[ "python", "string", "list", "csv", "floating-point" ]
I'm starting to write a code, but it fails at the beginning. **This is my code:** ``` import csv reader = csv.reader(open("QstartRefseqhg19.head"), dialect='excel-tab' ) for row in reader: C = row[1].split(",")[1:] C1 = [float(i) for i in C] print C1 ``` **and the error log says:** ``` Traceback (most...
Your input line is ended with a comma, e.g.: ``` 0,182,283,388,470,579,757, ``` So naturally, this will be split into: ``` ['0', '182', '283', '388', '470', '579', '757', ''] ``` The last element will always be an empty string, `''`. You'd need to account for this. One way is simply by ignoring it: ``` C1 = [float...
Is it safe to modify the output of globals()?
5,958,793
19
2011-05-11T03:07:49Z
5,958,992
19
2011-05-11T03:44:47Z
[ "python", "globals" ]
The [documentation for the locals() function](https://docs.python.org/2/library/functions.html#locals) specifically warns not to modify its output, as interpreters may not reflect changes in the local scope. I'm assuming that means the Python spec doesn't require it, even though it works in CPython. I'd like to know i...
Modifying `locals()` *doesn't* work reliably, even in CPython. It happens to work in module and class scopes, but it fails inside a function (any modifications "won't take", since `locals()` provides a copy of the local namespace in that case, rather than a reference to the real thing) However, `globals()` is differen...
What does INSTALLED_APPS setting in Django actually do?
5,958,882
8
2011-05-11T03:23:35Z
5,958,915
10
2011-05-11T03:29:30Z
[ "python", "django" ]
What does this *actually* do? I recently branched out my project from 1 app into 6 different apps and forgot to update the `INSTALLED_APPS` part of my settings file. Everything still works even though I didn't list the new apps in. Is that supposed to happen? Do I need to include all my apps in `INSTALLED_APPS`?
yes. INSTALLED\_APPS helps django to sync the database, run tests, get the urls to work and more related issues. Maybe your installed apps still works because the main one calls the others with imports, a django app is nothing more that a simple **python module** that is imported when called in the settings file, tha...
Uninstalling a python module in ubuntu
5,959,647
3
2011-05-11T05:25:56Z
5,959,706
8
2011-05-11T05:32:55Z
[ "python", "django", "uninstall" ]
I have to delete a python module named "django" (a popular one), because I installed the wrong version (1.3 - beta in py-2.6). How to uninstall this module? Please explain, because I've used python only in Windows and never in Ubuntu.
go to the python shell ``` >> import django ``` ``` django.__path__ ``` copy the path on the shell ``` sudo rm -r path ```
How to create abstract properties in python abstract classes
5,960,337
22
2011-05-11T06:49:24Z
5,960,468
24
2011-05-11T07:03:01Z
[ "python", "properties", "abstract-class", "decorator" ]
In the following code, I create a base abstract class `Base`. I want all the classes that inherit from `Base` to provide the `name` property, so I made this property an `@abstractmethod`. Then I created a subclass of `Base`, called `Base_1`, which is meant to supply some functionality, but still remain abstract. There...
Until [Python 3.3](https://docs.python.org/3/whatsnew/3.3.html#abc), you cannot nest `@abstractmethod` and `@property`. Use `@abstractproperty` to create abstract properties ([docs](http://docs.python.org/library/abc.html#abc.abstractproperty)). ``` from abc import ABCMeta, abstractmethod, abstractproperty class Bas...