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
Replace newlines in a Unicode string
2,201,633
11
2010-02-04T17:08:39Z
2,201,785
14
2010-02-04T17:28:33Z
[ "python", "google-app-engine", "unicode" ]
I am trying to replace newline characters in a unicode string and seem to be missing some magic codes. My particular example is that I am working on AppEngine and trying to put titles from HTML pages into a `db.StringProperty()` in my model. So I do something like: ``` link.title = unicode(page_title,"utf-8").replac...
Try `''.join(unicode(page_title, 'utf-8').splitlines())`. [`splitlines()`](http://docs.python.org/library/stdtypes.html#str.splitlines) should let the standard library take care of all the possible crazy Unicode line breaks, and then you just join them all back together with the empty string to get a single-line versio...
Replace newlines in a Unicode string
2,201,633
11
2010-02-04T17:08:39Z
2,202,029
8
2010-02-04T18:08:35Z
[ "python", "google-app-engine", "unicode" ]
I am trying to replace newline characters in a unicode string and seem to be missing some magic codes. My particular example is that I am working on AppEngine and trying to put titles from HTML pages into a `db.StringProperty()` in my model. So I do something like: ``` link.title = unicode(page_title,"utf-8").replac...
Python uses these characters for splitting in `unicode.splitlines()`: * U+000A LINE FEED (\n) * U+000D CARRIAGE RETURN (\r) * U+001C FILE SEPARATOR * U+001D GROUP SEPARATOR * U+001E RECORD SEPARATOR * U+0085 NEXT LINE * U+2028 LINE SEPARATOR * U+2029 PARAGRAPH SEPARATOR As Hank says, using `splitlines()` will let Pyt...
Creating custom Field Lookups in Django
2,203,179
11
2010-02-04T20:59:29Z
2,210,784
12
2010-02-05T22:04:29Z
[ "python", "django", "django-queryset" ]
How do you create custom [field lookups](http://docs.djangoproject.com/en/dev/topics/db/queries/#field-lookups) in Django? When filtering querysets, django provides a set of lookups that you can use: `__contains`, `__iexact`, `__in`, and so forth. I want to be able to provide a new lookup for my manager, so for instan...
A more flexible way to do this is to write a custom QuerySet as well as a custom manager. Working from ozan's code: ``` class PersonQuerySet(models.query.QuerySet): def in_age_range(self, min, max): return self.filter(age__gte=min, age__lt=max) class PersonManager(models.Manager): def get_query_set(se...
Python: How to retrieve class information from a 'frame' object?
2,203,424
10
2010-02-04T21:38:09Z
2,220,759
11
2010-02-08T10:07:51Z
[ "python", "introspection" ]
Is it possible to retrieve any class information from a frame object? I know how to get the file (frame.f\_code.co\_filename), function (frame.f\_code.co\_name) and line number (frame.f\_lineno), but would like to be able to also get the name of the class of the active object instance of the frame (or None if not in an...
I don't believe that, at the frame object level, there's any way to find the actual python function object that has been called. However, if your code rely on the common convention : naming the instance parameter of a method `self`, then you could do the following : ``` def get_class_from_frame(fr): import inspect ...
Python: How do you call a method when you only have the string name of the method?
2,203,438
9
2010-02-04T21:39:16Z
2,203,479
22
2010-02-04T21:46:08Z
[ "python", "json", "api", "serialization" ]
This is for use in a JSON API. I don't want to have: ``` if method_str == 'method_1': method_1() if method_str == 'method_2': method_2() ``` For obvious reasons this is not optimal. How would I use map strings to methods like this in a reusable way (also note that I need to pass in arguments to the called fu...
For methods of instances, use `getattr` ``` >>> class MyClass(object): ... def sayhello(self): ... print "Hello World!" ... >>> m=MyClass() >>> getattr(m,"sayhello")() Hello World! >>> ``` For functions you can look in the global dict ``` >>> def sayhello(): ... print "Hello World!" ... >>> globals().get("sayh...
Efficient way to convert numpy record array to a list of dictionary
2,203,673
7
2010-02-04T22:21:15Z
2,204,485
12
2010-02-05T01:26:43Z
[ "python", "numpy" ]
How do I convert the numpy record array below: ``` recs = [('Bill', 31, 260.0), ('Fred', 15, 145.0)] r = rec.fromrecords(recs, names='name, age, weight', formats='S30, i2, f4') ``` to a list of dictionary like: ``` [{'name': 'Bill', 'age': 31, 'weight': 260.0}, 'name': 'Fred', 'age': 15, 'weight': 145.0}] ```
I am not sure there is built-in function for that or not, but following could do the work. ``` >>> [dict(zip(r.dtype.names,x)) for x in r] [{'age': 31, 'name': 'Bill', 'weight': 260.0}, {'age': 15, 'name': 'Fred', 'weight': 145.0}] ```
Why am I getting an error about my class defining __slots__ when trying to pickle an object?
2,204,155
20
2010-02-05T00:00:58Z
2,204,702
20
2010-02-05T02:35:10Z
[ "python", "pickle", "slots" ]
I'm trying to pickle an object of a (new-style) class I defined. But I'm getting the following error: ``` >>> with open('temp/connection.pickle','w') as f: ... pickle.dump(c,f) ... Traceback (most recent call last): File "<stdin>", line 2, in <module> File "/usr/lib/python2.5/pickle.py", line 1362, in dump ...
The class defining [`__slots__`](https://docs.python.org/2/reference/datamodel.html#__slots__) (and not [`__getstate__`](https://docs.python.org/2/library/pickle.html#object.__getstate__)) can be either an ancestor class of yours, or a class (or ancestor class) of an attribute or item of yours, directly or indirectly: ...
PIP install a Python Package without a setup.py file?
2,204,811
12
2010-02-05T03:18:27Z
2,210,050
15
2010-02-05T20:04:15Z
[ "python", "setuptools", "easy-install", "pip" ]
I'm trying to figure out how I can install a python package that doesn't have a `setup.py` file with [pip](http://pip.openplans.org/). (package in question is <http://code.google.com/p/django-google-analytics/>) Normally I would just checkout the code from the repo and symlink into my site-packages, but I'm trying to ...
Fork the repo and add a working setup.py. Then send a pull request to the author. Oh, it's on Google Code. Well then, file a bug and post a patch. If the author refuses to make their code into an installable Python distribution (never happened to me), just host your fork somewhere and put that in your requirements fi...
Print string in a form of Unicode codes
2,206,210
3
2010-02-05T09:36:03Z
2,206,246
9
2010-02-05T09:41:03Z
[ "python", "string", "unicode" ]
How can I print a string as a sequence of unicode codes in Python? Input: `"если"` (in Russian). Output: `"\u0435\u0441\u043b\u0438"`
This should work: ``` >>> s = u'если' >>> print repr(s) u'\u0435\u0441\u043b\u0438' ```
Python - best way to set a column in a 2d array to a specific value
2,207,283
7
2010-02-05T12:56:32Z
2,207,315
10
2010-02-05T13:02:05Z
[ "python", "multidimensional-array" ]
I have a 2d array, I would like to set a column to a particular value, my code is below. Is this the best way in python? ``` rows = 5 cols = 10 data = (rows * cols) *[0] val = 10 set_col = 5 for row in range(rows): data[row * cols + set_col - 1] = val ``` If I want to set a number of columns to a particular val...
A better solution would be: ``` data = [[0] * cols for i in range(rows)] ``` For the values of `cols = 2`, `rows = 3` we'd get: ``` data = [[0, 0], [0, 0], [0, 0]] ``` Then you can access it as: ``` v = data[row][col] ``` Which leads to: ``` val = 10 set_col = 5 for row in range(rows): data[...
Python - best way to set a column in a 2d array to a specific value
2,207,283
7
2010-02-05T12:56:32Z
2,207,432
23
2010-02-05T13:24:51Z
[ "python", "multidimensional-array" ]
I have a 2d array, I would like to set a column to a particular value, my code is below. Is this the best way in python? ``` rows = 5 cols = 10 data = (rows * cols) *[0] val = 10 set_col = 5 for row in range(rows): data[row * cols + set_col - 1] = val ``` If I want to set a number of columns to a particular val...
[NumPy](http://numpy.scipy.org/) package provides powerful N-dimensional array object. If `data` is a `numpy` array then to set `set_col` column to `val` value: ``` data[:, set_col] = val ``` Complete Example: ``` >>> import numpy as np >>> a = np.arange(10) >>> a.shape = (5,2) >>> a array([[0, 1], [2, 3], ...
Detect 64bit OS (windows) in Python
2,208,828
26
2010-02-05T16:55:56Z
2,208,869
36
2010-02-05T17:01:15Z
[ "python", "windows", "64bit" ]
Does anyone know how I would go about detected what bit version Windows is under Python. I need to know this as a way of using the right folder for Program Files. Many thanks
I guess you should look in `os.environ['PROGRAMFILES']` for the program files folder.
Detect 64bit OS (windows) in Python
2,208,828
26
2010-02-05T16:55:56Z
2,209,083
17
2010-02-05T17:31:16Z
[ "python", "windows", "64bit" ]
Does anyone know how I would go about detected what bit version Windows is under Python. I need to know this as a way of using the right folder for Program Files. Many thanks
[`platform` module](http://docs.python.org/library/platform.html) -- Access to underlying platform’s identifying data ``` >>> import platform >>> platform.architecture() ('32bit', 'WindowsPE') ``` On 64-bit Windows, 32-bit Python returns: ``` ('32bit', 'WindowsPE') ``` And that means that **this answer, even thou...
Detect 64bit OS (windows) in Python
2,208,828
26
2010-02-05T16:55:56Z
5,838,022
24
2011-04-29T22:27:39Z
[ "python", "windows", "64bit" ]
Does anyone know how I would go about detected what bit version Windows is under Python. I need to know this as a way of using the right folder for Program Files. Many thanks
Came here searching for properly detecting if running on 64bit windows, compiling all the above into something more concise. Below you will find a function to test if running on 64bit windows, a function to get the 32bit Program Files folder, and a function to get the 64bit Program Files folder; all regardless of runn...
Detect 64bit OS (windows) in Python
2,208,828
26
2010-02-05T16:55:56Z
7,260,315
7
2011-08-31T16:32:26Z
[ "python", "windows", "64bit" ]
Does anyone know how I would go about detected what bit version Windows is under Python. I need to know this as a way of using the right folder for Program Files. Many thanks
``` def os_platform(): true_platform = os.environ['PROCESSOR_ARCHITECTURE'] try: true_platform = os.environ["PROCESSOR_ARCHITEW6432"] except KeyError: pass #true_platform not assigned to if this does not exist return true_platform ``` <http://blogs.msdn.com/b/david.w...
Detect 64bit OS (windows) in Python
2,208,828
26
2010-02-05T16:55:56Z
12,578,715
21
2012-09-25T08:08:36Z
[ "python", "windows", "64bit" ]
Does anyone know how I would go about detected what bit version Windows is under Python. I need to know this as a way of using the right folder for Program Files. Many thanks
I think the best solution to the problem has been posted by Mark Ribau. The best answer to the question for Python 2.7 and newer is: ``` def is_os_64bit(): return platform.machine().endswith('64') ``` On windows the cross-platform-function `platform.machine()` internally uses the environmental variables used in ...
Python != operation vs "is not"
2,209,755
99
2010-02-05T19:21:45Z
2,209,769
11
2010-02-05T19:23:02Z
[ "python", "operators" ]
In a comment on [this question](http://stackoverflow.com/questions/2079786/caching-sitemaps-in-django), I saw a statement that recommended using ``` result is not None ``` vs ``` result != None ``` I was wondering what the difference is, and why one might be recommended over the other?
`None` is a singleton, therefore identity comparison will always work, whereas an object can fake the equality comparison via `.__eq__()`.
Python != operation vs "is not"
2,209,755
99
2010-02-05T19:21:45Z
2,209,781
130
2010-02-05T19:25:05Z
[ "python", "operators" ]
In a comment on [this question](http://stackoverflow.com/questions/2079786/caching-sitemaps-in-django), I saw a statement that recommended using ``` result is not None ``` vs ``` result != None ``` I was wondering what the difference is, and why one might be recommended over the other?
`==` is an **equality test**. It checks whether the right hand side and the left hand side are equal objects (according to their `__eq__` or `__cmp__` methods.) `is` is an **identity test**. It checks whether the right hand side and the left hand side are the very same object. No methodcalls are done, objects can't in...
Python != operation vs "is not"
2,209,755
99
2010-02-05T19:21:45Z
2,210,044
15
2010-02-05T20:03:36Z
[ "python", "operators" ]
In a comment on [this question](http://stackoverflow.com/questions/2079786/caching-sitemaps-in-django), I saw a statement that recommended using ``` result is not None ``` vs ``` result != None ``` I was wondering what the difference is, and why one might be recommended over the other?
Consider the following: ``` class Bad(object): def __eq__(self, other): return True c = Bad() c is None # False, equivalent to id(c) == id(None) c == None # True, equivalent to c.__eq__(None) ```
Python != operation vs "is not"
2,209,755
99
2010-02-05T19:21:45Z
2,210,222
80
2010-02-05T20:32:49Z
[ "python", "operators" ]
In a comment on [this question](http://stackoverflow.com/questions/2079786/caching-sitemaps-in-django), I saw a statement that recommended using ``` result is not None ``` vs ``` result != None ``` I was wondering what the difference is, and why one might be recommended over the other?
First, let me go over a few terms. If you just want your question answered, scroll down to "Answering your question". ## Definitions **Object identity**: When you create an object, you can assign it to a variable. You can then also assign it to another variable. And another. ``` >>> button = Button() >>> cancel = bu...
Map List of Tuples into a Dictionary, python
2,210,581
4
2010-02-05T21:31:32Z
2,210,612
8
2010-02-05T21:35:51Z
[ "python", "list", "dictionary", "tuples" ]
I've got a list of tuples extracted from a table in a DB which looks like (*key* , *foreignkey* , *value*). There is a many to one relationship between the key and foreignkeys and I'd like to convert it into a dict indexed by the foreignkey containing the sum of all values with that foreignkey, i.e. { *foreignkey* , *s...
Assuming all your values are `int`s, you could use a `defaultdict` to make this easier: ``` from collections import defaultdict myDict = defaultdict(int) for item in myTupleList: myDict[item[1]] += item[2] ``` `defaultdict` is like a dictionary, except if you try to get a key that isn't there it fills in the va...
Python setuptools import error (Using NetBeans)
2,211,335
17
2010-02-06T00:02:08Z
2,211,348
28
2010-02-06T00:07:05Z
[ "python", "netbeans", "setuptools", "importerror" ]
I tried to find a question that would answer to this question but wasn't succesful, so I made a new question. I'm trying to compile my old Python Tic Tac Toe game in NetBeans, but I get the error message ``` ImportError: No module named setuptools ``` In my actual code I haven't imported a module named setuptools. A...
You need to install either [setuptools](http://pypi.python.org/pypi/setuptools) or [Distribute](http://pypi.python.org/pypi/distribute) in your Python instance. Follow the directions at either web page.
Method of Multiple Assignment in Python
2,211,822
8
2010-02-06T02:55:58Z
2,211,828
11
2010-02-06T02:59:13Z
[ "python", "syntax", "variable-assignment" ]
I'm trying to prepare for a future in computer science, so I started with ECMAScript and I am now trying to learn more about Python. Coming from ECMAScript, seeing multiple assignments such as `a, b, c = 1, 2, 3` leaves me bewildered for a moment, until I realize that there are multiple assignments going on. To make th...
It should not have any effect on performance. The parenthesis do not make it a tuple, the comma's do. So (1,2,3) is exactly the same as 1,2,3
Method of Multiple Assignment in Python
2,211,822
8
2010-02-06T02:55:58Z
2,211,925
13
2010-02-06T03:40:59Z
[ "python", "syntax", "variable-assignment" ]
I'm trying to prepare for a future in computer science, so I started with ECMAScript and I am now trying to learn more about Python. Coming from ECMAScript, seeing multiple assignments such as `a, b, c = 1, 2, 3` leaves me bewildered for a moment, until I realize that there are multiple assignments going on. To make th...
It's extremely easy to check, with the [`dis`](http://docs.python.org/library/dis.html?highlight=dis#module-dis) module: ``` >>> import dis >>> dis.dis(compile('a,b,c=1,2,3','','exec')) 1 0 LOAD_CONST 4 ((1, 2, 3)) 3 UNPACK_SEQUENCE 3 6 STORE_NAME ...
Python memory usage? loading large dictionaries in memory
2,211,965
22
2010-02-06T03:56:56Z
2,212,001
8
2010-02-06T04:06:47Z
[ "python", "memory" ]
hey all, I have a file on disk that's only 168MB. It's just a comma separated list of word,id the word can be 1-5 words long. There's 6.5 million lines. I created a dictionary in python to load this up into memory so I can search incoming text against that list of words. When python loads it up into memory it shows 1.3...
convert your data into a dbm (import anydbm, or use berkerley db by import bsddb ...), and then use dbm API to access it. the reason to explode is that python has extra meta information for any objects, and the dict needs to construct a hash table (which would require more memory). you just created so many objects (6....
Python memory usage? loading large dictionaries in memory
2,211,965
22
2010-02-06T03:56:56Z
2,212,005
16
2010-02-06T04:07:56Z
[ "python", "memory" ]
hey all, I have a file on disk that's only 168MB. It's just a comma separated list of word,id the word can be 1-5 words long. There's 6.5 million lines. I created a dictionary in python to load this up into memory so I can search incoming text against that list of words. When python loads it up into memory it shows 1.3...
Take a look (Python 2.6, 32-bit version)...: ``` >>> sys.getsizeof('word,1') 30 >>> sys.getsizeof(('word', '1')) 36 >>> sys.getsizeof(dict(word='1')) 140 ``` The string (taking 6 bytes on disk, clearly) gets an overhead of 24 bytes (no matter how long it is, add 24 to its length to find how much memory it takes). Whe...
Python memory usage? loading large dictionaries in memory
2,211,965
22
2010-02-06T03:56:56Z
2,212,006
24
2010-02-06T04:09:05Z
[ "python", "memory" ]
hey all, I have a file on disk that's only 168MB. It's just a comma separated list of word,id the word can be 1-5 words long. There's 6.5 million lines. I created a dictionary in python to load this up into memory so I can search incoming text against that list of words. When python loads it up into memory it shows 1.3...
Lots of ideas. However, if you want practical help, edit your question to show ALL of your code. Also tell us what is the "it" that shows memory used, what it shows when you load a file with zero entries, and what platform you are on, and what version of Python. You say that "the word can be 1-5 words long". What is t...
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
38
2010-02-06T04:04:50Z
2,212,090
20
2010-02-06T04:41:42Z
[ "python", "generator", "primes" ]
This is not a homework, I am just curious. INFINITE is the key word here. I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell. So, the answer cannot be as naive as "Just do a Sieve". First of all, you do not know how many consecutive primes will be consumed. Well, suppose yo...
I still like what I wrote up [here](http://macdevcenter.com/pub/a/python/excerpt/pythonckbk_chap1/index1.html?page=2) (a Cookbook recipe with many other authors) -- it shows how a Sieve of Eratosthenes has no intrinsic limits, and the comments and discussion, I believe, make it quite clear. This was recently discussed ...
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
38
2010-02-06T04:04:50Z
3,796,442
57
2010-09-26T03:01:48Z
[ "python", "generator", "primes" ]
This is not a homework, I am just curious. INFINITE is the key word here. I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell. So, the answer cannot be as naive as "Just do a Sieve". First of all, you do not know how many consecutive primes will be consumed. Well, suppose yo...
# “If I have seen further…” The `erat2` function from the cookbook can be further sped up (by about 20-25%): ## erat2a ``` import itertools as it def erat2a( ): D = { } yield 2 for q in it.islice(it.count(3), 0, None, 2): p = D.pop(q, None) if p is None: D[q*q] = q ...
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
38
2010-02-06T04:04:50Z
10,733,621
40
2012-05-24T08:16:32Z
[ "python", "generator", "primes" ]
This is not a homework, I am just curious. INFINITE is the key word here. I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell. So, the answer cannot be as naive as "Just do a Sieve". First of all, you do not know how many consecutive primes will be consumed. Well, suppose yo...
Since the OP asks for an *efficient* implementation, here's a significant improvement to the [active state 2002 code](http://code.activestate.com/recipes/117119-sieve-of-eratosthenes/) by David Eppstein/Alex Martelli (seen here in [his answer](http://stackoverflow.com/a/2212090/849891)): **don't record a prime's info i...
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
38
2010-02-06T04:04:50Z
19,391,111
17
2013-10-15T21:08:31Z
[ "python", "generator", "primes" ]
This is not a homework, I am just curious. INFINITE is the key word here. I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell. So, the answer cannot be as naive as "Just do a Sieve". First of all, you do not know how many consecutive primes will be consumed. Well, suppose yo...
For posterity, here's a rewrite of Will Ness's beautiful algorithm for Python 3. Some changes are needed (iterators no longer have `.next()` methods, but there's a new `next()` builtin function). Other changes are for fun (using the new `yield from <iterable>` replaces four `yield` statements in the original. More are ...
Counting the Number of keywords in a dictionary in python
2,212,433
67
2010-02-06T07:37:39Z
2,212,437
10
2010-02-06T07:40:01Z
[ "python", "dictionary", "count", "keyword" ]
I have a list of words in a dictionary with the value = the repetition of the keyword but I only want a list of distinct words so i wanted to count the number of keywords. Is there a to count the number of keywords or is there another way I should look for distinct words?
The number of distinct words (i.e. count of entries in the dictionary) can be found using the `len()` function. ``` > a = {'foo':42, 'bar':69} > len(a) 2 ``` To get all the distinct words (i.e. the keys), use the `.keys()` method. ``` > list(a.keys()) ['foo', 'bar'] ```
Counting the Number of keywords in a dictionary in python
2,212,433
67
2010-02-06T07:37:39Z
2,212,442
134
2010-02-06T07:41:38Z
[ "python", "dictionary", "count", "keyword" ]
I have a list of words in a dictionary with the value = the repetition of the keyword but I only want a list of distinct words so i wanted to count the number of keywords. Is there a to count the number of keywords or is there another way I should look for distinct words?
``` len(yourdict.keys()) ``` or just ``` len(yourdict) ``` If you like to count unique words in the file, you could just use [`set`](http://docs.python.org/library/sets.html#module-sets) and do like ``` len(set(open(yourdictfile).read().split())) ```
Python recursive folder read
2,212,643
80
2010-02-06T09:24:39Z
2,212,698
164
2010-02-06T09:48:17Z
[ "python", "scripting", "file-io" ]
I have a C++/Obj-C background and I am just discovering Python (been writing it for about an hour). I am writing a script to recursively read the contents of text files in a folder structure. The problem I have is the code I have written will only work for one folder deep. I can see why in the code (see `#hardcoded pa...
Make sure you understand the three return values of `os.walk`: ``` for root, subdirs, files in os.walk(rootdir): ``` has the following meaning: * `root`: Current path which is "walked through" * `subdirs`: Files in `root` of type directory * `files`: Files in `root` (not in `subdirs`) of type other than directory A...
Python recursive folder read
2,212,643
80
2010-02-06T09:24:39Z
2,212,728
13
2010-02-06T09:59:58Z
[ "python", "scripting", "file-io" ]
I have a C++/Obj-C background and I am just discovering Python (been writing it for about an hour). I am writing a script to recursively read the contents of text files in a folder structure. The problem I have is the code I have written will only work for one folder deep. I can see why in the code (see `#hardcoded pa...
Agree with Dave Webb, `os.walk` will yield an item for each directory in the tree. Fact is, you just don't have to care about `subFolders`. Code like this should work: ``` import os import sys rootdir = sys.argv[1] for folder, subs, files in os.walk(rootdir): with open(os.path.join(folder, 'python-outfile.txt')...
Python: Why is IDLE so slow?
2,212,722
16
2010-02-06T09:58:20Z
2,212,812
27
2010-02-06T10:33:07Z
[ "python", "performance", "python-idle" ]
[IDLE](http://en.wikipedia.org/wiki/IDLE_%28Python%29) is my favorite Python editor. It offers very nice and intuitive Python shell which is extremely useful for unit-testing and debugging, and a neat debugger. **However, code executed under IDLE is insanely slow. By insanely I mean *3 orders of magnitude* slow:** ##...
The problem is the text output not the debugger. I just tried it on my Q6600 (3GHz overclocked) System and my numbers are even worse. But its easy to see that they are going down the more output text is added. I tried to run it with 1000 iterations => 7,8 sec 2000 iterations => 28,5 sec 3000 iterations => 70 sec I ...
Python: Why is IDLE so slow?
2,212,722
16
2010-02-06T09:58:20Z
2,213,321
8
2010-02-06T13:59:13Z
[ "python", "performance", "python-idle" ]
[IDLE](http://en.wikipedia.org/wiki/IDLE_%28Python%29) is my favorite Python editor. It offers very nice and intuitive Python shell which is extremely useful for unit-testing and debugging, and a neat debugger. **However, code executed under IDLE is insanely slow. By insanely I mean *3 orders of magnitude* slow:** ##...
The problem is in the Tkinter Text widget, and its inefficient management of very long lines, and you create one. You'll notice that, while any part of a very long line is visible, all scrolling is devilishly slow.
What is a nicer alternative to a namedtuples _replace?
2,213,102
5
2010-02-06T12:40:47Z
2,213,108
16
2010-02-06T12:43:21Z
[ "python", "namedtuple" ]
Take this code: ``` >>> import urlparse >>> parts = urlparse.urlparse('http://docs.python.org/library/') >>> parts = parts._replace(path='/3.0'+parts.path) ``` `parts._replace works` but as it is an underscored method, it's supposed to be internal, and not used. Is there an alternative? I don't want to do: ``` >>> p...
The reason methods of `namedtuple` start with an initial underscore is only to prevent name collisions. They [should not be considered to be for internal use only](http://docs.python.org/library/collections.html#collections.namedtuple): > To prevent conflicts with field names, the method and attribute names start with...
Why can't I do a hyphen in Django template view?
2,213,308
3
2010-02-06T13:53:22Z
2,213,330
7
2010-02-06T14:03:19Z
[ "python", "django", "templates" ]
``` {{profile.first-name.value}} ``` My variable is hypeh only...I wish I could do **first\_name**, but many variables are hyphens. However, due to this problem, I can't display my variables in the template. Why?
The hyphen is an operator in Python. It would work better if you swapped all hyphens for underscores.
Django model class methods for predefined values
2,213,309
12
2010-02-06T13:53:34Z
2,213,341
26
2010-02-06T14:09:12Z
[ "python", "django", "django-models" ]
I'm working on some Django-code that has a model like this: ``` class Status(models.Model): code = models.IntegerField() text = models.CharField(maxlength=255) ``` There are about 10 pre-defined code/text-pairs that are stored in the database. Scattered around the codebase I see code like this: ``` status = ...
You should perhaps implement this by defining a custom manager for your class, and adding two manager methods on that manager (which I believe is the preferred way for adding table-level functionality for any model). However, another way of doing it is by throwing in two [class methods](http://docs.python.org/library/f...
In Python, I have a dictionary. How do I change the keys of this dictionary?
2,213,334
19
2010-02-06T14:04:55Z
2,213,349
28
2010-02-06T14:11:13Z
[ "python", "dictionary" ]
Let's say I have a pretty complex dictionary. ``` {'fruit':'orange','colors':{'dark':4,'light':5}} ``` Anyway, my objective is to **scan every key** in this complex multi-level dictionary. Then, append "abc" to the end of each key. So that it will be: ``` {'fruitabc':'orange','colorsabc':{'darkabc':4,'lightabc':5}}...
Keys cannot be changed. You will need to add a new key with the modified value then remove the old one, or create a new dict with a dict comprehension or the like.
In Python, I have a dictionary. How do I change the keys of this dictionary?
2,213,334
19
2010-02-06T14:04:55Z
2,213,368
12
2010-02-06T14:17:38Z
[ "python", "dictionary" ]
Let's say I have a pretty complex dictionary. ``` {'fruit':'orange','colors':{'dark':4,'light':5}} ``` Anyway, my objective is to **scan every key** in this complex multi-level dictionary. Then, append "abc" to the end of each key. So that it will be: ``` {'fruitabc':'orange','colorsabc':{'darkabc':4,'lightabc':5}}...
For example like this: ``` def appendabc(somedict): return dict(map(lambda (key, value): (str(key)+"abc", value), somedict.items())) def transform(multilevelDict): new = appendabc(multilevelDict) for key, value in new.items(): if isinstance(value, dict): new[key] = transform(value) ...
In Python, I have a dictionary. How do I change the keys of this dictionary?
2,213,334
19
2010-02-06T14:04:55Z
2,213,378
7
2010-02-06T14:19:43Z
[ "python", "dictionary" ]
Let's say I have a pretty complex dictionary. ``` {'fruit':'orange','colors':{'dark':4,'light':5}} ``` Anyway, my objective is to **scan every key** in this complex multi-level dictionary. Then, append "abc" to the end of each key. So that it will be: ``` {'fruitabc':'orange','colorsabc':{'darkabc':4,'lightabc':5}}...
``` >>> mydict={'fruit':'orange','colors':{'dark':4,'light':5}} >>> def f(mydict): ... return dict((k+"abc",f(v) if hasattr(v,'keys') else v) for k,v in mydict.items()) ... >>> f(mydict) {'fruitabc': 'orange', 'colorsabc': {'darkabc': 4, 'lightabc': 5}} ```
What's the pythonic way of declaring variables?
2,213,531
10
2010-02-06T15:09:32Z
2,213,535
9
2010-02-06T15:10:49Z
[ "python" ]
Usually declaring variables on assignment is considered a best practice in VBScript or JavaScript , for example, although it is allowed. Why does Python force you to create the variable only when you use it? Since Python is case sensitive can't it cause bugs because you misspelled a variable's name? How would you avo...
In python it helps to think of declaring variables as binding values to names. Try not to misspell them, or you will have new ones (assuming you are talking about assignment statements - referencing them will cause an exception). If you are talking about instance variables, you won't be able to use them afterwards. ...
What's the pythonic way of declaring variables?
2,213,531
10
2010-02-06T15:09:32Z
2,213,663
15
2010-02-06T15:48:42Z
[ "python" ]
Usually declaring variables on assignment is considered a best practice in VBScript or JavaScript , for example, although it is allowed. Why does Python force you to create the variable only when you use it? Since Python is case sensitive can't it cause bugs because you misspelled a variable's name? How would you avo...
It's a silly artifact of Python's inspiration by "teaching languages", and it serves to make the language more accessible by removing the stumbling block of "declaration" entirely. For whatever reason (probably represented as "simplicity"), Python never gained an optional stricture like VB's "Option Explicit" to introd...
What's the pythonic way of declaring variables?
2,213,531
10
2010-02-06T15:09:32Z
2,213,963
12
2010-02-06T17:31:22Z
[ "python" ]
Usually declaring variables on assignment is considered a best practice in VBScript or JavaScript , for example, although it is allowed. Why does Python force you to create the variable only when you use it? Since Python is case sensitive can't it cause bugs because you misspelled a variable's name? How would you avo...
If you want a class with "locked-down" instance attributes, it's not hard to make one, e.g.: ``` class LockedDown(object): __locked = False def __setattr__(self, name, value): if self.__locked: if name[:2] != '__' and name not in self.__dict__: raise ValueError("Can't set attribute %r" % name) ...
Installing SciPy with pip
2,213,551
142
2010-02-06T15:13:55Z
2,214,018
83
2010-02-06T17:48:20Z
[ "python", "install", "scipy", "pip" ]
It is possible to install [NumPy](http://en.wikipedia.org/wiki/NumPy) with [pip](https://en.wikipedia.org/wiki/Pip_%28package_manager%29) using `pip install numpy`. Is there a similar possibility with [SciPy](http://en.wikipedia.org/wiki/SciPy)? (Doing `pip install scipy` does not work.) --- **Update** The package ...
An attempt to `easy_install` indicates a problem with their [listing](http://pypi.python.org/pypi/scipy/0.7.0) in the [Python Package Index](http://pypi.python.org/pypi), which pip searches. ``` easy_install scipy Searching for scipy Reading http://pypi.python.org/simple/scipy/ Reading http://www.scipy.org Reading htt...
Installing SciPy with pip
2,213,551
142
2010-02-06T15:13:55Z
3,625,365
11
2010-09-02T08:29:46Z
[ "python", "install", "scipy", "pip" ]
It is possible to install [NumPy](http://en.wikipedia.org/wiki/NumPy) with [pip](https://en.wikipedia.org/wiki/Pip_%28package_manager%29) using `pip install numpy`. Is there a similar possibility with [SciPy](http://en.wikipedia.org/wiki/SciPy)? (Doing `pip install scipy` does not work.) --- **Update** The package ...
If I first install BLAS, LAPACK and GCC Fortran as system packages (I'm using [Arch Linux](http://en.wikipedia.org/wiki/Arch_Linux)), I can get SciPy installed with: ``` pip install scipy ```
Installing SciPy with pip
2,213,551
142
2010-02-06T15:13:55Z
3,865,521
31
2010-10-05T16:05:34Z
[ "python", "install", "scipy", "pip" ]
It is possible to install [NumPy](http://en.wikipedia.org/wiki/NumPy) with [pip](https://en.wikipedia.org/wiki/Pip_%28package_manager%29) using `pip install numpy`. Is there a similar possibility with [SciPy](http://en.wikipedia.org/wiki/SciPy)? (Doing `pip install scipy` does not work.) --- **Update** The package ...
In Ubuntu 10.04 (Lucid), I could successfully `pip install scipy` (within a virtualenv) after installing some of its dependencies, in particular: ``` $ sudo apt-get install libamd2.2.0 libblas3gf libc6 libgcc1 libgfortran3 liblapack3gf libumfpack5.4.0 libstdc++6 build-essential gfortran libatlas-sse2-dev python-all-de...
Installing SciPy with pip
2,213,551
142
2010-02-06T15:13:55Z
15,355,787
174
2013-03-12T07:45:21Z
[ "python", "install", "scipy", "pip" ]
It is possible to install [NumPy](http://en.wikipedia.org/wiki/NumPy) with [pip](https://en.wikipedia.org/wiki/Pip_%28package_manager%29) using `pip install numpy`. Is there a similar possibility with [SciPy](http://en.wikipedia.org/wiki/SciPy)? (Doing `pip install scipy` does not work.) --- **Update** The package ...
*Prerequisite:* ``` sudo apt-get install build-essential gfortran libatlas-base-dev python-pip python-dev sudo pip install --upgrade pip ``` *Actual packages:* ``` sudo pip install numpy sudo pip install scipy ``` *Optional packages:* ``` sudo pip install matplotlib OR sudo apt-get install python-matplotlib sud...
Installing SciPy with pip
2,213,551
142
2010-02-06T15:13:55Z
22,493,784
11
2014-03-19T00:17:56Z
[ "python", "install", "scipy", "pip" ]
It is possible to install [NumPy](http://en.wikipedia.org/wiki/NumPy) with [pip](https://en.wikipedia.org/wiki/Pip_%28package_manager%29) using `pip install numpy`. Is there a similar possibility with [SciPy](http://en.wikipedia.org/wiki/SciPy)? (Doing `pip install scipy` does not work.) --- **Update** The package ...
I tried all the above and nothing worked for me. This solved all my problems: ``` pip install -U numpy pip install -U scipy ``` Note that the `-U` option to `pip install` requests that the package be *upgraded*. Without it, if the package is already installed `pip` will inform you of this and exit without doing anyt...
Installing SciPy with pip
2,213,551
142
2010-02-06T15:13:55Z
22,633,734
7
2014-03-25T11:50:57Z
[ "python", "install", "scipy", "pip" ]
It is possible to install [NumPy](http://en.wikipedia.org/wiki/NumPy) with [pip](https://en.wikipedia.org/wiki/Pip_%28package_manager%29) using `pip install numpy`. Is there a similar possibility with [SciPy](http://en.wikipedia.org/wiki/SciPy)? (Doing `pip install scipy` does not work.) --- **Update** The package ...
For the Arch Linux users: `pip install --user scipy` prerequisites the following Arch packages to be installed: * `gcc-fortran` * `blas` * `lapack`
Installing SciPy with pip
2,213,551
142
2010-02-06T15:13:55Z
28,116,352
12
2015-01-23T18:26:22Z
[ "python", "install", "scipy", "pip" ]
It is possible to install [NumPy](http://en.wikipedia.org/wiki/NumPy) with [pip](https://en.wikipedia.org/wiki/Pip_%28package_manager%29) using `pip install numpy`. Is there a similar possibility with [SciPy](http://en.wikipedia.org/wiki/SciPy)? (Doing `pip install scipy` does not work.) --- **Update** The package ...
On Fedora, this works: ``` sudo yum install -y python-pip sudo yum install -y lapack lapack-devel blas blas-devel sudo yum install -y blas-static lapack-static sudo pip install numpy sudo pip install scipy ``` If you get any `public key` errors while downloading, add `--nogpgcheck` as parameter to `yum`, for example...
Installing SciPy with pip
2,213,551
142
2010-02-06T15:13:55Z
34,220,168
7
2015-12-11T09:32:22Z
[ "python", "install", "scipy", "pip" ]
It is possible to install [NumPy](http://en.wikipedia.org/wiki/NumPy) with [pip](https://en.wikipedia.org/wiki/Pip_%28package_manager%29) using `pip install numpy`. Is there a similar possibility with [SciPy](http://en.wikipedia.org/wiki/SciPy)? (Doing `pip install scipy` does not work.) --- **Update** The package ...
To install scipy on windows follow these instructions:- Step-1 : Press this link <http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy> to download a scipy .whl file (e.g. scipy-0.17.0-cp34-none-win\_amd64.whl). Step-2: Go to the directory where that download file is there from the command prompt (cd folder-name ). Step...
Changing the hour with datetime.replace() in python
2,213,682
14
2010-02-06T15:57:11Z
2,213,710
23
2010-02-06T16:08:46Z
[ "python", "osx", "datetime" ]
Given that foo is a valid datetime object in python, One can change the hour represented in a datestamp (foo) by doing something something like: ``` foo2 = foo.replace( hour=5 ) ``` Rather then replacing the hour with a particular value ( as is done above )..is it possible to increment the time in foo by say, 5 hour...
That's what `timedelta` is for: ``` >>> import datetime >>> d = datetime.datetime(2010, 12, 25, 18, 25) >>> d + datetime.timedelta(hours = 8) datetime.datetime(2010, 12, 26, 2, 25) ```
Python: removing duplicates from a list of lists
2,213,923
59
2010-02-06T17:17:46Z
2,213,935
12
2010-02-06T17:21:34Z
[ "python" ]
I have a list of lists in Python: ``` k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]] ``` And I want to remove duplicate elements from it. Was if it a normal list not of lists I could used `set`. But unfortunate that list is not hashable and can't make set of lists. Only of tuples. So I can turn all lists to tuples th...
``` >>> k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]] >>> k = sorted(k) >>> k [[1, 2], [1, 2], [3], [4], [4], [5, 6, 2]] >>> dedup = [k[i] for i in range(len(k)) if i == 0 or k[i] != k[i-1]] >>> dedup [[1, 2], [3], [4], [5, 6, 2]] ``` I don't know if it's necessarily faster, but you don't have to use to tuples and se...
Python: removing duplicates from a list of lists
2,213,923
59
2010-02-06T17:17:46Z
2,213,973
85
2010-02-06T17:33:57Z
[ "python" ]
I have a list of lists in Python: ``` k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]] ``` And I want to remove duplicate elements from it. Was if it a normal list not of lists I could used `set`. But unfortunate that list is not hashable and can't make set of lists. Only of tuples. So I can turn all lists to tuples th...
``` >>> k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]] >>> import itertools >>> k.sort() >>> list(k for k,_ in itertools.groupby(k)) [[1, 2], [3], [4], [5, 6, 2]] ``` [`itertools`](http://docs.python.org/library/itertools.html?highlight=itertools#module-itertools) often offers the fastest and most powerful solutions t...
Is everything greater than None?
2,214,194
50
2010-02-06T18:32:17Z
2,214,223
59
2010-02-06T18:38:29Z
[ "python", "python-3.x", "python-datamodel" ]
Is there a Python built-in datatype, **besides `None`**, for which: ``` >>> not foo > None True ``` where `foo` is a value of that type? How about Python 3?
`None` is always less than any datatype in Python 2 (see [`object.c`](http://hg.python.org/cpython/file/ab05e7dd2788/Objects/object.c#l778)). In Python 3, this was changed; now doing comparisons on things without a sensible natural ordering results in a `TypeError`. From the **[3.0 "what's new" updates](https://docs.p...
Is everything greater than None?
2,214,194
50
2010-02-06T18:32:17Z
2,214,230
23
2010-02-06T18:40:12Z
[ "python", "python-3.x", "python-datamodel" ]
Is there a Python built-in datatype, **besides `None`**, for which: ``` >>> not foo > None True ``` where `foo` is a value of that type? How about Python 3?
From the Python **2.7.5** source ([`object.c`](http://hg.python.org/cpython/file/ab05e7dd2788/Objects/object.c#l778)): ``` static int default_3way_compare(PyObject *v, PyObject *w) { ... /* None is smaller than anything */ if (v == Py_None) return -1; if (w == Py_None) return 1;...
Efficient Python array with 100 million zeros?
2,214,651
18
2010-02-06T20:46:40Z
2,214,771
25
2010-02-06T21:17:34Z
[ "python", "arrays", "performance" ]
What is an efficient way to initialize and access elements of a large array in Python? I want to create an array in Python with 100 million entries, unsigned 4-byte integers, initialized to zero. I want fast array access, preferably with contiguous memory. Strangely, [NumPy](http://en.wikipedia.org/wiki/NumPy) arrays...
I have done some profiling, and the results are completely counterintuitive. For simple array access operations, **numpy and array.array are 10x slower than native Python arrays**. Note that for array access, I am doing operations of the form: ``` a[i] += 1 ``` Profiles: * [0] \* 20000000 + Access: 2.3M / sec ...
Efficient Python array with 100 million zeros?
2,214,651
18
2010-02-06T20:46:40Z
2,214,986
10
2010-02-06T22:26:07Z
[ "python", "arrays", "performance" ]
What is an efficient way to initialize and access elements of a large array in Python? I want to create an array in Python with 100 million entries, unsigned 4-byte integers, initialized to zero. I want fast array access, preferably with contiguous memory. Strangely, [NumPy](http://en.wikipedia.org/wiki/NumPy) arrays...
Just a reminder how Python's integers work: if you allocate a list by saying ``` a = [0] * K ``` you need the memory for the list (`sizeof(PyListObject) + K * sizeof(PyObject*)`) and the memory for the single integer object `0`. As long as the numbers in the list stay below the magic number `V` that Python uses for c...
Django: Can the value of ForeignKey be None?
2,214,909
4
2010-02-06T21:59:58Z
2,215,003
9
2010-02-06T22:35:43Z
[ "python", "database", "django", "foreign-keys" ]
I have a model called `SimplePage` in which I have this line: ``` category = models.ForeignKey('Category', related_name='items', blank=True, null=True) ``` I assumed this will allow me to have SimplePage instances that do not have a Category. But for some reason, when I try to create a S...
Could it possibly be that you added the `null=True` attribute after doing the `syncdb` for that model? Django won't change database tables, only create them. Check in your database if `NULL` is allowed for that column and change it manually. **Edit**: starting with Django 1.7, this answer and the comments are not real...
Difference Between Modulus Implementation in Python Vs Java
2,215,318
12
2010-02-07T00:16:41Z
2,215,331
7
2010-02-07T00:20:43Z
[ "java", "python", "modulo" ]
I've noticed differing implementations of the modulus operator in Python and Java. For example, in Python: ``` >>> print -300 % 800 >>> 500 ``` Whereas in Java: ``` System.out.println(-300 % 800); -300 ``` This caught me off guard, since I thought something as basic as modulus was universally interpreted the same ...
I prefer C's interpretation (also used in Python), where `%` is indeed a modulus operator. Good discussion in the [wikipedia page](http://en.wikipedia.org/wiki/Modulo_operation) and the links from it (including one bit about why taking instead the sign of the dividend can lead to one silly bug unless one's careful;-).
Placing nodes vertically in Graphviz using pydot
2,215,461
11
2010-02-07T01:06:03Z
2,215,870
10
2010-02-07T03:59:37Z
[ "python", "visualization", "graphviz", "pydot" ]
I am using Graphviz in Python via pydot. The diagram I am making has many clusters of directed graphs. pydot is putting them next to each other horizontally resulting in an image that is very wide. How can I tell it to output images of a maximum width so that I can scroll vertically instead?
There are several things you can do. 1. You can set the maximum size of your graph, using 'size' (e.g., size = "4, 8" (inches)). This fixes the size of your final layout. Unlike most other node,edge, and graph parameters in the dot language, 'size' has no default. Also, the default orientation is 'portrait', which i b...
Placing nodes vertically in Graphviz using pydot
2,215,461
11
2010-02-07T01:06:03Z
16,312,306
7
2013-05-01T03:26:41Z
[ "python", "visualization", "graphviz", "pydot" ]
I am using Graphviz in Python via pydot. The diagram I am making has many clusters of directed graphs. pydot is putting them next to each other horizontally resulting in an image that is very wide. How can I tell it to output images of a maximum width so that I can scroll vertically instead?
Initialize your graph like this: `graph = pydot.Dot(graph_type='digraph', rankdir='LR')` This will set the graph direction from left to right. In general, use the [graphviz documentation](http://www.graphviz.org/doc/info/attrs.html) to find the right attribute in order to achieve what you want.
Conditional output in Sphinx Documentation
2,215,518
16
2010-02-07T01:29:35Z
2,215,815
22
2010-02-07T03:37:11Z
[ "python", "documentation", "python-sphinx" ]
I'm writing some documentation with [Sphinx](http://sphinx.pocoo.org/) and I'd like to print out a certain block of text only for HTML documentation, not for LaTeX documentation. Something tells me I should be able to do this with `sphinx.ext.ifconfig` but I can't figure out how. Does anyone know how to do this?
No extension is required. Just use the [only directive](http://sphinx.pocoo.org/markup/misc.html?highlight=only#including-content-based-on-tags). It works like this: ``` .. only:: latex The stuff in here only appears in the latex output. .. only:: html The stuff in this block only appears in the HTML output...
Migrating off AppEngine
2,215,721
12
2010-02-07T02:59:58Z
2,215,741
9
2010-02-07T03:12:01Z
[ "python", "google-app-engine", "web-applications" ]
I have an application running on AppEngine that uses about 50 CPU hours a day. Most of it is spent waiting for the datastore. I am contemplating moving it off of AppEngine to something like Rackspace Cloud Servers because I think that my application can be more efficient if I can offload some of the work to the databa...
If you can redeploy to [appscale](http://code.google.com/p/appscale/), you won't have to rewrite any of your App Engine code.
Avoid specifying all arguments in a subclass
2,215,923
12
2010-02-07T04:24:43Z
2,216,157
13
2010-02-07T06:20:57Z
[ "python", "constructor", "arguments", "subclass" ]
I have a class: ``` class A(object): def __init__(self,a,b,c,d,e,f,g,...........,x,y,z) #do some init stuff ``` And I have a subclass which needs one extra arg (the last `W`) ``` class B(A): def __init__(self.a,b,c,d,e,f,g,...........,x,y,z,W) A.__init__(self,a,b,c,d,e,f,g,...........,x,y,z) ...
Considering that arguments could be passed either by name or by position, I'd code: ``` class B(A): def __init__(self, *a, **k): if 'W' in k: w = k.pop('W') else: w = a.pop() A.__init__(self, *a, **k) self._W = w ```
gstreamer playbin - setting uri on windows
2,216,064
2
2010-02-07T05:33:15Z
2,216,842
9
2010-02-07T13:12:27Z
[ "python", "gstreamer" ]
I am trying to play some audio files with the CLI example on this site: <http://pygstdocs.berlios.de/pygst-tutorial/playbin.html> http://pygstdocs.berlios.de/pygst-tutorial/playbin.html I am on windows and it is giving error while reading the file. I specified the following path: ``` $ python cliplayer.py C:\\voice....
As you may have suspected, this code is rather badly written: ``` for filepath in sys.argv[1:]: # ... self.player.set_property("uri", "file://" + filepath) ``` Use something like this: ``` 'file:' + urllib.pathname2url(filepath) ``` and (in the command line) specify the file path in normal Windows notation,...
How to get path of Start Menu's Programs directory?
2,216,173
5
2010-02-07T06:26:03Z
2,216,217
9
2010-02-07T06:51:11Z
[ "python", "windows" ]
...for current user? for all users? I'm working an a small program which needs to create links in the start menu. Currently I'm hardcoding like below, but it only works in english locales, for example it should be "Startmenü" in german. What are cleaner, more portable approaches? ``` OUR_STARTMENU = os.environ['ALLU...
I've heard of 2 ways of doing this. First: ``` from win32com.shell import shell shell.SHGetSpecialFolderPath(0,shellcon.CSIDL_COMMON_STARTMENU) ``` Second, using the WScript.Shell object (source : <http://www.mail-archive.com/python-win32@python.org/msg00992.html>): ``` import win32com.client objShell = win32com.cli...
How can I validate a date in Python 3.x?
2,216,250
16
2010-02-07T07:13:59Z
2,216,257
26
2010-02-07T07:17:23Z
[ "python", "validation", "date", "python-3.x" ]
I would like to have the user input a date, something like: ``` date = input('Date (m/dd/yyyy): ') ``` and then make sure that the input is a valid date. I don't really care that much about the date format. Thanks for any input.
You can use the [`time` module's `strptime()`](http://docs.python.org/library/time.html#time.strptime) function: ``` import time date = input('Date (mm/dd/yyyy): ') try: valid_date = time.strptime(date, '%m/%d/%Y') except ValueError: print('Invalid date!') ``` Note that in Python 2.x you'll need to use `raw_input...
Adding values in a tuple that is in a list in python
2,216,450
3
2010-02-07T08:46:27Z
2,216,486
7
2010-02-07T09:04:53Z
[ "python", "list", "tuples" ]
I retrieve some data from a database which returns it in a list of tuple values such as this: [(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)] Is there a function that can sum up the values in the list of tuples? For example, the above sample should return 18...
``` >>>> l=[(1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)] >>> sum(map(sum,l)) 18 >>> l[0]=(1,2,3,) >>> l [(1, 2, 3), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,), (1,)] >>> sum(map(sum,l)) 23 ```
Django ModelForm for Many-to-Many fields
2,216,974
47
2010-02-07T13:59:48Z
2,232,307
11
2010-02-09T20:28:48Z
[ "python", "django", "django-forms" ]
Consider the following models and form: ``` class Pizza(models.Model): name = models.CharField(max_length=50) class Topping(models.Model): name = models.CharField(max_length=50) ison = models.ManyToManyField(Pizza, blank=True) class ToppingForm(forms.ModelForm): class Meta: model = Topping ``...
I'm not certain I get the question 100%, so I'm going to run with this assumption: Each `Pizza` can have many `Topping`s. Each `Topping` can have many `Pizza`s. But if a `Topping` is added to a `Pizza`, that `Topping` then automagically will have a `Pizza`, and vice versa. In this case, your best bet is a relationshi...
Django ModelForm for Many-to-Many fields
2,216,974
47
2010-02-07T13:59:48Z
2,264,722
85
2010-02-15T08:31:09Z
[ "python", "django", "django-forms" ]
Consider the following models and form: ``` class Pizza(models.Model): name = models.CharField(max_length=50) class Topping(models.Model): name = models.CharField(max_length=50) ison = models.ManyToManyField(Pizza, blank=True) class ToppingForm(forms.ModelForm): class Meta: model = Topping ``...
I guess you would have here to add a new `ModelMultipleChoiceField` to your `PizzaForm`, and manually link that form field with the model field, as Django won't do that automatically for you. The following snippet might be helpful : ``` class PizzaForm(forms.ModelForm): class Meta: model = Pizza # Re...
Override 'in' operator?
2,217,001
92
2010-02-07T14:08:27Z
2,217,005
122
2010-02-07T14:10:19Z
[ "python", "operators", "operator-overloading" ]
If I am creating my own class in Python, what function should I define so as to allow the use of the 'in' operator, e.g. ``` class MyClass(object): ... m = MyClass() if 54 in m: ... ```
[`MyClass.__contains__(self, item)`](http://docs.python.org/reference/datamodel.html#object.__contains__)
Override 'in' operator?
2,217,001
92
2010-02-07T14:08:27Z
2,218,413
101
2010-02-07T21:26:28Z
[ "python", "operators", "operator-overloading" ]
If I am creating my own class in Python, what function should I define so as to allow the use of the 'in' operator, e.g. ``` class MyClass(object): ... m = MyClass() if 54 in m: ... ```
A more complete answer is: ``` class MyClass(object): def __init__(self): self.numbers = [1,2,3,4,54] def __contains__(self, key): return key in self.numbers ``` Here you would get True when asking if 54 was in m: ``` >>> m = MyClass() >>> 54 in m True ``` See [documentation on overloading...
Using a debugger and curses at the same time?
2,217,109
8
2010-02-07T14:51:48Z
2,633,977
7
2010-04-13T23:48:05Z
[ "python", "exception", "interpreter", "curses", "pdb" ]
I'm calling `python -m pdb myapp.py`, when an exception fires, and I'd normally be thrown back to the pdb interpreter to investigate the problem. However this exception is being thrown after I've called through `curses.wrapper()` and entered curses mode, rendering the pdb interpreter useless. How can I work around this...
Not being familiar with Python, this may not be exactly what you want. But apparently, winpdb can attach to a script - just like gdb can to a running process (IIUC). <http://winpdb.org/docs/launch-time/> Don't be mislead by the name, it is platform independent.
Using a debugger and curses at the same time?
2,217,109
8
2010-02-07T14:51:48Z
2,949,419
7
2010-06-01T11:44:34Z
[ "python", "exception", "interpreter", "curses", "pdb" ]
I'm calling `python -m pdb myapp.py`, when an exception fires, and I'd normally be thrown back to the pdb interpreter to investigate the problem. However this exception is being thrown after I've called through `curses.wrapper()` and entered curses mode, rendering the pdb interpreter useless. How can I work around this...
James` answer is a good and I've upvoted it but I'd also consider trying to split the logic and presentation layers of my program. Keep the curses part a thin layer on top of a library and write a simple driver that invokes the correct routines to recreate the error. Then you can dive in and do what's necessary. Anoth...
Age from birthdate in python
2,217,488
78
2010-02-07T17:10:02Z
2,259,711
65
2010-02-14T00:39:21Z
[ "python", "datetime", "date" ]
How can I find an age in python from today's date and a persons birthdate? The birthdate is a from a DateField in a Django model.
``` from datetime import date def calculate_age(born): today = date.today() try: birthday = born.replace(year=today.year) except ValueError: # raised when birth date is February 29 and the current year is not a leap year birthday = born.replace(year=today.year, month=born.month+1, day=1) ...
Age from birthdate in python
2,217,488
78
2010-02-07T17:10:02Z
4,828,842
12
2011-01-28T13:40:20Z
[ "python", "datetime", "date" ]
How can I find an age in python from today's date and a persons birthdate? The birthdate is a from a DateField in a Django model.
``` from datetime import date days_in_year = 365.2425 age = int((date.today() - birth_date).days / days_in_year) ``` In Python 3, you could perform division on `datetime.timedelta`: ``` from datetime import date, timedelta age = (date.today() - birth_date) // timedelta(days=365.2425) ```
Age from birthdate in python
2,217,488
78
2010-02-07T17:10:02Z
9,754,466
123
2012-03-17T22:46:32Z
[ "python", "datetime", "date" ]
How can I find an age in python from today's date and a persons birthdate? The birthdate is a from a DateField in a Django model.
That can be done much simpler considering that int(True) is 1 and int(False) is 0: ``` from datetime import date def calculate_age(born): today = date.today() return today.year - born.year - ((today.month, today.day) < (born.month, born.day)) ```
Age from birthdate in python
2,217,488
78
2010-02-07T17:10:02Z
12,467,950
7
2012-09-17T22:28:23Z
[ "python", "datetime", "date" ]
How can I find an age in python from today's date and a persons birthdate? The birthdate is a from a DateField in a Django model.
The simplest way is using `python-dateutil` ``` import datetime import dateutil def birthday(date): # Get the current date now = datetime.datetime.utcnow() now = now.date() # Get the difference between the current date and the birthday age = dateutil.relativedelta.relativedelta(now, date) ag...
Inserting values into specific locations in a list in Python
2,218,238
18
2010-02-07T20:38:26Z
2,218,249
16
2010-02-07T20:41:17Z
[ "python", "list" ]
I am trying to do print all the possible outcomes of a given list and I was wondering how to put a value into various locations in the list. For example, if my list was `[A,B]`, I want to insert `X` into all possible index of the list such that it would return this `[X,A,B]`, `[A,X,B]`, `[A,B,X]`. I was thinking about...
You could do this with the following list comprehension: ``` [mylist[i:] + [newelement] + mylist[:i] for i in xrange(len(mylist),-1,-1)] ``` With your example: ``` >>> mylist=['A','B'] >>> newelement='X' >>> [mylist[i:] + [newelement] + mylist[:i] for i in xrange(len(mylist),-1,-1)] [['X', 'A', 'B'], ['B', 'X', 'A']...
Inserting values into specific locations in a list in Python
2,218,238
18
2010-02-07T20:38:26Z
2,218,392
36
2010-02-07T21:23:11Z
[ "python", "list" ]
I am trying to do print all the possible outcomes of a given list and I was wondering how to put a value into various locations in the list. For example, if my list was `[A,B]`, I want to insert `X` into all possible index of the list such that it would return this `[X,A,B]`, `[A,X,B]`, `[A,B,X]`. I was thinking about...
Use insert() to insert an element before a given position. For instance, with ``` arr = ['A','B','C'] arr.insert(0,'D') ``` arr becomes ['D','A','B','C'] because 'D' is inserted before the element at index 0. Now, for ``` arr = ['A','B','C'] arr.insert(4,'D') ``` arr becomes ['A','B','C','D'] because 'D' is inser...
SQLAlchemy INSERT IGNORE
2,218,304
19
2010-02-07T20:54:53Z
2,224,729
22
2010-02-08T20:45:04Z
[ "python", "insert", "sqlalchemy", "ignore" ]
How can I insert multiple data records into table ignoring duplicates. I am using SQLAlchemy. Thank you!
`prefix_with("TEXT")` adds arbitrary text between `INSERT` and the rest of the SQL. `execute()` accepts a list of dictionaries with the records you would like to insert or a single dictionary if you only want to insert a single record. The SQLite syntax for the behavior you're looking for: ``` inserter = table_object...
What's wrong here? Iterating over a dictionary in Django template
2,218,388
7
2010-02-07T21:22:30Z
2,218,605
27
2010-02-07T22:19:58Z
[ "python", "django", "django-templates" ]
I'm trying to iterate over a dictionary of model values in a Django template - I want to list the verbose\_name of each model field alongside its value. Here's what I have in models.py: ``` class Manors(models.Model): structidx = models.IntegerField(primary_key=True, verbose_name="ID") county = models.Cha...
To iterate a dictionary wouldn't you need: ``` <h4>Statistics</h4> <ul> {% for key, value in manor_stats.get_fields.items %} <li> {{ key }}: {{ value }}</li> {% endfor %} </ul> ``` But I'd suggest retrieving the dictionary from the function first: Views.py: ``` manor_stats = Manors.objects.get(structidx__exa...
Unable to access ID property from a datastore entity
2,218,693
6
2010-02-07T22:45:26Z
2,218,736
8
2010-02-07T22:59:20Z
[ "python", "google-app-engine", "entity", "gae-datastore" ]
Using Google App Engine SDK and Python, I'm facing an issue : I'm unable to access the ID property of a given entity properties. The only properties I can access are those defined in my class Model, plus the key property (see answer below) : ``` class Question(db.Model): text = db.StringProperty() answers = db...
According to the **[documentation](http://code.google.com/appengine/docs/python/datastore/modelclass.html)**, there is no `id()` instance method defined for Model subclasses. Try `{{ question.key }}` instead. Also note that the key is not created until the entity is saved to the datastore. --- Edit: more info based...
Pylons: Webhelpers: missing secure_form module
2,219,316
2
2010-02-08T02:58:22Z
2,219,493
7
2010-02-08T03:58:40Z
[ "python", "module", "pylons" ]
I installed Pylons 0.9.7 using the go-pylons.py script. I have a line of python: ``` from webhelpers.html.secure_form import secure_form ``` When I try to serve my application I get the error: no module secure\_form. I've tried writing import webhelpers.html.tags and other modules from webhelpers and those work. I...
if your webhelpers version is 1.0b4 or above, secure\_form is under webhelpers.pylonslib, ie. ``` from webhelpers.pylonslib import secure_form ```
Independent instances of 'random'
2,219,436
6
2010-02-08T03:42:33Z
2,219,470
12
2010-02-08T03:51:36Z
[ "python", "class", "random", "module", "seed" ]
The below code attempts to illustrate what I want. I basically want two instances of "random" that operate independently of each other. I want to seed "random" within one class without affecting "random" in another class. How can I do that? ``` class RandomSeeded: def __init__(self, seed): import random as...
Class `random.Random` exists specifically to allow the behavior you want -- modules are intrinsically singletons, but classes are meant to be multiply instantiated, so both kinds of needs are covered. Should you ever need an independent copy of a module (which you definitely don't in the case of `random`!), try using ...
How to know all the derived classes of a parent?
2,219,998
14
2010-02-08T06:46:38Z
2,220,121
13
2010-02-08T07:28:40Z
[ "python" ]
Suppose you have a base class A, and this class is reimplemented by B and C. Suppose also there's a class method `A.derived()` that tells you which classes are reimplementing A, hence returns [B, C], and if you later on have `class D(A): pass` or `class D(B): pass`, now `A.derived()` returns [B,C,D]. How would you imp...
If you define your classes as a new-style class (subclass of `object`) then this is possible since the subclasses are saved in `__subclasses__`. ``` class A(object): def hello(self): print "Hello A" class B(A): def hello(self): print "Hello B" >>> for cls in A.__subclasses__(): ... print cls.__name__ ... B `...
What would I use Stackless Python for?
2,220,645
38
2010-02-08T09:48:12Z
2,221,057
12
2010-02-08T10:58:20Z
[ "python", "python-stackless" ]
There are many questions related to Stackless Python. But none answering this my question, I think (correct me if wrong - please!). There's some buzz about it all the time so I curious to know. What would I use Stackless for? How is it better than CPython? Yes it has green threads (stackless) that allow quickly create...
Stackless Python's main benefit is the support for very lightweight coroutines. CPython doesn't support coroutines natively (although I expect someone to post a generator-based hack in the comments) so Stackless is a clear improvement on CPython when you have a problem that benefits from coroutines. I think the main a...
What would I use Stackless Python for?
2,220,645
38
2010-02-08T09:48:12Z
2,249,019
27
2010-02-12T01:15:33Z
[ "python", "python-stackless" ]
There are many questions related to Stackless Python. But none answering this my question, I think (correct me if wrong - please!). There's some buzz about it all the time so I curious to know. What would I use Stackless for? How is it better than CPython? Yes it has green threads (stackless) that allow quickly create...
It allows you to work with massive amounts of concurrency. Nobody sane would create one hundred thousand system threads, but you can do this using stackless. This article tests doing just that, creating one hundred thousand tasklets in both Python and Google Go (a new programming language): <http://dalkescientific.com...
What would I use Stackless Python for?
2,220,645
38
2010-02-08T09:48:12Z
2,251,860
8
2010-02-12T12:50:27Z
[ "python", "python-stackless" ]
There are many questions related to Stackless Python. But none answering this my question, I think (correct me if wrong - please!). There's some buzz about it all the time so I curious to know. What would I use Stackless for? How is it better than CPython? Yes it has green threads (stackless) that allow quickly create...
Thirler already mentioned that stackless was used in Eve Online. Keep in mind, that: > (..) stackless adds a further twist to this by allowing tasks to be separated into smaller tasks, Tasklets, which can then be split off the main program to execute on their own. This can be used for fire-and-forget tasks, like sendi...
What's the difference between eval, exec, and compile in Python?
2,220,699
231
2010-02-08T09:56:43Z
2,220,790
175
2010-02-08T10:13:31Z
[ "python", "dynamic", "eval", "exec" ]
I've been looking at dynamic evaluation of Python code, and come across the `eval()` and `compile()` functions, and the `exec` statement. Can someone please explain the difference between `eval` and `exec`, and how the different modes of `compile()` fit in?
1. `exec` is not an expression: a statement in Python 2.x, and a function in Python 3.x. It compiles and immediately evaluates a statement or set of statement contained in a string. Example: ``` exec('print(5)') # prints 5. # exec 'print 5' if you use Python 2.x, nor the exec neither the print i...
What's the difference between eval, exec, and compile in Python?
2,220,699
231
2010-02-08T09:56:43Z
14,097,282
42
2012-12-31T04:02:10Z
[ "python", "dynamic", "eval", "exec" ]
I've been looking at dynamic evaluation of Python code, and come across the `eval()` and `compile()` functions, and the `exec` statement. Can someone please explain the difference between `eval` and `exec`, and how the different modes of `compile()` fit in?
exec is for statement and does not return anything. eval is for expression and returns value of expression. expression means "something" while statement means "do something".
What's the difference between eval, exec, and compile in Python?
2,220,699
231
2010-02-08T09:56:43Z
29,456,463
158
2015-04-05T10:44:44Z
[ "python", "dynamic", "eval", "exec" ]
I've been looking at dynamic evaluation of Python code, and come across the `eval()` and `compile()` functions, and the `exec` statement. Can someone please explain the difference between `eval` and `exec`, and how the different modes of `compile()` fit in?
# The short answer, or TL;DR Basically, [`eval`](https://docs.python.org/3/library/functions.html#eval) is used to **eval**uate a single dynamically generated Python expression, and [`exec`](https://docs.python.org/3/library/functions.html#exec) is used to **exec**ute dynamically generated Python code only for its sid...
Rasterizing a GDAL layer
2,220,749
22
2010-02-08T10:06:43Z
2,220,980
8
2010-02-08T10:45:45Z
[ "python", "gis", "gdal", "rasterizing" ]
**Edit** Here is the proper way to do it, and the [documentation](http://gdal.org/gdal__alg_8h.html#dfe5e5d287d6c184aab03acbfa567cb1): ``` import random from osgeo import gdal, ogr RASTERIZE_COLOR_FIELD = "__color__" def rasterize(pixel_size=25) # Open the data source orig_data_source = ogr.Open("test.s...
EDIT: I guess I'd use qGIS python bindings: <http://www.qgis.org/wiki/Python_Bindings> That's the easiest way I can think of. I remember hand rolling something before, but it's ugly. qGIS would be easier, even if you had to make a separate Windows installation (to get python to work with it) then set up an XML-RPC ser...
Python: Setting an element of a Numpy matrix
2,220,968
12
2010-02-08T10:43:24Z
2,220,983
28
2010-02-08T10:46:52Z
[ "python" ]
I am a pretty new to python. I have created an empty matrix ``` a = numpy.zeros(shape=(n,n)) ``` Now I can access each element using ``` a.item(i,j) ``` How do I set an index (i,j)?
Here's how: ``` a[i,j] = x ```
Logging in and using cookies in pycurl
2,221,191
6
2010-02-08T11:24:04Z
2,335,107
10
2010-02-25T15:21:43Z
[ "python", "curl", "pycurl" ]
I need to download a file that is on a password protected page. To get to the page manually I first have to authenticate via an ordinary login page. I want to use curl to fetch this page in script. My script first logins. It appears to succeed--it returns a 200 from a PUT to /login. However, the fetch of the desired ...
I believe Curl will store the cookies but you need to use them explicitly. I've only ever used the command line interface for this though. Scanning the documentation I think you might want to try: ``` C.setopt(pycurl.COOKIEFILE, 'cookie.txt') ``` (before the second request)
Why doesn't this loop display an updated object count every five seconds?
2,221,247
7
2010-02-08T11:34:29Z
2,221,400
16
2010-02-08T12:05:49Z
[ "python", "mysql", "django" ]
I use this python code to output the number of Things every 5 seconds: ``` def my_count(): while True: print "Number of Things: %d" % Thing.objects.count() time.sleep(5) my_count() ``` If another process generates a new Thing while my\_count() is running, my\_count() will keep printing the s...
Because Python DB API is by default in AUTOCOMMIT=OFF mode, and (at least for MySQLdb) on REPEATABLE READ isolation level. This means that behind the scenes you have an ongoing database transaction (InnoDB is transactional engine) in which the first access to given row (or maybe even table, I'm not sure) fixes "view" o...