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
How to sort based on dependencies?
952,302
7
2009-06-04T18:31:25Z
952,388
15
2009-06-04T18:47:11Z
[ "python", "sorting", "dependencies" ]
I have an class that has a list of "dependencies" pointing to other classes of the same base type. ``` class Foo(Base): dependencies = [] class Bar(Base): dependencies = [Foo] class Baz(Base): dependencies = [Bar] ``` I'd like to sort the instances these classes generate based on their dependencies. In ...
It's called a topological sort. ``` def sort_deps(objs): queue = [objs with no dependencies] while queue: obj = queue.pop() yield obj for obj in objs: if dependencies are now satisfied: queue.append(obj) if not all dependencies are satisfied: erro...
Making a flat list out of list of lists in Python
952,914
1,039
2009-06-04T20:30:05Z
952,943
46
2009-06-04T20:35:30Z
[ "python", "list" ]
I wonder whether there is a shortcut to make a simple list out of list of lists in Python. I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with *reduce*, but I get an error. **Code** ``` l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] reduce(lambda x, y: x.extend(y), l) ``` **Error message...
``` >>> l = [[1,2,3],[4,5,6], [7], [8,9]] >>> reduce(lambda x,y: x+y,l) [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` The `extend()` method in your example modifies `x` instead of returning a useful value (which `reduce()` expects). A faster way to do the `reduce` version would be ``` >>> import operator >>> l = [[1,2,3],[4,5,6],...
Making a flat list out of list of lists in Python
952,914
1,039
2009-06-04T20:30:05Z
952,946
375
2009-06-04T20:35:53Z
[ "python", "list" ]
I wonder whether there is a shortcut to make a simple list out of list of lists in Python. I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with *reduce*, but I get an error. **Code** ``` l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] reduce(lambda x, y: x.extend(y), l) ``` **Error message...
``` >>> sum(l, []) [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` Note that only works on lists of lists. For lists of lists of lists, you'll need another solution.
Making a flat list out of list of lists in Python
952,914
1,039
2009-06-04T20:30:05Z
952,952
1,587
2009-06-04T20:37:01Z
[ "python", "list" ]
I wonder whether there is a shortcut to make a simple list out of list of lists in Python. I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with *reduce*, but I get an error. **Code** ``` l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] reduce(lambda x, y: x.extend(y), l) ``` **Error message...
``` [item for sublist in l for item in sublist] ``` is faster than the shortcuts posted so far. (`l` is the list to flatten.) For evidence, as always, you can use the `timeit` module in the standard library: ``` $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]' 10...
Making a flat list out of list of lists in Python
952,914
1,039
2009-06-04T20:30:05Z
952,954
18
2009-06-04T20:38:08Z
[ "python", "list" ]
I wonder whether there is a shortcut to make a simple list out of list of lists in Python. I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with *reduce*, but I get an error. **Code** ``` l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] reduce(lambda x, y: x.extend(y), l) ``` **Error message...
Why do you use extend? ``` reduce(lambda x, y: x+y, l) ``` This should work fine.
Making a flat list out of list of lists in Python
952,914
1,039
2009-06-04T20:30:05Z
952,993
21
2009-06-04T20:46:49Z
[ "python", "list" ]
I wonder whether there is a shortcut to make a simple list out of list of lists in Python. I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with *reduce*, but I get an error. **Code** ``` l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] reduce(lambda x, y: x.extend(y), l) ``` **Error message...
**I take my statement back. sum is not the winner. Although it is faster when the list is small. But the performance degrades significantly with larger lists.** ``` >>> timeit.Timer( '[item for sublist in l for item in sublist]', 'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]] * 10000' ).tim...
Making a flat list out of list of lists in Python
952,914
1,039
2009-06-04T20:30:05Z
952,997
9
2009-06-04T20:47:13Z
[ "python", "list" ]
I wonder whether there is a shortcut to make a simple list out of list of lists in Python. I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with *reduce*, but I get an error. **Code** ``` l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] reduce(lambda x, y: x.extend(y), l) ``` **Error message...
The reason your function didn't work: the extend extends array in-place and doesn't return it. You can still return x from lambda, using some trick: ``` reduce(lambda x,y: x.extend(y) or x, l) ``` Note: extend is more efficient than + on lists.
Making a flat list out of list of lists in Python
952,914
1,039
2009-06-04T20:30:05Z
953,050
57
2009-06-04T20:57:24Z
[ "python", "list" ]
I wonder whether there is a shortcut to make a simple list out of list of lists in Python. I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with *reduce*, but I get an error. **Code** ``` l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] reduce(lambda x, y: x.extend(y), l) ``` **Error message...
@Nadia: You have to use much longer lists. Then you see the difference quite strikingly! My results for `len(l) = 1600` ``` A took 14.323 ms B took 13.437 ms C took 1.135 ms ``` where: ``` A = reduce(lambda x,y: x+y,l) B = sum(l, []) C = [item for sublist in l for item in sublist] ```
Making a flat list out of list of lists in Python
952,914
1,039
2009-06-04T20:30:05Z
953,097
687
2009-06-04T21:06:17Z
[ "python", "list" ]
I wonder whether there is a shortcut to make a simple list out of list of lists in Python. I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with *reduce*, but I get an error. **Code** ``` l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] reduce(lambda x, y: x.extend(y), l) ``` **Error message...
You can use [`itertools.chain()`](http://docs.python.org/2/library/itertools.html#itertools.chain): ``` >>> import itertools >>> list2d = [[1,2,3],[4,5,6], [7], [8,9]] >>> merged = list(itertools.chain(*list2d)) ``` or, on Python >=2.6, use [`itertools.chain.from_iterable()`](http://docs.python.org/2/library/itertool...
Explicit access to Python's built in scope
953,027
10
2009-06-04T20:54:02Z
953,063
11
2009-06-04T21:00:00Z
[ "python" ]
How do you explicitly access name in Python's built in scope? One situation where I ran in to this was a in module, say called foo, which happened to have an open function. In another module foo's open function would be accessible as foo.open which works well. In foo itself though, open blocks the built in open. How c...
Use `__builtin__`. ``` def open(): pass import __builtin__ print open print __builtin__.open ``` ... gives you ... > `<function open at 0x011E8670>` > `<built-in function open>`
Why won't python allow me to delete files?
953,040
3
2009-06-04T20:55:38Z
953,052
14
2009-06-04T20:57:40Z
[ "python", "file-io" ]
I've created a python script that gets a list of files from a text file and deletes them if they're empty. It correctly detects empty files but it doesn't want to delete them. It gives me: ``` (32, 'The process cannot access the file because it is being used by another process') ``` I've used two different tools to c...
You need to call `.close()` on the file object before you try and delete it. Edit: And really you shouldn't be opening the file at all. `os.stat()` will tell you the size of a file (and 9 other values) without ever opening the file. This (I think) does the same thing but is a little cleaner (IMHO): ``` import os _M...
Why won't python allow me to delete files?
953,040
3
2009-06-04T20:55:38Z
953,062
9
2009-06-04T20:59:35Z
[ "python", "file-io" ]
I've created a python script that gets a list of files from a text file and deletes them if they're empty. It correctly detects empty files but it doesn't want to delete them. It gives me: ``` (32, 'The process cannot access the file because it is being used by another process') ``` I've used two different tools to c...
Try ActiveFile.close() before doing the unlink. Also, reading the whole file isn't necessary, you can use os.path.getsize(filename) == 0.
SSH Connection with Python 3.0
953,477
6
2009-06-04T22:39:35Z
953,510
11
2009-06-04T22:47:36Z
[ "python", "file", "ssh" ]
How can I make an SSH connection in Python 3.0? I want to save a file on a remote computer where I have password-less SSH set up.
I recommend calling ssh as a subprocess. It's reliable and portable. ``` import subprocess proc = subprocess.Popen(['ssh', 'user@host', 'cat > %s' % filename], stdin=subprocess.PIPE) proc.communicate(file_contents) if proc.retcode != 0: ... ``` You'd have to worry about quoting the destina...
Check unread count of Gmail messages with Python
953,561
31
2009-06-04T23:05:30Z
953,607
22
2009-06-04T23:22:58Z
[ "python", "email", "gmail", "pop3" ]
How can I check the number of unread Gmail message in my inbox with a short Python script? Bonus points for retrieving the password from a file.
I advise you to use [Gmail atom feed](https://developers.google.com/gmail/gmail_inbox_feed) It is as simple as this: ``` import urllib url = 'https://mail.google.com/mail/feed/atom/' opener = urllib.FancyURLopener() f = opener.open(url) feed = f.read() ``` You can then use the feed parse function in this nice artic...
Check unread count of Gmail messages with Python
953,561
31
2009-06-04T23:05:30Z
954,099
22
2009-06-05T03:05:12Z
[ "python", "email", "gmail", "pop3" ]
How can I check the number of unread Gmail message in my inbox with a short Python script? Bonus points for retrieving the password from a file.
Well, I'm going to go ahead and spell out an imaplib solution as Cletus suggested. I don't see why people feel the need to use gmail.py or Atom for this. This kind of thing is what IMAP was designed for. Gmail.py is particularly egregious as it actually parses Gmail's HTML. That may be necessary for some things, but no...
Check unread count of Gmail messages with Python
953,561
31
2009-06-04T23:05:30Z
3,984,850
49
2010-10-21T06:30:45Z
[ "python", "email", "gmail", "pop3" ]
How can I check the number of unread Gmail message in my inbox with a short Python script? Bonus points for retrieving the password from a file.
``` import imaplib obj = imaplib.IMAP4_SSL('imap.gmail.com','993') obj.login('username','password') obj.select() obj.search(None,'UnSeen') ```
Which gps library would you recommend for python?
953,701
8
2009-06-05T00:01:57Z
973,022
8
2009-06-09T23:31:28Z
[ "python", "gps", "gpsd" ]
I'm looking for a free library for python that can calculate your direction and your speed from GPS coordinates and maybe can calculate if you are in some boundaries or things like this. Are there Libraries that you know and that worked well for you? **Edit:** Ok it seems I have to specify this a little bit. We are u...
Apparently the python module that comes with gpsd is the best module to go with for us. For a start look [here](http://www.perrygeo.net/wordpress/?p=13) The gps module coming with the gpsd has some very useful functions. The first one is getting the data from gpsd and transforming those data in a usable data structure...
Getting object's parent namespace in python?
954,340
9
2009-06-05T05:03:01Z
954,347
14
2009-06-05T05:06:02Z
[ "python", "python-datamodel" ]
In python it's possible to use '.' in order to access object's dictionary items. For example: ``` class test( object ) : def __init__( self ) : self.b = 1 def foo( self ) : pass obj = test() a = obj.foo ``` From above example, having 'a' object, is it possible to get from it reference to 'obj' that is a p...
## Python 2.6+ (including Python 3) You can use the [`__self__` property of a bound method](https://docs.python.org/2/reference/datamodel.html#the-standard-type-hierarchy) to access the instance that the method is bound to. ``` >> a.__self__ <__main__.test object at 0x782d0> >> a.__self__.b = 2 >> obj.b 2 ``` ## Pyt...
Getting object's parent namespace in python?
954,340
9
2009-06-05T05:03:01Z
954,514
17
2009-06-05T06:31:40Z
[ "python", "python-datamodel" ]
In python it's possible to use '.' in order to access object's dictionary items. For example: ``` class test( object ) : def __init__( self ) : self.b = 1 def foo( self ) : pass obj = test() a = obj.foo ``` From above example, having 'a' object, is it possible to get from it reference to 'obj' that is a p...
On bound methods, you can use three special read-only parameters: * **im\_func** which returns the (unbound) function object * **im\_self** which returns the object the function is bound to (class instance) * **im\_class** which returns the class of *im\_self* Testing around: ``` class Test(object): def foo(self...
Getting object's parent namespace in python?
954,340
9
2009-06-05T05:03:01Z
954,619
7
2009-06-05T07:16:59Z
[ "python", "python-datamodel" ]
In python it's possible to use '.' in order to access object's dictionary items. For example: ``` class test( object ) : def __init__( self ) : self.b = 1 def foo( self ) : pass obj = test() a = obj.foo ``` From above example, having 'a' object, is it possible to get from it reference to 'obj' that is a p...
since python2.6 synonyms for `im_self` and `im_func` are `__self__` and `__func__`, respectively. `im*` attributes are completely gone in py3k. so you would need to change it to: ``` >> a.__self__ <__main__.test object at 0xb7b7d9ac> >> a.__self__.b = 2 >> obj.b 2 ```
How to get files in a directory, including all subdirectories
954,504
15
2009-06-05T06:27:08Z
954,517
7
2009-06-05T06:33:17Z
[ "python" ]
I'm trying to get a list of all log files (.log) in directory, including all subdirectories.
Checkout [Python Recursive Directory Walker](http://ssscripting.wordpress.com/2009/03/03/python-recursive-directory-walker/). In short os.listdir() and os.walk() are your friends.
How to get files in a directory, including all subdirectories
954,504
15
2009-06-05T06:27:08Z
954,522
28
2009-06-05T06:35:19Z
[ "python" ]
I'm trying to get a list of all log files (.log) in directory, including all subdirectories.
``` import os import os.path for dirpath, dirnames, filenames in os.walk("."): for filename in [f for f in filenames if f.endswith(".log")]: print os.path.join(dirpath, filename) ```
How do I use raw_input in Python 3
954,834
220
2009-06-05T08:32:23Z
954,840
405
2009-06-05T08:35:38Z
[ "python", "python-3.x" ]
``` import sys print (sys.platform) print (2 ** 100) raw_input( ) ``` I am using Python 3.1 and can't get the raw\_input to "freeze" the dos pop-up. The book I'm reading is for 2.5 and I'm using 3.1 What should I do to fix this?
`raw_input()` was renamed to `input()` From <http://docs.python.org/dev/py3k/whatsnew/3.0.html>
How do I use raw_input in Python 3
954,834
220
2009-06-05T08:32:23Z
7,321,970
66
2011-09-06T14:59:18Z
[ "python", "python-3.x" ]
``` import sys print (sys.platform) print (2 ** 100) raw_input( ) ``` I am using Python 3.1 and can't get the raw\_input to "freeze" the dos pop-up. The book I'm reading is for 2.5 and I'm using 3.1 What should I do to fix this?
This works in Python 3.x and 2.x: ``` # Fix Python 2.x. try: input = raw_input except NameError: pass print("Hi " + input("Say something: ")) ```
How do I use raw_input in Python 3
954,834
220
2009-06-05T08:32:23Z
9,411,780
11
2012-02-23T11:05:27Z
[ "python", "python-3.x" ]
``` import sys print (sys.platform) print (2 ** 100) raw_input( ) ``` I am using Python 3.1 and can't get the raw\_input to "freeze" the dos pop-up. The book I'm reading is for 2.5 and I'm using 3.1 What should I do to fix this?
As others have indicated, the `raw_input` function has been renamed to `input` in Python 3.0, and you really would be better served by a more up-to-date book, but I want to point out that there are better ways to see the output of your script. From your description, I think you're using Windows, you've saved a `.py` f...
How do I use raw_input in Python 3
954,834
220
2009-06-05T08:32:23Z
31,687,067
8
2015-07-28T21:05:42Z
[ "python", "python-3.x" ]
``` import sys print (sys.platform) print (2 ** 100) raw_input( ) ``` I am using Python 3.1 and can't get the raw\_input to "freeze" the dos pop-up. The book I'm reading is for 2.5 and I'm using 3.1 What should I do to fix this?
A reliable way to address this is ``` from six.moves import input ``` [six](http://pythonhosted.org/six/) is a module which patches over many of the 2/3 common code base pain points.
How do I run "dot" as a command from Python?
955,504
4
2009-06-05T11:55:09Z
955,523
10
2009-06-05T12:01:06Z
[ "python", "osx", "path", "graphviz", "dot" ]
I am using Python on Mac OSX Leopard. I am trying to run the program 'dot' (part of Graphviz) from Python: ``` # -*- coding: utf-8 -*- import os print os.environ['PATH'] print os.system("ls >> a.txt") print os.system("dot -o9.png -Tpng ./6.dot") ``` The command "ls" is there just to make sure that python is in the ...
`whereis` locates man pages, `which` locates binaries. So try `which dot`.
How to identify whether a file is normal file or directory using python
955,941
64
2009-06-05T13:47:31Z
955,952
93
2009-06-05T13:50:09Z
[ "python" ]
How do you check whether a file is a normal file or a directory using python?
`os.path.isdir()` and `os.path.isfile()` should give you what you want. See: <http://docs.python.org/library/os.path.html>
How to identify whether a file is normal file or directory using python
955,941
64
2009-06-05T13:47:31Z
956,092
27
2009-06-05T14:15:07Z
[ "python" ]
How do you check whether a file is a normal file or a directory using python?
As other answers have said, `os.path.isdir()` and `os.path.isfile()` are what you want. However, you need to keep in mind that these are not the only two cases. Use `os.path.islink()` for symlinks for instance. Furthermore, these all return `False` if the file does not exist, so you'll probably want to check with `os.p...
What is the correct way to set Python's locale on Windows?
955,986
50
2009-06-05T13:56:42Z
956,084
62
2009-06-05T14:13:18Z
[ "python", "localization", "internationalization" ]
I'm attempting to sort a list of strings in a locale-aware manner. I've used the Babel library for other i18n-related tasks, but it doesn't support sorting. Python's `locale` module provides a `strcoll` function, but requires the locale of the process to be set to the one I want to work with. Kind of a pain, but I can ...
It seems you're using Windows. The locale strings are different there. Take a more precise look at the doc: ``` locale.setlocale(locale.LC_ALL, 'de_DE') # use German locale; name might vary with platform ``` On Windows, I think it would be something like: ``` locale.setlocale(locale.LC_ALL, 'deu_deu') ``` MSDN has ...
What is the correct way to set Python's locale on Windows?
955,986
50
2009-06-05T13:56:42Z
24,485,432
10
2014-06-30T07:59:59Z
[ "python", "localization", "internationalization" ]
I'm attempting to sort a list of strings in a locale-aware manner. I've used the Babel library for other i18n-related tasks, but it doesn't support sorting. Python's `locale` module provides a `strcoll` function, but requires the locale of the process to be set to the one I want to work with. Kind of a pain, but I can ...
On Ubuntu you may have this problem because you don't have that local installed on your system. From shell try a: ``` $> locale -a ``` and check if you find the locale you are interested in. Otherwise you have to install it: ``` $> sudo apt-get install language-pack-XXX ``` where XXX is your language (in my case "...
Getting column info in cx_oracle when table is empty?
956,085
6
2009-06-05T14:13:18Z
957,599
12
2009-06-05T19:11:16Z
[ "python", "cx-oracle" ]
I am working on an a handler for the python logging module. That essentially logs to an oracle database. I am using cx\_oracle, and something i don't know how to get is the column values when the table is empty. ``` cursor.execute('select * from FOO') for row in cursor: # this is never executed because cursor has...
I think the [`description`](http://cx-oracle.readthedocs.org/en/latest/cursor.html#Cursor.description) attribute may be what you are looking for. This returns a list of tuples that describe the columns of the data returned. It works quite happily if there are no rows returned, for example: ``` >>> import cx_Oracle >>>...
python: attributes on a generator object
956,585
5
2009-06-05T15:39:54Z
956,600
13
2009-06-05T15:42:21Z
[ "python" ]
Is it possible to create an attribute on a generator object? Here's a very simple example: ``` def filter(x): for line in myContent: if line == x: yield x ``` Now say I have a lot of these filter generator objects floating around... maybe some of them are anonymous... I want to go back later ...
Yes. ``` class Filter( object ): def __init__( self, content ): self.content = content def __call__( self, someParam ): self.someParam = someParam for line in self.content: if line == someParam: yield line ```
Python open raw audio data file
956,720
5
2009-06-05T16:05:51Z
956,755
7
2009-06-05T16:10:57Z
[ "python", "audio" ]
I have these files with the extension ".adc". They are simply raw data files. I can open them with Audacity using File->Import->Raw data with encoding "Signed 16 bit" and sample rate "16000 Khz". I would like to do the same with python. I think that audioop module is what I need, but I can't seem to find examples on h...
For opening the file, you just need `file()`. For finding a location, you don't need audioop: you just need to convert seconds to bytes and get the required bytes of the file. For instance, if your file is 16 kHz 16bit mono, each second is 32,000 bytes of data. So the 10th second is 320kB into the file. Just seek to th...
How to get string objects instead of Unicode ones from JSON in Python?
956,867
176
2009-06-05T16:32:17Z
956,927
31
2009-06-05T16:44:45Z
[ "python", "json", "serialization", "unicode", "yaml" ]
I'm using **Python 2** to parse JSON from (**ASCII encoded**) text files. When loading these files with either [`json`](https://docs.python.org/2/library/json.html) or [`simplejson`](https://pypi.python.org/pypi/simplejson/), all my string values are cast to Unicode objects instead of string objects. The problem is, I...
That's because json has no difference between string objects and unicode objects. They're all strings in javascript. I think **JSON is right to return unicode objects**. In fact, I wouldn't accept anything less, since javascript strings **are in fact `unicode` objects** (i.e. JSON (javascript) strings can store *any k...
How to get string objects instead of Unicode ones from JSON in Python?
956,867
176
2009-06-05T16:32:17Z
957,274
9
2009-06-05T18:10:03Z
[ "python", "json", "serialization", "unicode", "yaml" ]
I'm using **Python 2** to parse JSON from (**ASCII encoded**) text files. When loading these files with either [`json`](https://docs.python.org/2/library/json.html) or [`simplejson`](https://pypi.python.org/pypi/simplejson/), all my string values are cast to Unicode objects instead of string objects. The problem is, I...
I'm afraid there's no way to achieve this automatically within the simplejson library. The scanner and decoder in simplejson are designed to produce unicode text. To do this, the library uses a function called `c_scanstring` (if it's available, for speed), or `py_scanstring` if the C version is not available. The `sca...
How to get string objects instead of Unicode ones from JSON in Python?
956,867
176
2009-06-05T16:32:17Z
6,633,651
68
2011-07-09T08:25:41Z
[ "python", "json", "serialization", "unicode", "yaml" ]
I'm using **Python 2** to parse JSON from (**ASCII encoded**) text files. When loading these files with either [`json`](https://docs.python.org/2/library/json.html) or [`simplejson`](https://pypi.python.org/pypi/simplejson/), all my string values are cast to Unicode objects instead of string objects. The problem is, I...
You can use the `object_hook` parameter for [`json.loads`](http://docs.python.org/library/json.html#json.loads) to pass in a converter. You don't have to do the conversion after the fact. The [`json`](http://docs.python.org/library/json.html) module will always pass the `object_hook` dicts only, and it will recursively...
How to get string objects instead of Unicode ones from JSON in Python?
956,867
176
2009-06-05T16:32:17Z
13,105,359
112
2012-10-28T00:27:17Z
[ "python", "json", "serialization", "unicode", "yaml" ]
I'm using **Python 2** to parse JSON from (**ASCII encoded**) text files. When loading these files with either [`json`](https://docs.python.org/2/library/json.html) or [`simplejson`](https://pypi.python.org/pypi/simplejson/), all my string values are cast to Unicode objects instead of string objects. The problem is, I...
There's no built-in option to make the json module functions return byte strings instead of unicode strings. However, this short and simple recursive function will convert any decoded JSON object from using unicode strings to UTF-8-encoded byte strings: ``` def byteify(input): if isinstance(input, dict): r...
How to get string objects instead of Unicode ones from JSON in Python?
956,867
176
2009-06-05T16:32:17Z
16,373,377
121
2013-05-04T10:37:24Z
[ "python", "json", "serialization", "unicode", "yaml" ]
I'm using **Python 2** to parse JSON from (**ASCII encoded**) text files. When loading these files with either [`json`](https://docs.python.org/2/library/json.html) or [`simplejson`](https://pypi.python.org/pypi/simplejson/), all my string values are cast to Unicode objects instead of string objects. The problem is, I...
While there are some good answers here, I ended up using [PyYAML](http://pyyaml.org/) to parse my JSON files, since it gives the keys and values as `str` type strings instead of `unicode` type. Because JSON is a subset of YAML it works nicely: ``` >>> import json >>> import yaml >>> list_org = ['a', 'b'] >>> list_dump...
How to get string objects instead of Unicode ones from JSON in Python?
956,867
176
2009-06-05T16:32:17Z
19,826,039
11
2013-11-07T01:01:43Z
[ "python", "json", "serialization", "unicode", "yaml" ]
I'm using **Python 2** to parse JSON from (**ASCII encoded**) text files. When loading these files with either [`json`](https://docs.python.org/2/library/json.html) or [`simplejson`](https://pypi.python.org/pypi/simplejson/), all my string values are cast to Unicode objects instead of string objects. The problem is, I...
There exists an easy work-around. TL;DR - Use `ast.literal_eval()` instead of `json.loads()`. Both `ast` and `json` are in the standard library. While not a 'perfect' answer, it gets one pretty far if your plan is to ignore Unicode altogether. In Python 2.7 ``` import json, ast d = { 'field' : 'value' } print "JSON ...
How to get string objects instead of Unicode ones from JSON in Python?
956,867
176
2009-06-05T16:32:17Z
33,571,117
23
2015-11-06T16:18:59Z
[ "python", "json", "serialization", "unicode", "yaml" ]
I'm using **Python 2** to parse JSON from (**ASCII encoded**) text files. When loading these files with either [`json`](https://docs.python.org/2/library/json.html) or [`simplejson`](https://pypi.python.org/pypi/simplejson/), all my string values are cast to Unicode objects instead of string objects. The problem is, I...
### A solution with `object_hook` ``` import json def json_load_byteified(file_handle): return _byteify( json.load(file_handle, object_hook=_byteify), ignore_dicts=True ) def json_loads_byteified(json_text): return _byteify( json.loads(json_text, object_hook=_byteify), ign...
Clean Python Regular Expressions
958,853
12
2009-06-06T02:21:57Z
958,860
22
2009-06-06T02:25:01Z
[ "python", "regex", "list" ]
Is there a cleaner way to write long regex patterns in python? I saw this approach somewhere but regex in python doesn't allow lists. ``` patterns = [ re.compile(r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>'), re.compile(r'\n+|\s{2}') ] ```
You can use verbose mode to write more readable regular expressions. In this mode: * Whitespace within the pattern is ignored, except when in a character class or preceded by an unescaped backslash. * When a line contains a '#' neither in a character class or preceded by an unescaped backslash, all characters from the...
Clean Python Regular Expressions
958,853
12
2009-06-06T02:21:57Z
958,890
12
2009-06-06T02:58:07Z
[ "python", "regex", "list" ]
Is there a cleaner way to write long regex patterns in python? I saw this approach somewhere but regex in python doesn't allow lists. ``` patterns = [ re.compile(r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>'), re.compile(r'\n+|\s{2}') ] ```
Though @Ayman's suggestion about `re.VERBOSE` is a better idea, if all you want is what you're showing, just do: ``` patterns = re.compile( r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>' r'\n+|\s{2}' ) ``` and Python's automatic concatenation of adjacent string literals (much like C's, btw) will do the rest;-)...
Python function calls are bleeding scope, stateful, failing to initialize parameters?
959,113
4
2009-06-06T06:15:00Z
959,118
15
2009-06-06T06:20:01Z
[ "python", "scope" ]
Before I have the audacity to file a bug report, I thought I'd check my assumptions among wiser Pythonistas here. I encountered a baffling case today, so I whittled it down to a toy example, shown below: ``` #!/usr/bin/env python # -*- coding: UTF-8 -*- """ A little script to demonstrate that a function won't re-init...
In Python default parameter values only get initialized when the def call is parsed. In the case of an object (such as your lists), it gets reused between calls. Take a look at this article about it, which also provides the necessary workaround: <http://effbot.org/zone/default-values.htm>
Python function calls are bleeding scope, stateful, failing to initialize parameters?
959,113
4
2009-06-06T06:15:00Z
959,121
8
2009-06-06T06:21:31Z
[ "python", "scope" ]
Before I have the audacity to file a bug report, I thought I'd check my assumptions among wiser Pythonistas here. I encountered a baffling case today, so I whittled it down to a toy example, shown below: ``` #!/usr/bin/env python # -*- coding: UTF-8 -*- """ A little script to demonstrate that a function won't re-init...
This is your problem: ``` def bleedscope(a=[], b=[]): ``` it should be ``` def bleedscope(a=None, b=None): if a is None: a = [] if b is None: b = [] ``` The default parameters are only executed once when the function is parsed, thus using the same 2 lists every time.
Removing starting spaces in Python?
959,215
51
2009-06-06T07:55:12Z
959,216
118
2009-06-06T07:57:22Z
[ "python", "string", "trim" ]
I have a text string that starts with a number of spaces, varying between 2 & 4. What's the easiest & simplest way to remove them ie. remove everything before a certain character?
The [`lstrip()`](http://docs.python.org/library/stdtypes.html#str.lstrip) method will remove leading whitespaces, newline and tab characters on a string beginning: ``` >>> ' hello world!'.lstrip() 'hello world!' ``` **Edit** As balpha pointed out in the comments, in order to remove *only* spaces from the beginni...
Removing starting spaces in Python?
959,215
51
2009-06-06T07:55:12Z
959,218
24
2009-06-06T07:58:37Z
[ "python", "string", "trim" ]
I have a text string that starts with a number of spaces, varying between 2 & 4. What's the easiest & simplest way to remove them ie. remove everything before a certain character?
The function `strip` will remove whitespace from the beginning and end of a string. ``` my_str = " text " my_str = my_str.strip() ``` will set `my_str` to `"text"`.
Parsing numbers in Python
959,412
2
2009-06-06T10:15:20Z
959,425
7
2009-06-06T10:25:34Z
[ "python", "parsing" ]
i want to take inputs like this 10 12 13 14 15 16 .. how to take this input , as two diffrent integers so that i can multiply them in python after every 10 and 12 there is newline
I'm not sure I understood your problem very well, it seems you want to parse two int separated from a space. In python you do: ``` s = raw_input('Insert 2 integers separated by a space: ') a,b = [int(i) for i in s.split(' ')] print a*b ``` Explanation: ``` s = raw_input('Insert 2 integers separated by a space: ') `...
How to generate permutations of a list without "reverse duplicates" in Python using generators
960,557
5
2009-06-06T21:15:22Z
960,730
10
2009-06-06T22:46:24Z
[ "python", "algorithm", "generator", "combinatorics" ]
This is related to question [How to generate all permutations of a list in Python](http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python) How to generate all permutations that *match following criteria*: **if two permutations are reverse of each other (i.e. [1,2,3,4] and [4,3,2...
If you generate permutations in lexicographical order, then you don't need to store anything to work out whether the reverse of a given permutation has already been seen. You just have to lexicographically compare it to its reverse - if it's smaller then return it, if it's larger then skip it. There's probably a more ...
python3.0: imputils
960,646
4
2009-06-06T21:58:16Z
960,665
9
2009-06-06T22:09:39Z
[ "python-3.x", "python" ]
Why was the imputil module removed from python3.0 and what should be used in its place?
According to [PEP 3108](http://www.python.org/dev/peps/pep-3108/#hardly-used-done), it was rarely used, undocumented and never updated to support absolute imports.
python3.0: imputils
960,646
4
2009-06-06T21:58:16Z
960,759
10
2009-06-06T23:04:26Z
[ "python-3.x", "python" ]
Why was the imputil module removed from python3.0 and what should be used in its place?
In Python 3.1, there is a module called [importlib](http://doc.python.org/dev/py3k/library/importlib.html), which should be a superior replacement for imputil.
Python creating a dictionary of lists
960,733
131
2009-06-06T22:47:29Z
960,735
18
2009-06-06T22:49:49Z
[ "python", "dictionary" ]
I want to create a dictionary whose values are lists. For example: ``` { 1: ['1'], 2: ['1','2'], 3: ['2'] } ``` If I do: ``` d = dict() a = ['1', '2'] for i in a: for j in range(int(i), int(i) + 2): d[j].append(i) ``` I get a KeyError, because d[...] isn't a list. In this case, I can add the foll...
Use `setdefault`: ``` d = dict() a = ['1', '2'] for i in a: for j in range(int(i), int(i) + 2): d.setdefault(j, []).append(i) print d # prints {1: ['1'], 2: ['1', '2'], 3: ['2']} ``` The rather oddly-named `setdefault` function says "Get the value with this key, or if that key isn't there, add this val...
Python creating a dictionary of lists
960,733
131
2009-06-06T22:47:29Z
960,748
34
2009-06-06T22:54:33Z
[ "python", "dictionary" ]
I want to create a dictionary whose values are lists. For example: ``` { 1: ['1'], 2: ['1','2'], 3: ['2'] } ``` If I do: ``` d = dict() a = ['1', '2'] for i in a: for j in range(int(i), int(i) + 2): d[j].append(i) ``` I get a KeyError, because d[...] isn't a list. In this case, I can add the foll...
You can build it with list comprehension like this: ``` >>> dict((i, range(int(i), int(i) + 2)) for i in ['1', '2']) {'1': [1, 2], '2': [2, 3]} ``` And for the second part of your question use [defaultdict](http://www.python.org/doc/2.5.2/lib/defaultdict-examples.html) ``` >>> from collections import defaultdict >>>...
Python creating a dictionary of lists
960,733
131
2009-06-06T22:47:29Z
960,753
164
2009-06-06T23:00:39Z
[ "python", "dictionary" ]
I want to create a dictionary whose values are lists. For example: ``` { 1: ['1'], 2: ['1','2'], 3: ['2'] } ``` If I do: ``` d = dict() a = ['1', '2'] for i in a: for j in range(int(i), int(i) + 2): d[j].append(i) ``` I get a KeyError, because d[...] isn't a list. In this case, I can add the foll...
You can use [defaultdict](http://docs.python.org/library/collections.html#collections.defaultdict): ``` >>> from collections import defaultdict >>> d = defaultdict(list) >>> for i in a: ... for j in range(int(i), int(i) + 2): ... d[j].append(i) ... >>> d defaultdict(<type 'list'>, {1: ['1'], 2: ['1', '2'], 3: ['...
Trie (Prefix Tree) in Python
960,963
16
2009-06-07T01:14:07Z
961,039
18
2009-06-07T02:09:25Z
[ "python", "algorithm", "trie" ]
I don't know if this is the place to ask about algorithms. But let's see if I get any answers ... :) If anything is unclear I'm very happy to clarify things. I just implemented a [Trie](http://en.wikipedia.org/wiki/Trie) in python. However, one bit seemed to be more complicated than it ought to (as someone who loves ...
At a glance, it sounds like you've implemented a [Patricia Trie](http://portal.acm.org/citation.cfm?id=321481). This approach also is called path compression in some of the literature. There should be copies of that paper that aren't behind the ACM paywall, which will include an insertion algorithm. There's also anoth...
Python Comet Server
960,969
30
2009-06-07T01:18:21Z
1,216,820
12
2009-08-01T15:27:37Z
[ "python", "cometd", "python-stackless" ]
I am building a web application that has a real-time feed (similar to Facebook's newsfeed) that I want to update via a long-polling mechanism. I understand that with Python, my choices are pretty much to either use Stackless (building from their Comet wsgi example) or Cometd + Twisted. Unfortunately there is very littl...
[Orbited](http://www.orbited.org/) seems as a nice solution. Haven't tried it though. --- ***Update**: things have changed in the last 2.5 years.* We now have websockets in all major browsers, except IE (naturally) and a couple of very good abstractions over it, that provide many methods of emulating real-time commu...
Python Comet Server
960,969
30
2009-06-07T01:18:21Z
1,309,560
8
2009-08-21T00:41:01Z
[ "python", "cometd", "python-stackless" ]
I am building a web application that has a real-time feed (similar to Facebook's newsfeed) that I want to update via a long-polling mechanism. I understand that with Python, my choices are pretty much to either use Stackless (building from their Comet wsgi example) or Cometd + Twisted. Unfortunately there is very littl...
I recommend you use [StreamHub Comet Server](http://www.stream-hub.com/) - its used by a lot of people - personally I use it with a couple of Django sites I run. You will need to write a tiny bit of Java to handle the streaming - I did this using [Jython](http://www.jython.org/). The front-end code is some real simple ...
Get class that defined method
961,048
35
2009-06-07T02:18:12Z
961,057
44
2009-06-07T02:23:02Z
[ "python", "python-2.6", "python-datamodel" ]
How can I get the class that defined a method in Python? I'd want the following example to print "`__main__.FooClass`": ``` class FooClass: def foo_method(self): print "foo" class BarClass(FooClass): pass bar = BarClass() print get_class_that_defined_method(bar.foo_method) ```
``` import inspect def get_class_that_defined_method(meth): for cls in inspect.getmro(meth.im_class): if meth.__name__ in cls.__dict__: return cls return None ```
Reloading module giving NameError: name 'reload' is not defined
961,162
68
2009-06-07T03:55:15Z
961,219
98
2009-06-07T04:41:25Z
[ "python", "python-3.x" ]
I'm trying to reload a module I have already imported in Python 3. I know that you only need to import once and executing the `import` command again won't do anything. Executing `reload(foo)` is giving this error: ``` Traceback (most recent call last): File "(stdin)", line 1, in (module) ... NameError: name '...
[`reload`](https://docs.python.org/2/library/functions.html#reload) is a builtin in Python 2, but not in Python 3, so the error you're seeing is expected. If you truly must reload a module in Python 3, you should use either: * [`importlib.reload`](https://docs.python.org/3/library/importlib.html#importlib.reload) for...
Reloading module giving NameError: name 'reload' is not defined
961,162
68
2009-06-07T03:55:15Z
8,691,152
47
2012-01-01T00:02:09Z
[ "python", "python-3.x" ]
I'm trying to reload a module I have already imported in Python 3. I know that you only need to import once and executing the `import` command again won't do anything. Executing `reload(foo)` is giving this error: ``` Traceback (most recent call last): File "(stdin)", line 1, in (module) ... NameError: name '...
``` import imp imp.reload(script4) ```
Reloading module giving NameError: name 'reload' is not defined
961,162
68
2009-06-07T03:55:15Z
33,409,066
25
2015-10-29T08:19:33Z
[ "python", "python-3.x" ]
I'm trying to reload a module I have already imported in Python 3. I know that you only need to import once and executing the `import` command again won't do anything. Executing `reload(foo)` is giving this error: ``` Traceback (most recent call last): File "(stdin)", line 1, in (module) ... NameError: name '...
***For >= Python3.4:*** ``` import importlib importlib.reload(module) ``` ***For <= Python3.3:*** ``` import imp imp.reload(module) ``` ***For Python2.x:*** Use the in-built `reload()` function. ``` reload(module) ```
Two values from one input in python?
961,263
15
2009-06-07T05:27:53Z
961,300
28
2009-06-07T05:59:45Z
[ "python", "variables", "input" ]
This is somewhat of a simple question and I hate to ask it here, but I can't seem the find the answer anywhere else: is it possible to get multiple values from the user in one line of Python? For instance, in C I can do something like this: `scanf("%d %d", &var1, &var2)`. However, I can't figure out what the Python eq...
The Python way to map ``` printf("Enter two numbers here: "); scanf("%d %d", &var1, &var2) ``` would be ``` var1, var2 = raw_input("Enter two numbers here: ").split() ``` Note that we don't have to explicitly specify `split(' ')` because `split()` uses any whitespace characters as delimiter as default. That means i...
Two values from one input in python?
961,263
15
2009-06-07T05:27:53Z
961,322
8
2009-06-07T06:19:06Z
[ "python", "variables", "input" ]
This is somewhat of a simple question and I hate to ask it here, but I can't seem the find the answer anywhere else: is it possible to get multiple values from the user in one line of Python? For instance, in C I can do something like this: `scanf("%d %d", &var1, &var2)`. However, I can't figure out what the Python eq...
In `Python 2.*`, `input` lets the user enter any expression, e.g. a tuple: ``` >>> a, b = input('Two numbers please (with a comma in between): ') Two numbers please (with a comma in between): 23, 45 >>> print a, b 23 45 ``` In `Python 3.*`, `input` is like `2.*`'s `raw_input`, returning you a string that's just what ...
how to multiply two different array of integers in python?
961,326
2
2009-06-07T06:20:45Z
961,327
7
2009-06-07T06:22:43Z
[ "python" ]
i have taken input in two different lists by splitting a line having integers 1 2 for eg 1 2 3 4 so now i have split it and kept it in lists , and want to multiply them like 1\*3 +2\*4, but when i try to do it , its giving me that it can only multiply integers and not lists !! help here can't multiply sequence by n...
You need: ``` >>> a = [1,2] >>> b = [3,4] >>> sum(i*j for i, j in zip(a,b)) 11 ```
What does the percentage sign mean in Python 3.1
961,344
24
2009-06-07T06:47:03Z
961,351
32
2009-06-07T06:50:49Z
[ "python" ]
In the tutorial there is an example for finding prime numbers. ``` >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... break ... else: ... # loop fell through without finding a factor ... print(n, 'is a...
Modulus operator; gives the remainder of the left value divided by the right value. Like: `3 % 1` would equal zero (since 3 divides evenly by 1) `3 % 2` would equal 1 (since dividing 3 by 2 results in a remainder of 1).
What does the percentage sign mean in Python 3.1
961,344
24
2009-06-07T06:47:03Z
961,365
64
2009-06-07T06:58:52Z
[ "python" ]
In the tutorial there is an example for finding prime numbers. ``` >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... break ... else: ... # loop fell through without finding a factor ... print(n, 'is a...
The % does two things, depending on its arguments. In this case, it acts as the modulo operator, meaning when its arguments are numbers, it divides the first by the second and returns the *remainder*. `34 % 10 == 4` since 34 divided by 10 is three, with a remainder of four. If the first argument is a string, it format...
Converting integer to string in Python?
961,632
649
2009-06-07T10:22:38Z
961,636
48
2009-06-07T10:23:58Z
[ "python" ]
I want to convert an integer to a string in Python. I am typecasting it in vain: ``` t=raw_input() c=[] for j in range(0,int(t)): n=raw_input() a=[] a,b= (int(i) for i in n.split(' ')) d=pow(a,b) d.str() c.append(d[0]) for j in c: print j ``` When I try to convert it to string, it's showin...
Try this: ``` str(i) ```
Converting integer to string in Python?
961,632
649
2009-06-07T10:22:38Z
961,638
1,037
2009-06-07T10:24:15Z
[ "python" ]
I want to convert an integer to a string in Python. I am typecasting it in vain: ``` t=raw_input() c=[] for j in range(0,int(t)): n=raw_input() a=[] a,b= (int(i) for i in n.split(' ')) d=pow(a,b) d.str() c.append(d[0]) for j in c: print j ``` When I try to convert it to string, it's showin...
``` >>> str(10) '10' >>> int('10') 10 ``` [Edit] Links to the documentation: [`int()`](https://docs.python.org/2/library/functions.html#int) [`str()`](https://docs.python.org/2/library/functions.html#str) [Edit] The problem seems to come from this line: `d.str()` Conversion to string is done with the builtin ...
Converting integer to string in Python?
961,632
649
2009-06-07T10:22:38Z
961,641
10
2009-06-07T10:24:40Z
[ "python" ]
I want to convert an integer to a string in Python. I am typecasting it in vain: ``` t=raw_input() c=[] for j in range(0,int(t)): n=raw_input() a=[] a,b= (int(i) for i in n.split(' ')) d=pow(a,b) d.str() c.append(d[0]) for j in c: print j ``` When I try to convert it to string, it's showin...
``` >>> i = 5 >>> s = str(5) >>> print "Hello, world the number is " + s Hello, world the number is 5 ```
Converting integer to string in Python?
961,632
649
2009-06-07T10:22:38Z
961,652
28
2009-06-07T10:30:48Z
[ "python" ]
I want to convert an integer to a string in Python. I am typecasting it in vain: ``` t=raw_input() c=[] for j in range(0,int(t)): n=raw_input() a=[] a,b= (int(i) for i in n.split(' ')) d=pow(a,b) d.str() c.append(d[0]) for j in c: print j ``` When I try to convert it to string, it's showin...
There is not typecast and no type coercion in Python. You have to convert your variable in a explicit way. To convert an object in string you use the `str()` function. It works with any object that has a method called `__str__()` defined. In fact ``` str(a) ``` is equivalent to ``` a.__str__() ``` The same is if y...
Converting integer to string in Python?
961,632
649
2009-06-07T10:22:38Z
961,661
12
2009-06-07T10:32:28Z
[ "python" ]
I want to convert an integer to a string in Python. I am typecasting it in vain: ``` t=raw_input() c=[] for j in range(0,int(t)): n=raw_input() a=[] a,b= (int(i) for i in n.split(' ')) d=pow(a,b) d.str() c.append(d[0]) for j in c: print j ``` When I try to convert it to string, it's showin...
To manage non-integer inputs: ``` number = raw_input() try: value = int(number) except ValueError: value = 0 ``` --- Ok, if I take your latest code and rewrite a bit to get it working with Python: ``` t=raw_input() c=[] for j in range(0,int(t)): n=raw_input() a=[] a,b= (int(i) for i in n.split('...
Converting integer to string in Python?
961,632
649
2009-06-07T10:22:38Z
14,801,285
18
2013-02-10T18:47:04Z
[ "python" ]
I want to convert an integer to a string in Python. I am typecasting it in vain: ``` t=raw_input() c=[] for j in range(0,int(t)): n=raw_input() a=[] a,b= (int(i) for i in n.split(' ')) d=pow(a,b) d.str() c.append(d[0]) for j in c: print j ``` When I try to convert it to string, it's showin...
``` a=2 ``` you can use `str(a)` which gives you a string object of `int(2)`
How to enumerate a list of non-string objects in Python?
962,082
5
2009-06-07T15:18:15Z
962,087
11
2009-06-07T15:20:01Z
[ "python", "loops", "enumeration", "sequence" ]
There is a nice class `Enum` from `enum`, but it only works for strings. I'm currently using: ``` for index in range(len(objects)): # do something with index and objects[index] ``` I guess it's not the optimal solution due to the premature use of `len`. How is it possible to do it more efficiently?
Here is the pythonic way to write this loop: ``` for index, obj in enumerate(objects): # Use index, obj. ``` [`enumerate`](http://docs.python.org/library/functions.html#enumerate) works on any sequence regardless of the types of its elements. It is a builtin function. **Edit:** After running some `timeit` tests u...
How to use numpy with 'None' value in Python?
962,343
21
2009-06-07T17:21:44Z
962,442
11
2009-06-07T18:10:31Z
[ "python", "numpy", "mean" ]
I'd like to calculate the mean of an array in Python in this form: ``` Matrice = [1, 2, None] ``` I'd just like to have my `None` value ignored by the `numpy.mean` calculation but I can't figure out how to do it.
You are looking for [masked arrays](http://docs.scipy.org/doc/numpy/reference/maskedarray.html). Here's an example. ``` import MA a = MA.array([1, 2, None], mask = [0, 0, 1]) print "average =", MA.average(a) ``` Unfortunately, masked arrays aren't thoroughly supported in numpy, so you've got to look around to see wha...
How to pull a random record using Django's ORM?
962,619
109
2009-06-07T19:25:15Z
962,662
8
2009-06-07T19:49:53Z
[ "python", "django", "django-models" ]
I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. I'm using Django 1.0.2. While first 3 of them are easy to pull using django models, last one (random) causes me some trou...
You could create a [manager](http://docs.djangoproject.com/en/dev/topics/db/managers/) on your model to do this sort of thing. To first understand what a manager is, the `Painting.objects` method is a manager that contains `all()`, `filter()`, `get()`, etc. Creating your own manager allows you to pre-filter results and...
How to pull a random record using Django's ORM?
962,619
109
2009-06-07T19:25:15Z
962,672
174
2009-06-07T19:54:50Z
[ "python", "django", "django-models" ]
I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. I'm using Django 1.0.2. While first 3 of them are easy to pull using django models, last one (random) causes me some trou...
Simply use: ``` MyModel.objects.order_by('?').first() ``` It is documented in [QuerySet API](http://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by-fields).
How to pull a random record using Django's ORM?
962,619
109
2009-06-07T19:25:15Z
971,671
23
2009-06-09T18:16:49Z
[ "python", "django", "django-models" ]
I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. I'm using Django 1.0.2. While first 3 of them are easy to pull using django models, last one (random) causes me some trou...
The solutions with order\_by('?')[:N] are extremely slow even for medium-sized tables if you use MySQL (don't know about other databases). `order_by('?')[:N]` will be translated to `SELECT ... FROM ... WHERE ... ORDER BY RAND() LIMIT N` query. It means that for every row in table the RAND() function will be executed,...
How to pull a random record using Django's ORM?
962,619
109
2009-06-07T19:25:15Z
2,118,712
79
2010-01-22T16:27:08Z
[ "python", "django", "django-models" ]
I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. I'm using Django 1.0.2. While first 3 of them are easy to pull using django models, last one (random) causes me some trou...
Using `order_by('?')` will kill the db server on the second day in production. A better way is something like what is described in [Getting a random row from a relational database](http://web.archive.org/web/20110802060451/http://bolddream.com/2010/01/22/getting-a-random-row-from-a-relational-database/). ``` from djan...
Python: changing methods and attributes at runtime
962,962
63
2009-06-07T22:39:01Z
962,966
107
2009-06-07T22:42:51Z
[ "python", "reflection", "runtime" ]
I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that? Oh, and please don't ask why.
This example shows the differences between adding a method to a class and to an instance. ``` >>> class Dog(): ... def __init__(self, name): ... self.name = name ... >>> skip = Dog('Skip') >>> spot = Dog('Spot') >>> def talk(self): ... print 'Hi, my name is ' + self.name ... >>> Dog.talk = talk # a...
Python: changing methods and attributes at runtime
962,962
63
2009-06-07T22:39:01Z
963,199
26
2009-06-08T01:32:40Z
[ "python", "reflection", "runtime" ]
I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that? Oh, and please don't ask why.
A possibly interesting alternative to using `types.MethodType` in: ``` >>> f = types.MethodType(talk, puppy, Dog) >>> puppy.talk = f # add method to specific instance ``` would be to exploit the fact that functions are [descriptors](http://users.rcn.com/python/download/Descriptor.htm): ``` >>> puppy.talk = talk.__ge...
Python: changing methods and attributes at runtime
962,962
63
2009-06-07T22:39:01Z
964,049
39
2009-06-08T09:24:15Z
[ "python", "reflection", "runtime" ]
I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that? Oh, and please don't ask why.
> I wish to create a class in Python that I can add and remove attributes and methods. ``` import types class SpecialClass(object): @classmethod def removeVariable(cls, name): return delattr(cls, name) @classmethod def addMethod(cls, func): return setattr(cls, func.__name__, types.Met...
Python display string multiple times
963,161
40
2009-06-08T01:11:57Z
963,166
78
2009-06-08T01:13:45Z
[ "python" ]
I want to print a character or string like '-' n number of times. Can I do it without using a loop?.. Is there a function like ``` print('-',3) ``` ..which would mean printing the `-` 3 times, like this: ``` --- ```
Python 2.x: ``` print '-' * 3 ``` Python 3.x: ``` print('-' * 3) ```
Zipping dynamic files in App Engine (Python)
963,800
6
2009-06-08T07:38:02Z
963,842
7
2009-06-08T08:01:28Z
[ "python", "google-app-engine", "zipfile" ]
Is there anyway I can zip dynamically generated content, such as a freshly rendered html template, into a zip file using zipfile? There seem to be some examples around for zipping static content, but none for zipping dynamic ones. Or, is it not possible at all? One more question: Is it possible to create a zip file w...
You can add whatever you want to a zip file using [`ZipFile.writestr()`](http://docs.python.org/library/zipfile#zipfile.ZipFile.writestr): ``` my_data = "<html><body><p>Hello, world!</p></body></html>" z.writestr("hello.html", my_data) ``` You can also use sub-folders using `/` (or `os.sep`) as a separator: ``` z.wr...
Zipping dynamic files in App Engine (Python)
963,800
6
2009-06-08T07:38:02Z
964,418
14
2009-06-08T11:16:36Z
[ "python", "google-app-engine", "zipfile" ]
Is there anyway I can zip dynamically generated content, such as a freshly rendered html template, into a zip file using zipfile? There seem to be some examples around for zipping static content, but none for zipping dynamic ones. Or, is it not possible at all? One more question: Is it possible to create a zip file w...
The working code: (for app engine:) ``` output = StringIO.StringIO() z = zipfile.ZipFile(output,'w') my_data = "<html><body><p>Hello, world!</p></body></html>" z.writestr("hello.html", my_data) z.close() self.response.headers["Content-Type"] = "multipart/x-zip" self.response.headers['Content-Disposition'] = "attachme...
How to write Strategy Pattern in Python differently than example in Wikipedia?
963,965
27
2009-06-08T08:58:40Z
964,033
40
2009-06-08T09:18:07Z
[ "python", "design-patterns" ]
In the 2009 Wikipedia entry for the Strategy Pattern, there's a example [written in PHP](http://web.archive.org/web/20090626214649/http://en.wikipedia.org/wiki/Strategy_Pattern#PHP). Most other code samples do something like: ``` a = Context.new(StrategyA.new) a.execute #=> Doing the task the normal way b = Context....
The example in Python is not so different of the others. To mock the PHP script: ``` class StrategyExample: def __init__(self, func=None): if func: self.execute = func def execute(self): print("Original execution") def executeReplacement1(): print("Strategy 1") def executeRe...
How to write Strategy Pattern in Python differently than example in Wikipedia?
963,965
27
2009-06-08T08:58:40Z
964,325
9
2009-06-08T10:53:38Z
[ "python", "design-patterns" ]
In the 2009 Wikipedia entry for the Strategy Pattern, there's a example [written in PHP](http://web.archive.org/web/20090626214649/http://en.wikipedia.org/wiki/Strategy_Pattern#PHP). Most other code samples do something like: ``` a = Context.new(StrategyA.new) a.execute #=> Doing the task the normal way b = Context....
For clarity, I would still use a pseudo-interface: ``` class CommunicationStrategy(object): def execute(self, a, b): raise NotImplementedError('execute') class ConcreteCommunicationStrategyDuck(CommunicationStrategy): def execute(self, a, b): print "Quack Quack" class ConcreteCommunicationStr...
How to write Strategy Pattern in Python differently than example in Wikipedia?
963,965
27
2009-06-08T08:58:40Z
964,345
26
2009-06-08T10:59:30Z
[ "python", "design-patterns" ]
In the 2009 Wikipedia entry for the Strategy Pattern, there's a example [written in PHP](http://web.archive.org/web/20090626214649/http://en.wikipedia.org/wiki/Strategy_Pattern#PHP). Most other code samples do something like: ``` a = Context.new(StrategyA.new) a.execute #=> Doing the task the normal way b = Context....
You're right, the wikipedia example isn't helpful. It conflates two things. 1. **Strategy**. 2. Features of Python that simplify the implementation of **Strategy**. The "there's no need to implement this pattern explicitly" statement is incorrect. You often need to implement **Strategy**, but Python simplifies this by...
How to write Strategy Pattern in Python differently than example in Wikipedia?
963,965
27
2009-06-08T08:58:40Z
8,919,545
30
2012-01-19T00:30:47Z
[ "python", "design-patterns" ]
In the 2009 Wikipedia entry for the Strategy Pattern, there's a example [written in PHP](http://web.archive.org/web/20090626214649/http://en.wikipedia.org/wiki/Strategy_Pattern#PHP). Most other code samples do something like: ``` a = Context.new(StrategyA.new) a.execute #=> Doing the task the normal way b = Context....
Answering an old question for the Googlers who searched "python strategy pattern" and landed here... This pattern is practically non-existent in languages that support first class functions. You may want to consider taking advantage of this feature in Python: ``` def strategy_add(a, b): return a + b def strategy...
how to remove text between <script> and </script> using python?
964,459
5
2009-06-08T11:30:28Z
964,485
25
2009-06-08T11:38:55Z
[ "javascript", "python" ]
how to remove text between `<script>` and `</script>` using python?
You can use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) with this (and other) methods: ``` soup = BeautifulSoup(source.lower()) to_extract = soup.findAll('script') for item in to_extract: item.extract() ``` This actually removes the nodes from the HTML. If you wanted to leave the empty `<script...
Patching classes in Python
964,532
6
2009-06-08T11:53:38Z
964,551
11
2009-06-08T11:57:28Z
[ "python", "class", "monkeypatching" ]
Suppose I have a Python class that I want to add an extra property to. Is there any difference between ``` import path.MyClass MyClass.foo = bar ``` and using something like : ``` import path.MyClass setattr(MyClass, 'foo', bar) ``` ? If not, why do people seem to do the second rather than the first? (Eg. here <h...
The statements are equivalent, but setattr might be used because it's the most dynamic choice of the two (with setattr you can use a variable for the attribute name.) See: <http://docs.python.org/library/functions.html#setattr>
Python - simple reading lines from a pipe
965,210
16
2009-06-08T14:38:32Z
965,226
16
2009-06-08T14:42:52Z
[ "python", "pipe", "producer-consumer" ]
I'm trying to read lines from a pipe and process them, but I'm doing something silly and I can't figure out what. The producer is going to keep producing lines indefinitely, like this: producer.py ``` import time while True: print 'Data' time.sleep(1) ``` The consumer just needs to check for lines periodica...
Some old versions of Windows simulated pipes through files (so they were prone to such problems), but that hasn't been a problem in 10+ years. Try adding a ``` sys.stdout.flush() ``` to the producer after the `print`, and also try to make the producer's stdout unbuffered (by using `python -u`). Of course this does...
Python - simple reading lines from a pipe
965,210
16
2009-06-08T14:38:32Z
965,247
7
2009-06-08T14:47:28Z
[ "python", "pipe", "producer-consumer" ]
I'm trying to read lines from a pipe and process them, but I'm doing something silly and I can't figure out what. The producer is going to keep producing lines indefinitely, like this: producer.py ``` import time while True: print 'Data' time.sleep(1) ``` The consumer just needs to check for lines periodica...
This is about I/O that is bufferized by default with Python. Pass `-u` option to the interpreter to disable this behavior: ``` python -u producer.py | python consumer.py ``` It fixes the problem for me.
What's the official way of storing settings for python programs?
965,694
38
2009-06-08T16:13:02Z
965,795
22
2009-06-08T16:35:37Z
[ "python", "settings" ]
Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information. Are one of these approaches blessed by Guido and/or the Python community more than another?
Depends on the predominant intended audience. If it is programmers who change the file anyway, just use python files like settings.py If it is end users then, think about ini files.
What's the official way of storing settings for python programs?
965,694
38
2009-06-08T16:13:02Z
966,074
8
2009-06-08T17:50:36Z
[ "python", "settings" ]
Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information. Are one of these approaches blessed by Guido and/or the Python community more than another?
Just one more option, PyQt. Qt has a platform independent way of storing settings with the QSettings class. Underneath the hood, on windows it uses the registry and in linux it stores the settings in a hidden conf file. QSettings works very well and is pretty seemless.
What's the official way of storing settings for python programs?
965,694
38
2009-06-08T16:13:02Z
967,036
25
2009-06-08T21:07:31Z
[ "python", "settings" ]
Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information. Are one of these approaches blessed by Guido and/or the Python community more than another?
As many have said, there is no "offical" way. There are, however, many choices. There was [a talk at PyCon](http://pyvideo.org/video/190/pycon-2009--data-storage-in-python---an-overview0) this year about many of the available options.
What's the official way of storing settings for python programs?
965,694
38
2009-06-08T16:13:02Z
6,214,590
14
2011-06-02T12:37:19Z
[ "python", "settings" ]
Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information. Are one of these approaches blessed by Guido and/or the Python community more than another?
I use a shelf ( <http://docs.python.org/library/shelve.html> ): ``` shelf = shelve.open(filename) shelf["users"] = ["David", "Abraham"] shelf.sync() # Save ```
Unicode Problem with SQLAlchemy
966,352
8
2009-06-08T18:50:08Z
966,423
7
2009-06-08T19:08:56Z
[ "python", "unicode", "encoding", "character-encoding", "sqlalchemy" ]
I know I'm having a problem with a conversion from Unicode but I'm not sure where it's happening. I'm extracting data about a recent Eruopean trip from a directory of HTML files. Some of the location names have non-ASCII characters (such as é, ô, ü). I'm getting the data from a string representation of the the file...
Try using a column type of Unicode rather than String for the unicode columns: ``` Base = declarative_base() class Point(Base): __tablename__ = 'points' id = Column(Integer, primary_key=True) pdate = Column(Date) ptime = Column(Time) location = Column(Unicode(32)) weather = Column(String(16)) ...
Unicode Problem with SQLAlchemy
966,352
8
2009-06-08T18:50:08Z
967,144
7
2009-06-08T21:34:59Z
[ "python", "unicode", "encoding", "character-encoding", "sqlalchemy" ]
I know I'm having a problem with a conversion from Unicode but I'm not sure where it's happening. I'm extracting data about a recent Eruopean trip from a directory of HTML files. Some of the location names have non-ASCII characters (such as é, ô, ü). I'm getting the data from a string representation of the the file...
From [sqlalchemy.org](http://www.sqlalchemy.org/CHANGES) See section 0.4.2 > added new flag to String and > create\_engine(), > assert \_unicode=(True|False|'warn'|None). > Defaults to `False` or `None` on > create \_engine() and String, `'warn'` on the Unicode type. When > `True`, > results in all unicode conversion...
Unicode Problem with SQLAlchemy
966,352
8
2009-06-08T18:50:08Z
967,171
10
2009-06-08T21:41:25Z
[ "python", "unicode", "encoding", "character-encoding", "sqlalchemy" ]
I know I'm having a problem with a conversion from Unicode but I'm not sure where it's happening. I'm extracting data about a recent Eruopean trip from a directory of HTML files. Some of the location names have non-ASCII characters (such as é, ô, ü). I'm getting the data from a string representation of the the file...
I found this article that helped explain my troubles somewhat: <http://www.amk.ca/python/howto/unicode#reading-and-writing-unicode-data> I was able to get the desired results by using the 'codecs' module and then changing my program as follows: When opening the file: ``` infile = codecs.open(filename, 'r', encoding...
debug variable in python
966,571
2
2009-06-08T19:35:39Z
966,617
12
2009-06-08T19:44:59Z
[ "python", "google-app-engine" ]
I want to separate the debug outputs from production ones by defining a variable that can be used throughput the module. It cannot be defined in environment. Any suggestions for globals reused across classes in modules? Additionally is there a way to configure this variable flag for telling appengine that dont use this...
Have a look at the [logging module](http://www.python.org/doc/2.5/lib/module-logging.html), which is fully supported by Google App Engine. You can specify logging levels such as debug, warning, error, etc. They will show up in the dev server console, and will also be stored in the request log. If you're after executin...