title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
list |
---|---|---|---|---|---|---|---|---|---|
Map two lists into a dictionary in Python | 209,840 | <p>Imagine that you have:</p>
<pre><code>keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
</code></pre>
<p>What is the simplest way to produce the following dictionary ?</p>
<pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
</code></pre>
<p>This code works, but I'm not really proud of it :</p>
<pre><code>dict = {}
junk = map(lambda k, v: dict.update({k: v}), keys, values)
</code></pre>
| 435 | 2008-10-16T19:05:47Z | 16,750,190 | <p>with Python 3.x, goes for dict comprehensions</p>
<pre><code>keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
dic = {k:v for k,v in zip(keys, values)}
print(dic)
</code></pre>
<p>More on <a href="http://www.python.org/dev/peps/pep-0274/">dict comprehensions here</a>, an example is there:</p>
<pre><code>>>> print {i : chr(65+i) for i in range(4)}
{0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'}
</code></pre>
| 7 | 2013-05-25T13:47:03Z | [
"python",
"dictionary"
] |
Map two lists into a dictionary in Python | 209,840 | <p>Imagine that you have:</p>
<pre><code>keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
</code></pre>
<p>What is the simplest way to produce the following dictionary ?</p>
<pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
</code></pre>
<p>This code works, but I'm not really proud of it :</p>
<pre><code>dict = {}
junk = map(lambda k, v: dict.update({k: v}), keys, values)
</code></pre>
| 435 | 2008-10-16T19:05:47Z | 33,728,822 | <p>A more natural way is to use dictionary comprehension </p>
<pre><code>keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
dict = {keys[i]: values[i] for i in range(len(keys))}
</code></pre>
| 3 | 2015-11-16T05:03:26Z | [
"python",
"dictionary"
] |
Map two lists into a dictionary in Python | 209,840 | <p>Imagine that you have:</p>
<pre><code>keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
</code></pre>
<p>What is the simplest way to produce the following dictionary ?</p>
<pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
</code></pre>
<p>This code works, but I'm not really proud of it :</p>
<pre><code>dict = {}
junk = map(lambda k, v: dict.update({k: v}), keys, values)
</code></pre>
| 435 | 2008-10-16T19:05:47Z | 33,737,067 | <blockquote>
<p>Imagine that you have:</p>
<pre><code>keys = ('name', 'age', 'food')
values = ('Monty', 42, 'spam')
</code></pre>
<p><strong>What is the simplest way to produce the following dictionary ?</strong></p>
<pre><code>dict = {'name' : 'Monty', 'age' : 42, 'food' : 'spam'}
</code></pre>
</blockquote>
<h1>Python 2</h1>
<p>I see some answers mentioning to use <code>izip</code> from <code>itertools</code>, but this goes away in Python 3. However, <code>izip</code> is the best approach for Python 2:</p>
<pre><code>from itertools import izip
new_dict = dict(izip(keys, values))
</code></pre>
<h1>Python 3</h1>
<p>In Python 3, <code>zip</code> becomes the same function that was in the <code>itertools</code> module, so that is simply:</p>
<pre><code>new_dict = dict(zip(keys, values))
</code></pre>
<h1>Python 2.7 and 3, dict comprehension:</h1>
<p>A possible improvement on using the dict constructor is to use the native syntax of a dict comprehension (not a list comprehension, as others have mistakenly put it):</p>
<pre><code>new_dict = {k: v for k, v in zip(keys, values)}
</code></pre>
<p>In all cases:</p>
<pre><code>>>> new_dict
{'age': 42, 'name': 'Monty', 'food': 'spam'}
</code></pre>
<h2>Explanation:</h2>
<p>If we look at the help on <code>dict</code> we see that it takes a variety of forms of arguments:</p>
<pre><code>>>> help(dict)
class dict(object)
| dict() -> new empty dictionary
| dict(mapping) -> new dictionary initialized from a mapping object's
| (key, value) pairs
| dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
| in the keyword argument list. For example: dict(one=1, two=2)
</code></pre>
<p>The optimal approach is to use an iterable while avoiding creating unnecessary data structures. In Python 2, zip creates an unnecessary list:</p>
<pre><code>>>> zip(keys, values)
[('name', 'Monty'), ('age', 42), ('food', 'spam')]
</code></pre>
<p>In Python 3, the equivalent would be:</p>
<pre><code>>>> list(zip(keys, values))
[('name', 'Monty'), ('age', 42), ('food', 'spam')]
</code></pre>
<p>and Python 3's <code>zip</code> merely creates an iterable object:</p>
<pre><code>>>> zip(keys, values)
<zip object at 0x7f0e2ad029c8>
</code></pre>
<p>Since we want to avoid creating unnecessary data structures, we usually want to avoid Python 2's <code>zip</code> (since it creates an unnecessary list).</p>
<h1>Less performant alternatives:</h1>
<p>This is a generator expression being passed to the dict constructor:</p>
<pre><code>generator_expression = ((k, v) for k, v in zip(keys, values))
dict(generator_expression)
</code></pre>
<p>or equivalently:</p>
<pre><code>dict((k, v) for k, v in zip(keys, values))
</code></pre>
<p>And this is a list comprehension being passed to the dict constructor:</p>
<pre><code>dict([(k, v) for k, v in zip(keys, values)])
</code></pre>
<p>In the first two cases, an extra layer of non-operative (thus unnecessary) computation is placed over the zip iterable, and in the case of the list comprehension, an extra list is unnecessarily created. I would expect all of them to be less performant, and certainly not more-so.</p>
<h1>Performance review:</h1>
<p>In 64 bit Python 3.4.3, on Ubuntu 14.04, ordered from fastest to slowest:</p>
<pre><code>>>> min(timeit.repeat(lambda: {k: v for k, v in zip(keys, values)}))
0.7836067057214677
>>> min(timeit.repeat(lambda: dict(zip(keys, values))))
1.0321204089559615
>>> min(timeit.repeat(lambda: {keys[i]: values[i] for i in range(len(keys))}))
1.0714934510178864
>>> min(timeit.repeat(lambda: dict([(k, v) for k, v in zip(keys, values)])))
1.6110592018812895
>>> min(timeit.repeat(lambda: dict((k, v) for k, v in zip(keys, values))))
1.7361853648908436
</code></pre>
| 21 | 2015-11-16T13:54:24Z | [
"python",
"dictionary"
] |
Advanced Python FTP - can I control how ftplib talks to a server? | 210,067 | <p>I need to send a very specific (non-standard) string to an FTP server:</p>
<pre><code>dir "SYS:\IC.ICAMA."
</code></pre>
<p>The case is critical, as are the style of quotes and their content.</p>
<p>Unfortunately, ftplib.dir() seems to use the 'LIST' command rather than 'dir' (and it uses the wrong case for this application).</p>
<p>The FTP server is actually a telephone switch and it's a very non-standard implementation.</p>
<p>I tried using ftplib.sendcmd(), but it also sends 'pasv' as part of the command sequence.</p>
<p>Is there an easy way of issuing specific commands to an FTP server?</p>
| 1 | 2008-10-16T20:03:39Z | 210,158 | <p>Try the following. It is a modification of the original <code>FTP.dir</code> command which uses "dir" instead of "LIST". It gives a "DIR not understood" error with the ftp server I tested it on, but it does send the command you're after. (You will want to remove the print command I used to check that.)</p>
<pre><code>import ftplib
class FTP(ftplib.FTP):
def shim_dir(self, *args):
'''List a directory in long form.
By default list current directory to stdout.
Optional last argument is callback function; all
non-empty arguments before it are concatenated to the
LIST command. (This *should* only be used for a pathname.)'''
cmd = 'dir'
func = None
if args[-1:] and type(args[-1]) != type(''):
args, func = args[:-1], args[-1]
for arg in args:
if arg:
cmd = cmd + (' ' + arg)
print cmd
self.retrlines(cmd, func)
if __name__ == '__main__':
f = FTP('ftp.ncbi.nih.gov')
f.login()
f.shim_dir('"blast"')
</code></pre>
| 4 | 2008-10-16T20:28:12Z | [
"python",
"ftp"
] |
py3k RC-1: "LookupError: unknown encoding: uft-8" | 210,344 | <p>I just installed the first release candidate of Python 3.0 and got this error after typing:</p>
<pre><code>>>> help('modules foo')
</code></pre>
<pre>[...]
LookupError: unknown encoding: uft-8</pre>
<p>Notice that it says <strong>uft</strong>-8 and not <strong>utf</strong>-8</p>
<p>Is this a py3k specific bug or a misconfiguration on my part? I do not have any other versions of Python installed on this French locale Windows XP SP3 machine.</p>
<p><strong>Edit</strong></p>
<p>A <a href="http://bugs.python.org/issue4135?@ok_message=msg%2074871%20created%3Cbr%3Eissue%204135%20created&@template=item" rel="nofollow">bug</a> has been filled by <a href="http://stackoverflow.com/users/22899/alex-coventry">Alex Coventry</a> on October 16th.</p>
| 1 | 2008-10-16T21:13:29Z | 210,395 | <p>Looks like a typo in a config file somewhere, whether in the Py3k package or on your machine. You might try installing the stable final Python 2.6 (which supports 3.0 syntax changes with imports from <code>__future__</code>), and if that works you should probably file a bug report.</p>
| 0 | 2008-10-16T21:34:16Z | [
"python",
"python-3.x"
] |
py3k RC-1: "LookupError: unknown encoding: uft-8" | 210,344 | <p>I just installed the first release candidate of Python 3.0 and got this error after typing:</p>
<pre><code>>>> help('modules foo')
</code></pre>
<pre>[...]
LookupError: unknown encoding: uft-8</pre>
<p>Notice that it says <strong>uft</strong>-8 and not <strong>utf</strong>-8</p>
<p>Is this a py3k specific bug or a misconfiguration on my part? I do not have any other versions of Python installed on this French locale Windows XP SP3 machine.</p>
<p><strong>Edit</strong></p>
<p>A <a href="http://bugs.python.org/issue4135?@ok_message=msg%2074871%20created%3Cbr%3Eissue%204135%20created&@template=item" rel="nofollow">bug</a> has been filled by <a href="http://stackoverflow.com/users/22899/alex-coventry">Alex Coventry</a> on October 16th.</p>
| 1 | 2008-10-16T21:13:29Z | 210,417 | <p>It's not a typo, it's a deliberate error in a test module.</p>
<pre><code>met% pwd
/home/coventry/src/Python-3.0rc1
met% rgrep uft-8 .
./Lib/test/bad_coding.py:# -*- coding: uft-8 -*-
./py3k/Lib/test/bad_coding.py:# -*- coding: uft-8 -*-
</code></pre>
<p>Removing this module causes the <code>help</code> command to fall over in a different way.</p>
<p>It is a bug, however. Someone should file a report.</p>
| 5 | 2008-10-16T21:43:43Z | [
"python",
"python-3.x"
] |
Distributing a stand-alone Python web-based application to non-technical users | 210,461 | <p>I'm writing a web application in Python, intended for use by teachers and pupils in a classroom. It'll run from a hosted website, but I also want people to be able to download a self-contained application they can install locally if they want more performance or they simply won't have an Internet connection available in the classroom.</p>
<p>The users aren't going to be able to manage instructions like "first install Python, then install dependencies, download the .tar.gz archive and type these commands into the command line...". I need to be able to create an all-in-one type installer that can potentially install Python, dependencies (Python-LDAP), some Python code, and register a Python-based web server as a Windows Service.</p>
<p>I've had a look through previous questions, but none quite seem relevant. I'm not concerned about the security of source code (my application will be open source, I'll sell content to go with it), I just need non-technical Windows users to be able to download and use my application with no fuss.</p>
<p>My current thoughts are to use <a href="http://nsis.sourceforge.net/Main_Page" rel="nofollow">NSIS</a> to create an installer that includes Python and Python-LDAP as MSIs, then registers my own simple Python-based web server as a Windows service and puts a shortcut in the start menu / on the desktop linking to <a href="http://localhost" rel="nofollow">http://localhost</a>. Is this doable with NSIS - can NSIS check for currently installed copies of Python, for instance? Is there a better way of doing this - is there a handy framework available that lets me shove my code in a folder and bundle it up to make an installer?</p>
| 5 | 2008-10-16T22:00:41Z | 210,510 | <p>Using NSIS is great (i use it too) but i would suggest using a "packager" like pyinstaller (my personal fav, alternatives bb_freeze, py2exe) to create an exe before the using NSIS</p>
<p>The primary benefit you get by doing this is;
Your download is smaller as you're not bundling the whole Python Standard Lib and extra stuff your app wont need and you get an exe file to boot!</p>
| 4 | 2008-10-16T22:23:47Z | [
"python",
"installer",
"installation"
] |
Distributing a stand-alone Python web-based application to non-technical users | 210,461 | <p>I'm writing a web application in Python, intended for use by teachers and pupils in a classroom. It'll run from a hosted website, but I also want people to be able to download a self-contained application they can install locally if they want more performance or they simply won't have an Internet connection available in the classroom.</p>
<p>The users aren't going to be able to manage instructions like "first install Python, then install dependencies, download the .tar.gz archive and type these commands into the command line...". I need to be able to create an all-in-one type installer that can potentially install Python, dependencies (Python-LDAP), some Python code, and register a Python-based web server as a Windows Service.</p>
<p>I've had a look through previous questions, but none quite seem relevant. I'm not concerned about the security of source code (my application will be open source, I'll sell content to go with it), I just need non-technical Windows users to be able to download and use my application with no fuss.</p>
<p>My current thoughts are to use <a href="http://nsis.sourceforge.net/Main_Page" rel="nofollow">NSIS</a> to create an installer that includes Python and Python-LDAP as MSIs, then registers my own simple Python-based web server as a Windows service and puts a shortcut in the start menu / on the desktop linking to <a href="http://localhost" rel="nofollow">http://localhost</a>. Is this doable with NSIS - can NSIS check for currently installed copies of Python, for instance? Is there a better way of doing this - is there a handy framework available that lets me shove my code in a folder and bundle it up to make an installer?</p>
| 5 | 2008-10-16T22:00:41Z | 463,428 | <p>You can try the <a href="http://bitnami.org/stack/djangostack" rel="nofollow">Bitnami Stack for Django</a> that includes Apache, MySQL,Python, etc in an all-in-one installer. It is free/open source</p>
| 0 | 2009-01-20T22:42:13Z | [
"python",
"installer",
"installation"
] |
I need some help with cursor event handling in python+Tkinter | 210,522 | <p>I'm building a code in which I'd like to be able to generate an event when the user changes the focus of the cursor from an Entry widget to anywhere, for example another entry widget, a button...</p>
<p>So far i only came out with the idea to bind to TAB and mouse click, although if i bind the mouse click to the Entry widget i only get mouse events when inside the Entry widget.</p>
<p>How can i accomplish to generate events for when a widget loses cursor focus?</p>
<p>Any help will be much appreciated!</p>
<p>Thanks in advance!</p>
<p>William.</p>
| 0 | 2008-10-16T22:29:13Z | 211,283 | <p>This isn't specific to tkinter, and it's not focus based, but I got an answer to a similar question here:</p>
<p><a href="http://stackoverflow.com/questions/165495/detecting-mouse-clicks-in-windows-using-python">http://stackoverflow.com/questions/165495/detecting-mouse-clicks-in-windows-using-python</a></p>
<p>I haven't done any tkinter in quite a while, but there seems to be "FocusIn" and "FocusOut" events. You might be able to bind and track these to solve your issue.</p>
<p>From:
<a href="http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm" rel="nofollow">http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm</a></p>
| 0 | 2008-10-17T07:12:44Z | [
"python",
"events",
"cursor",
"tkinter"
] |
I need some help with cursor event handling in python+Tkinter | 210,522 | <p>I'm building a code in which I'd like to be able to generate an event when the user changes the focus of the cursor from an Entry widget to anywhere, for example another entry widget, a button...</p>
<p>So far i only came out with the idea to bind to TAB and mouse click, although if i bind the mouse click to the Entry widget i only get mouse events when inside the Entry widget.</p>
<p>How can i accomplish to generate events for when a widget loses cursor focus?</p>
<p>Any help will be much appreciated!</p>
<p>Thanks in advance!</p>
<p>William.</p>
| 0 | 2008-10-16T22:29:13Z | 225,834 | <p>The events <FocusIn> and <FocusOut> are what you want. Run the following example and you'll see you get focus in and out bindings whether you click or press tab (or shift-tab) when focus is in one of the entry widgets.</p>
<pre><code>from Tkinter import *
def main():
global text
root=Tk()
l1=Label(root,text="Field 1:")
l2=Label(root,text="Field 2:")
t1=Text(root,height=4,width=40)
e1=Entry(root)
e2=Entry(root)
l1.grid(row=0,column=0,sticky="e")
e1.grid(row=0,column=1,sticky="ew")
l2.grid(row=1,column=0,sticky="e")
e2.grid(row=1,column=1,sticky="ew")
t1.grid(row=2,column=0,columnspan=2,sticky="nw")
root.grid_columnconfigure(1,weight=1)
root.grid_rowconfigure(2,weight=1)
root.bind_class("Entry","<FocusOut>",focusOutHandler)
root.bind_class("Entry","<FocusIn>",focusInHandler)
text = t1
root.mainloop()
def focusInHandler(event):
text.insert("end","FocusIn %s\n" % event.widget)
text.see("end")
def focusOutHandler(event):
text.insert("end","FocusOut %s\n" % event.widget)
text.see("end")
if __name__ == "__main__":
main();
</code></pre>
| 4 | 2008-10-22T13:56:48Z | [
"python",
"events",
"cursor",
"tkinter"
] |
Python: unsigned 32 bit bitwise arithmetic | 210,629 | <p>Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.</p>
<p>Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result must be a long in the range [0, 2**32]?</p>
<p>In other words, I need a working Python counterpart to the C bitwise operations between unsigned longs.</p>
<p>EDIT: the specific issue is this:</p>
<pre><code>>>> m = 0xFFFFFF00 # netmask 255.255.255.0
>>> ~m
-4294967041L # wtf?! I want 255
</code></pre>
| 24 | 2008-10-16T23:25:31Z | 210,707 | <pre><code>from numpy import uint32
</code></pre>
| 8 | 2008-10-17T00:04:03Z | [
"python",
"math"
] |
Python: unsigned 32 bit bitwise arithmetic | 210,629 | <p>Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.</p>
<p>Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result must be a long in the range [0, 2**32]?</p>
<p>In other words, I need a working Python counterpart to the C bitwise operations between unsigned longs.</p>
<p>EDIT: the specific issue is this:</p>
<pre><code>>>> m = 0xFFFFFF00 # netmask 255.255.255.0
>>> ~m
-4294967041L # wtf?! I want 255
</code></pre>
| 24 | 2008-10-16T23:25:31Z | 210,740 | <p>You can use <a href="http://docs.python.org/lib/module-ctypes.html">ctypes</a> and its <code>c_uint32</code>:</p>
<pre><code>>>> import ctypes
>>> m = 0xFFFFFF00
>>> ctypes.c_uint32(~m).value
255L
</code></pre>
<p>So what I did here was casting <code>~m</code> to a C 32-bit unsigned integer and retrieving its value back in Python format.</p>
| 47 | 2008-10-17T00:27:26Z | [
"python",
"math"
] |
Python: unsigned 32 bit bitwise arithmetic | 210,629 | <p>Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.</p>
<p>Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result must be a long in the range [0, 2**32]?</p>
<p>In other words, I need a working Python counterpart to the C bitwise operations between unsigned longs.</p>
<p>EDIT: the specific issue is this:</p>
<pre><code>>>> m = 0xFFFFFF00 # netmask 255.255.255.0
>>> ~m
-4294967041L # wtf?! I want 255
</code></pre>
| 24 | 2008-10-16T23:25:31Z | 210,747 | <p>You can mask everything by <code>0xFFFFFFFF</code>:</p>
<pre><code>>>> m = 0xFFFFFF00
>>> allf = 0xFFFFFFFF
>>> ~m & allf
255L
</code></pre>
| 32 | 2008-10-17T00:28:43Z | [
"python",
"math"
] |
Python: unsigned 32 bit bitwise arithmetic | 210,629 | <p>Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.</p>
<p>Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result must be a long in the range [0, 2**32]?</p>
<p>In other words, I need a working Python counterpart to the C bitwise operations between unsigned longs.</p>
<p>EDIT: the specific issue is this:</p>
<pre><code>>>> m = 0xFFFFFF00 # netmask 255.255.255.0
>>> ~m
-4294967041L # wtf?! I want 255
</code></pre>
| 24 | 2008-10-16T23:25:31Z | 211,342 | <p>This is a module that I created a long time ago, and it might be of help to you:</p>
<p><a href="http://pypi.python.org/pypi/IPv4_Utils/0.35" rel="nofollow">IPv4Utils</a></p>
<p>It provides at least a <code>CIDR</code> class with subnet arithmetic. Check the test cases at the end of the module for examples.</p>
| 1 | 2008-10-17T07:45:07Z | [
"python",
"math"
] |
Python: unsigned 32 bit bitwise arithmetic | 210,629 | <p>Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.</p>
<p>Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result must be a long in the range [0, 2**32]?</p>
<p>In other words, I need a working Python counterpart to the C bitwise operations between unsigned longs.</p>
<p>EDIT: the specific issue is this:</p>
<pre><code>>>> m = 0xFFFFFF00 # netmask 255.255.255.0
>>> ~m
-4294967041L # wtf?! I want 255
</code></pre>
| 24 | 2008-10-16T23:25:31Z | 34,951,075 | <p>You could also xor with 0xFFFFFFFF, which is equivalent to the "unsigned complement".</p>
<pre><code>>>> 0xFFFFFF00 ^ 0xFFFFFFFF
255
</code></pre>
| 0 | 2016-01-22T16:10:58Z | [
"python",
"math"
] |
Using os.execvp in Python | 210,978 | <p>I have a question about using <code>os.execvp</code> in Python. I have the following bit of code that's used to create a list of arguments:</p>
<pre>
args = [ "java"
, classpath
, "-Djava.library.path=" + lib_path()
, ea
, "-Xmx1000m"
, "-server"
, "code_swarm"
, params
]
</pre>
<p>When I output a string using <code>" ".join(args)</code> and paste that into my shell prompt, the JVM launches fine, and everything works. Everything works if I use <code>os.system(" ".join(args))</code> in my Python script, too.</p>
<p><em>But</em> the following bit of code does not work:</p>
<pre>os.execvp("java", args)</pre>
I get the following error:
<pre>
Unrecognized option: -classpath [and then the classpath I created, which looks okay]
Could not create the Java virtual machine.
</pre>
<p>So what gives? Why does copying/pasting into the shell or using <code>os.system()</code> work, but not <code>os.execvp()</code>?</p>
| 6 | 2008-10-17T03:04:38Z | 210,982 | <p>If your "classpath" variable contains for instance "-classpath foo.jar", it will not work, since it is thinking the option name is "-classpath foo.jar". Split it in two arguments: [..., "-classpath", classpath, ...].</p>
<p>The other ways (copy and paste and system()) work because the shell splits the command line at the spaces (unless they are escaped or quoted). The command line is in fact passed down to the called program as an array (unlike on Windows), and the JVM is expecting to find an element with only "-classpath" followed by another element with the classpath.</p>
<p>You can see the difference for yourself by calling the following small Python script instead of the JVM:</p>
<pre><code>#!/usr/bin/python
import sys
print sys.argv
</code></pre>
| 11 | 2008-10-17T03:07:53Z | [
"python",
"shell",
"exec"
] |
Using os.execvp in Python | 210,978 | <p>I have a question about using <code>os.execvp</code> in Python. I have the following bit of code that's used to create a list of arguments:</p>
<pre>
args = [ "java"
, classpath
, "-Djava.library.path=" + lib_path()
, ea
, "-Xmx1000m"
, "-server"
, "code_swarm"
, params
]
</pre>
<p>When I output a string using <code>" ".join(args)</code> and paste that into my shell prompt, the JVM launches fine, and everything works. Everything works if I use <code>os.system(" ".join(args))</code> in my Python script, too.</p>
<p><em>But</em> the following bit of code does not work:</p>
<pre>os.execvp("java", args)</pre>
I get the following error:
<pre>
Unrecognized option: -classpath [and then the classpath I created, which looks okay]
Could not create the Java virtual machine.
</pre>
<p>So what gives? Why does copying/pasting into the shell or using <code>os.system()</code> work, but not <code>os.execvp()</code>?</p>
| 6 | 2008-10-17T03:04:38Z | 211,898 | <p>Make sure you aren't relying on shell expansion in your classpath. E.g. "~/my.jar" will get expanded by the shell in an os.system call, but not, I believe in an os.execvp call.</p>
| 0 | 2008-10-17T12:11:04Z | [
"python",
"shell",
"exec"
] |
Create an icon in memory with win32 in python | 211,046 | <p>What's a good way to generate an icon in-memory in python? Right now I'm forced to use pygame to draw the icon, then I save it to disk as an .ico file, and then I load it from disk as an ICO resource...</p>
<p>Something like this:</p>
<pre><code> if os.path.isfile(self.icon):
icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
hicon = win32gui.LoadImage(hinst,
self.icon,
win32con.IMAGE_ICON,
0,
0,
icon_flags)
</code></pre>
<p>...where self.icon is the filename of the icon I created.</p>
<p>Is there any way to do this in memory? EDIT: All I want to do is create an icon with a 2-digit number displayed on it (weather-taskbar style.</p>
| 0 | 2008-10-17T04:07:42Z | 211,110 | <p>You can probably create a object that mimics the python file-object interface.</p>
<p><a href="http://docs.python.org/library/stdtypes.html#bltin-file-objects" rel="nofollow">http://docs.python.org/library/stdtypes.html#bltin-file-objects</a></p>
| 0 | 2008-10-17T04:49:23Z | [
"python",
"windows",
"winapi",
"icons"
] |
Create an icon in memory with win32 in python | 211,046 | <p>What's a good way to generate an icon in-memory in python? Right now I'm forced to use pygame to draw the icon, then I save it to disk as an .ico file, and then I load it from disk as an ICO resource...</p>
<p>Something like this:</p>
<pre><code> if os.path.isfile(self.icon):
icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
hicon = win32gui.LoadImage(hinst,
self.icon,
win32con.IMAGE_ICON,
0,
0,
icon_flags)
</code></pre>
<p>...where self.icon is the filename of the icon I created.</p>
<p>Is there any way to do this in memory? EDIT: All I want to do is create an icon with a 2-digit number displayed on it (weather-taskbar style.</p>
| 0 | 2008-10-17T04:07:42Z | 211,304 | <p>You can use <a href="http://wxpython.org/" rel="nofollow">wxPython</a> for this.</p>
<pre><code>from wx import EmptyIcon
icon = EmptyIcon()
icon.CopyFromBitmap(your_wxBitmap)
</code></pre>
<p>The <a href="http://docs.wxwidgets.org/stable/wx_wxbitmap.html#wxbitmap" rel="nofollow">wxBitmap</a> can be generated in memory using <a href="http://docs.wxwidgets.org/stable/wx_wxmemorydc.html#wxmemorydc" rel="nofollow">wxMemoryDC</a>, look <a href="http://docs.wxwidgets.org/stable/wx_wxdc.html" rel="nofollow">here</a> for operations you can do on a DC.</p>
<p>This icon can then be applied to a wxFrame (a window) or a wxTaskBarIcon using:</p>
<pre><code>frame.SetIcon(icon)
</code></pre>
| 2 | 2008-10-17T07:22:12Z | [
"python",
"windows",
"winapi",
"icons"
] |
Python's __import__ doesn't work as expected | 211,100 | <p>When using <code>__import__</code> with a dotted name, something like: <code>somepackage.somemodule</code>, the module returned isn't <code>somemodule</code>, whatever is returned seems to be mostly empty! what's going on here?</p>
| 40 | 2008-10-17T04:46:08Z | 211,101 | <p>From the python docs on <code>__import__</code>:</p>
<blockquote>
<pre><code>__import__( name[, globals[, locals[, fromlist[, level]]]])
</code></pre>
<p>...</p>
<p>When the name variable is of the form
package.module, normally, the
top-level package (the name up till
the first dot) is returned, not the
module named by name. However, when a
non-empty fromlist argument is given,
the module named by name is returned.
This is done for compatibility with
the bytecode generated for the
different kinds of import statement;
when using "import spam.ham.eggs", the
top-level package spam must be placed
in the importing namespace, but when
using "from spam.ham import eggs", the
spam.ham subpackage must be used to
find the eggs variable. As a
workaround for this behavior, use
getattr() to extract the desired
components. For example, you could
define the following helper:</p>
<pre><code>def my_import(name):
mod = __import__(name)
components = name.split('.')
for comp in components[1:]:
mod = getattr(mod, comp)
return mod
</code></pre>
</blockquote>
<p><strong>To paraphrase:</strong></p>
<p>When you ask for <code>somepackage.somemodule</code>, <code>__import__</code> returns <code>somepackage.__init__.py</code>, which is often empty.</p>
<p>It will return <code>somemodule</code> if you provide <code>fromlist</code> (a list of the variable names inside <code>somemodule</code> you want, which are not actually returned)</p>
<p>You can also, as I did, use the function they suggest.</p>
<p>Note: I asked this question fully intending to answer it myself. There was a big bug in my code, and having misdiagnosed it, it took me a long time to figure it out, so I figured I'd help the SO community out and post the gotcha I ran into here.</p>
| 51 | 2008-10-17T04:46:20Z | [
"python",
"python-import"
] |
Python's __import__ doesn't work as expected | 211,100 | <p>When using <code>__import__</code> with a dotted name, something like: <code>somepackage.somemodule</code>, the module returned isn't <code>somemodule</code>, whatever is returned seems to be mostly empty! what's going on here?</p>
| 40 | 2008-10-17T04:46:08Z | 214,682 | <p>There is something that works as you want it to: <code>twisted.python.reflect.namedAny</code>:</p>
<pre><code>>>> from twisted.python.reflect import namedAny
>>> namedAny("operator.eq")
<built-in function eq>
>>> namedAny("pysqlite2.dbapi2.connect")
<built-in function connect>
>>> namedAny("os")
<module 'os' from '/usr/lib/python2.5/os.pyc'>
</code></pre>
| 7 | 2008-10-18T06:37:19Z | [
"python",
"python-import"
] |
Python's __import__ doesn't work as expected | 211,100 | <p>When using <code>__import__</code> with a dotted name, something like: <code>somepackage.somemodule</code>, the module returned isn't <code>somemodule</code>, whatever is returned seems to be mostly empty! what's going on here?</p>
| 40 | 2008-10-17T04:46:08Z | 5,138,775 | <p>python 2.7 has importlib, dotted paths resolve as expected</p>
<pre><code>import importlib
foo = importlib.import_module('a.dotted.path')
instance = foo.SomeClass()
</code></pre>
| 32 | 2011-02-28T06:08:46Z | [
"python",
"python-import"
] |
Python's __import__ doesn't work as expected | 211,100 | <p>When using <code>__import__</code> with a dotted name, something like: <code>somepackage.somemodule</code>, the module returned isn't <code>somemodule</code>, whatever is returned seems to be mostly empty! what's going on here?</p>
| 40 | 2008-10-17T04:46:08Z | 5,489,623 | <p>For python 2.6, I wrote this snippet:</p>
<pre><code>def import_and_get_mod(str, parent_mod=None):
"""Attempts to import the supplied string as a module.
Returns the module that was imported."""
mods = str.split('.')
child_mod_str = '.'.join(mods[1:])
if parent_mod is None:
if len(mods) > 1:
#First time this function is called; import the module
#__import__() will only return the top level module
return import_and_get_mod(child_mod_str, __import__(str))
else:
return __import__(str)
else:
mod = getattr(parent_mod, mods[0])
if len(mods) > 1:
#We're not yet at the intended module; drill down
return import_and_get_mod(child_mod_str, mod)
else:
return mod
</code></pre>
| 1 | 2011-03-30T17:07:40Z | [
"python",
"python-import"
] |
Python's __import__ doesn't work as expected | 211,100 | <p>When using <code>__import__</code> with a dotted name, something like: <code>somepackage.somemodule</code>, the module returned isn't <code>somemodule</code>, whatever is returned seems to be mostly empty! what's going on here?</p>
| 40 | 2008-10-17T04:46:08Z | 6,957,437 | <p>There is a simpler solution, as explained in the documentation:</p>
<p>If you simply want to import a module (potentially within a package) by name, you can call __import__() and then look it up in sys.modules:</p>
<pre><code>>>> import sys
>>> name = 'foo.bar.baz'
>>> __import__(name)
<module 'foo' from ...>
>>> baz = sys.modules[name]
>>> baz
<module 'foo.bar.baz' from ...>
</code></pre>
| 16 | 2011-08-05T13:54:49Z | [
"python",
"python-import"
] |
Python's __import__ doesn't work as expected | 211,100 | <p>When using <code>__import__</code> with a dotted name, something like: <code>somepackage.somemodule</code>, the module returned isn't <code>somemodule</code>, whatever is returned seems to be mostly empty! what's going on here?</p>
| 40 | 2008-10-17T04:46:08Z | 25,381,926 | <p>The way I did is </p>
<pre><code>foo = __import__('foo', globals(), locals(), ["bar"], -1)
foobar = eval("foo.bar")
</code></pre>
<p>then i can access any content from by </p>
<pre><code>foobar.functionName()
</code></pre>
| 0 | 2014-08-19T11:11:58Z | [
"python",
"python-import"
] |
How to build "Tagging" support using CouchDB? | 211,118 | <p>I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large.
Any other approach?</p>
<pre><code>def by_tag(tag):
return '''
function(doc) {
if (doc.tags.length > 0) {
for (var tag in doc.tags) {
if (doc.tags[tag] == "%s") {
emit(doc.published, doc)
}
}
}
};
''' % tag
</code></pre>
| 4 | 2008-10-17T04:57:22Z | 211,144 | <p>You are very much on the right track with the view. A list of thoughts though:</p>
<p>View generation is incremental. If you're read traffic is greater than you're write traffic, then your views won't cause an issue at all. People that are concerned about this generally shouldn't be. Frame of reference, you should be worried if you're dumping hundreds of records into the view without an update.</p>
<p>Emitting an entire document will slow things down. You should only emit what is necessary for use of the view.</p>
<p>Not sure what the val == "%s" performance would be, but you shouldn't over think things. If there's a tag array you should emit the tags. Granted if you expect a tags array that will contain non-strings, then ignore this.</p>
| 1 | 2008-10-17T05:15:36Z | [
"python",
"couchdb",
"tagging",
"document-oriented-db"
] |
How to build "Tagging" support using CouchDB? | 211,118 | <p>I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large.
Any other approach?</p>
<pre><code>def by_tag(tag):
return '''
function(doc) {
if (doc.tags.length > 0) {
for (var tag in doc.tags) {
if (doc.tags[tag] == "%s") {
emit(doc.published, doc)
}
}
}
};
''' % tag
</code></pre>
| 4 | 2008-10-17T04:57:22Z | 213,138 | <p><em>Disclaimer: I didn't test this and don't know if it can perform better.</em> </p>
<p>Create a single perm view:</p>
<pre><code>function(doc) {
for (var tag in doc.tags) {
emit([tag, doc.published], doc)
}
};
</code></pre>
<p>And query with
_view/your_view/all?startkey=['your_tag_here']&endkey=['your_tag_here', {}]</p>
<p>Resulting JSON structure will be slightly different but you will still get the publish date sorting.</p>
| 7 | 2008-10-17T17:48:37Z | [
"python",
"couchdb",
"tagging",
"document-oriented-db"
] |
How to build "Tagging" support using CouchDB? | 211,118 | <p>I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large.
Any other approach?</p>
<pre><code>def by_tag(tag):
return '''
function(doc) {
if (doc.tags.length > 0) {
for (var tag in doc.tags) {
if (doc.tags[tag] == "%s") {
emit(doc.published, doc)
}
}
}
};
''' % tag
</code></pre>
| 4 | 2008-10-17T04:57:22Z | 216,543 | <p>You can define a single permanent view, as Bahadir suggests. when doing this sort of indexing, though, <em>don't</em> output the doc for each key. Instead, emit([tag, doc.published], null). In current release versions you'd then have to do a separate lookup for each doc, but SVN trunk now has support for specifying "include_docs=True" in the query string and CouchDB will automatically merge the docs into your view for you, without the space overhead.</p>
| 3 | 2008-10-19T15:34:37Z | [
"python",
"couchdb",
"tagging",
"document-oriented-db"
] |
How to build "Tagging" support using CouchDB? | 211,118 | <p>I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large.
Any other approach?</p>
<pre><code>def by_tag(tag):
return '''
function(doc) {
if (doc.tags.length > 0) {
for (var tag in doc.tags) {
if (doc.tags[tag] == "%s") {
emit(doc.published, doc)
}
}
}
};
''' % tag
</code></pre>
| 4 | 2008-10-17T04:57:22Z | 312,181 | <pre><code># Works on CouchDB 0.8.0
from couchdb import Server # http://code.google.com/p/couchdb-python/
byTag = """
function(doc) {
if (doc.type == 'post' && doc.tags) {
doc.tags.forEach(function(tag) {
emit(tag, doc);
});
}
}
"""
def findPostsByTag(self, tag):
server = Server("http://localhost:1234")
db = server['my_table']
return [row for row in db.query(byTag, key = tag)]
</code></pre>
<p>The byTag map function returns the data with each unique tag in the "key", then each post with that tag in <code>value</code>, so when you grab key = "mytag", it will retrieve all posts with the tag "mytag".</p>
<p>I've tested it against about 10 entries and it seems to take about 0.0025 seconds per query, not sure how efficient it is with large data sets..</p>
| 0 | 2008-11-23T05:53:49Z | [
"python",
"couchdb",
"tagging",
"document-oriented-db"
] |
Python Inverse of a Matrix | 211,160 | <p>How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.</p>
| 50 | 2008-10-17T05:30:49Z | 211,174 | <p>You should have a look at <a href="http://www.scipy.org/Tentative_NumPy_Tutorial">numpy</a> if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation.</p>
<pre><code>from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] ) # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] ) # Creates a matrix (like a row vector).
print A.T # Transpose of A.
print A*x # Matrix multiplication of A and x.
print A.I # Inverse of A.
print linalg.solve(A, x) # Solve the linear equation system.
</code></pre>
<p>You can also have a look at the <a href="http://www.python.org/doc/2.5.2/lib/module-array.html">array</a> module, which is a much more efficient implementation of lists when you have to deal with only one data type.</p>
| 93 | 2008-10-17T05:41:42Z | [
"python",
"algorithm",
"matrix",
"linear-algebra",
"matrix-inverse"
] |
Python Inverse of a Matrix | 211,160 | <p>How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.</p>
| 50 | 2008-10-17T05:30:49Z | 213,717 | <p>If you hate numpy, get out RPy and your local copy of R, and use it instead.</p>
<p>(I would also echo to make you you really need to invert the matrix. In R, for example, linalg.solve and the solve() function don't actually do a full inversion, since it is unnecessary.)</p>
| 1 | 2008-10-17T20:25:42Z | [
"python",
"algorithm",
"matrix",
"linear-algebra",
"matrix-inverse"
] |
Python Inverse of a Matrix | 211,160 | <p>How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.</p>
| 50 | 2008-10-17T05:30:49Z | 215,523 | <p>Make sure you really need to invert the matrix. This is often unnecessary and can be numerically unstable. When most people ask how to invert a matrix, they really want to know how to solve Ax = b where A is a matrix and x and b are vectors. It's more efficient and more accurate to use code that solves the equation Ax = b for x directly than to calculate A inverse then multiply the inverse by B. Even if you need to solve Ax = b for many b values, it's not a good idea to invert A. If you have to solve the system for multiple b values, save the Cholesky factorization of A, but don't invert it.</p>
<p>See <a href="http://www.johndcook.com/blog/2010/01/19/dont-invert-that-matrix/">Don't invert that matrix</a>.</p>
| 44 | 2008-10-18T20:12:27Z | [
"python",
"algorithm",
"matrix",
"linear-algebra",
"matrix-inverse"
] |
Python Inverse of a Matrix | 211,160 | <p>How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.</p>
| 50 | 2008-10-17T05:30:49Z | 605,460 | <p>You could calculate the determinant of the matrix which is recursive
and then form the adjoined matrix</p>
<p><a href="http://www.easycalculation.com/matrix/inverse-matrix-tutorial.php">Here is a short tutorial</a></p>
<p>I think this only works for square matrices</p>
<p>Another way of computing these involves gram-schmidt orthogonalization and then transposing the matrix, the transpose of an orthogonalized matrix is its inverse!</p>
| 6 | 2009-03-03T07:46:49Z | [
"python",
"algorithm",
"matrix",
"linear-algebra",
"matrix-inverse"
] |
Python Inverse of a Matrix | 211,160 | <p>How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.</p>
| 50 | 2008-10-17T05:30:49Z | 3,128,931 | <p>It is a pity that the chosen matrix, repeated here again, is either singular or badly conditioned:</p>
<pre><code>A = matrix( [[1,2,3],[11,12,13],[21,22,23]])
</code></pre>
<p>By definition, the inverse of A when multiplied by the matrix A itself must give a unit matrix. The A chosen in the much praised explanation does not do that. In fact just looking at the inverse gives a clue that the inversion did not work correctly. Look at the magnitude of the individual terms - they are very, very big compared with the terms of the original A matrix... </p>
<p>It is remarkable that the humans when picking an example of a matrix so often manage to pick a singular matrix!</p>
<p>I did have a problem with the solution, so looked into it further. On the ubuntu-kubuntu platform, the debian package numpy does not have the matrix and the linalg sub-packages, so in addition to import of numpy, scipy needs to be imported also.</p>
<p>If the diagonal terms of A are multiplied by a large enough factor, say 2, the matrix will most likely cease to be singular or near singular. So </p>
<pre><code>A = matrix( [[2,2,3],[11,24,13],[21,22,46]])
</code></pre>
<p>becomes neither singular nor nearly singular and the example gives meaningful results... When dealing with floating numbers one must be watchful for the effects of inavoidable round off errors.</p>
<p>Thanks for your contribution,</p>
<p>OldAl.</p>
| 9 | 2010-06-27T21:19:14Z | [
"python",
"algorithm",
"matrix",
"linear-algebra",
"matrix-inverse"
] |
Python Inverse of a Matrix | 211,160 | <p>How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.</p>
| 50 | 2008-10-17T05:30:49Z | 21,126,480 | <p>Numpy will be suitable for most people, but you can also do <a href="http://docs.sympy.org/latest/tutorial/matrices.html" rel="nofollow">matrices in Sympy</a></p>
<p>Try running these commands at <a href="http://live.sympy.org/" rel="nofollow">http://live.sympy.org/</a></p>
<pre><code>M = Matrix([[1, 3], [-2, 3]])
M
M**-1
</code></pre>
<p>For fun, try <code>M**(1/2)</code></p>
| 5 | 2014-01-14T23:49:57Z | [
"python",
"algorithm",
"matrix",
"linear-algebra",
"matrix-inverse"
] |
arguments to cryptographic functions | 211,483 | <p>I'm a bit confused that the argument to crypto functions is a string. Should I simply wrap non-string arguments with str() e.g.</p>
<pre><code>hashlib.sha256(str(user_id)+str(expiry_time))
hmac.new(str(random.randbits(256)))
</code></pre>
<p>(ignore for the moment that random.randbits() might not be cryptographically good).
edit: I realise that the hmac example is silly because I'm not storing the key anywhere!</p>
| 0 | 2008-10-17T08:55:21Z | 211,503 | <p>You can.</p>
<p>However, for the HMAC, you actually want to store the key somewhere. Without the key, there is no way for you to verify the hash value later. :-)</p>
| 1 | 2008-10-17T09:03:11Z | [
"python",
"cryptography"
] |
arguments to cryptographic functions | 211,483 | <p>I'm a bit confused that the argument to crypto functions is a string. Should I simply wrap non-string arguments with str() e.g.</p>
<pre><code>hashlib.sha256(str(user_id)+str(expiry_time))
hmac.new(str(random.randbits(256)))
</code></pre>
<p>(ignore for the moment that random.randbits() might not be cryptographically good).
edit: I realise that the hmac example is silly because I'm not storing the key anywhere!</p>
| 0 | 2008-10-17T08:55:21Z | 211,506 | <p>Well, usually hash-functions (and cryptographic functions generally) work on bytes. The Python strings are basically byte-strings. If you want to compute the hash of some object you have to convert it to a string representation. Just make sure to apply the same operation later if you want to check if the hash is correct. And make sure that your string representation doesn't contain any changing data that you don't want to be checked.</p>
<p>Edit: Due to popular request a short reminder that Python unicode strings don't contain bytes but unicode code points. Each unicode code point contains <em>multiple</em> bytes (2 or 4, depending on how the Python interpreter was compiled). Python strings only contain bytes. So Python strings (type <em>str</em>) are the type most similar to an array of bytes.</p>
| 6 | 2008-10-17T09:06:02Z | [
"python",
"cryptography"
] |
arguments to cryptographic functions | 211,483 | <p>I'm a bit confused that the argument to crypto functions is a string. Should I simply wrap non-string arguments with str() e.g.</p>
<pre><code>hashlib.sha256(str(user_id)+str(expiry_time))
hmac.new(str(random.randbits(256)))
</code></pre>
<p>(ignore for the moment that random.randbits() might not be cryptographically good).
edit: I realise that the hmac example is silly because I'm not storing the key anywhere!</p>
| 0 | 2008-10-17T08:55:21Z | 211,509 | <p>Oh and Sha256 isn't really an industrial strength cryptographic function (although unfortunately it's used quite commonly on many sites). It's not a real way to protect passwords or other critical data, but more than good enough for generating temporal tokens</p>
<p>Edit: As mentioned Sha256 needs at least some salt. Without salt, Sha256 has a low barrier to being cracked with a dictionary attack (time-wise) and there are plenty of Rainbow tables to use as well. Personally I'd not use anything less than Blowfish for passwords (but that's because I'm paranoid) </p>
| -1 | 2008-10-17T09:07:01Z | [
"python",
"cryptography"
] |
Using SQLite in a Python program | 211,501 | <p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production.</p>
<p>What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better).</p>
<p>I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn).</p>
<p>Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.</p>
| 13 | 2008-10-17T09:02:12Z | 211,534 | <p>AFAIK an SQLITE database is just a file.
To check if the database exists, check for file existence.</p>
<p>When you open a SQLITE database it will automatically create one if the file that backs it up is not in place.</p>
<p>If you try and open a file as a sqlite3 database that is NOT a database, you will get this:</p>
<p>"sqlite3.DatabaseError: file is encrypted or is not a database"</p>
<p>so check to see if the file exists and also make sure to try and catch the exception in case the file is not a sqlite3 database</p>
| 12 | 2008-10-17T09:23:01Z | [
"python",
"exception",
"sqlite"
] |
Using SQLite in a Python program | 211,501 | <p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production.</p>
<p>What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better).</p>
<p>I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn).</p>
<p>Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.</p>
| 13 | 2008-10-17T09:02:12Z | 211,539 | <p>Doing SQL in overall is horrible in any language I've picked up. SQLalchemy has shown to be easiest from them to use because actual query and committing with it is so clean and absent from troubles.</p>
<p>Here's some basic steps on actually using sqlalchemy in your app, better details can be found from the documentation.</p>
<ul>
<li>provide table definitions and create ORM-mappings</li>
<li>load database</li>
<li>ask it to create tables from the definitions (won't do so if they exist)</li>
<li>create session maker (optional)</li>
<li>create session</li>
</ul>
<p>After creating a session, you can commit and query from the database.</p>
| 3 | 2008-10-17T09:24:13Z | [
"python",
"exception",
"sqlite"
] |
Using SQLite in a Python program | 211,501 | <p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production.</p>
<p>What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better).</p>
<p>I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn).</p>
<p>Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.</p>
| 13 | 2008-10-17T09:02:12Z | 211,541 | <ul>
<li>Sqlite doesn't throw an exception if you create a new database with the same name, it will just connect to it. Since sqlite is a file based database, I suggest you just check for the existence of the file.</li>
<li>About your second problem, to check if a table has been already created, just catch the exception. An exception "sqlite3.OperationalError: table TEST already exists" is thrown if the table already exist.</li>
</ul>
<pre class="lang-python prettyprint-override"><code>import sqlite3
import os
database_name = "newdb.db"
if not os.path.isfile(database_name):
print "the database already exist"
db_connection = sqlite3.connect(database_name)
db_cursor = db_connection.cursor()
try:
db_cursor.execute('CREATE TABLE TEST (a INTEGER);')
except sqlite3.OperationalError, msg:
print msg
</code></pre>
| 4 | 2008-10-17T09:26:07Z | [
"python",
"exception",
"sqlite"
] |
Using SQLite in a Python program | 211,501 | <p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production.</p>
<p>What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better).</p>
<p>I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn).</p>
<p>Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.</p>
| 13 | 2008-10-17T09:02:12Z | 211,562 | <p>As @diciu pointed out, the database file will be created by <a href="http://docs.python.org/library/sqlite3.html#module-sqlite3">sqlite3.connect</a>.
If you want to take a special action when the file is not there, you'll have to explicitly check for existance:</p>
<pre><code>import os
import sqlite3
if not os.path.exists(mydb_path):
#create new DB, create table stocks
con = sqlite3.connect(mydb_path)
con.execute('''create table stocks
(date text, trans text, symbol text, qty real, price real)''')
else:
#use existing DB
con = sqlite3.connect(mydb_path)
...
</code></pre>
| 5 | 2008-10-17T09:40:12Z | [
"python",
"exception",
"sqlite"
] |
Using SQLite in a Python program | 211,501 | <p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production.</p>
<p>What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better).</p>
<p>I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn).</p>
<p>Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.</p>
| 13 | 2008-10-17T09:02:12Z | 211,573 | <p>SQLite automatically creates the database file the first time you try to use it. The SQL statements for creating tables can use <code>IF NOT EXISTS</code> to make the commands only take effect if the table has not been created This way you don't need to check for the database's existence beforehand: SQLite can take care of that for you.</p>
<p>The main thing I would still be worried about is that executing <code>CREATE TABLE IF EXISTS</code> for every web transaction (say) would be inefficient; you can avoid that by having the program keep an (in-memory) variable saying whether it has created the database today, so it runs the <code>CREATE TABLE</code> script once per run. This would still allow for you to delete the database and start over during debugging.</p>
| 7 | 2008-10-17T09:44:53Z | [
"python",
"exception",
"sqlite"
] |
Using SQLite in a Python program | 211,501 | <p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production.</p>
<p>What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better).</p>
<p>I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn).</p>
<p>Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.</p>
| 13 | 2008-10-17T09:02:12Z | 211,660 | <p>Don't make this more complex than it needs to be. The big, independent databases have complex setup and configuration requirements. SQLite is just a file you access with SQL, it's much simpler.</p>
<p>Do the following.</p>
<ol>
<li><p>Add a table to your database for "Components" or "Versions" or "Configuration" or "Release" or something administrative like that. </p>
<p>CREATE TABLE REVISION(
RELEASE_NUMBER CHAR(20)
);</p></li>
<li><p>In your application, connect to your database normally.</p></li>
<li>Execute a simple query against the revision table. Here's what can happen.
<ul>
<li>The query fails to execute: your database doesn't exist, so execute a series of CREATE statements to build it.</li>
<li>The query succeeds but returns no rows or the release number is lower than expected: your database exists, but is out of date. You need to migrate from that release to the current release. Hopefully, you have a sequence of DROP, CREATE and ALTER statements to do this.</li>
<li>The query succeeds, and the release number is the expected value. Do nothing more, your database is configured correctly.</li>
</ul></li>
</ol>
| 28 | 2008-10-17T10:30:02Z | [
"python",
"exception",
"sqlite"
] |
Using SQLite in a Python program | 211,501 | <p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production.</p>
<p>What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better).</p>
<p>I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn).</p>
<p>Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.</p>
| 13 | 2008-10-17T09:02:12Z | 214,623 | <p>Yes, I was nuking out the problem. All I needed to do was check for the file and catch the IOError if it didn't exist.</p>
<p>Thanks for all the other answers. They may come in handy in the future.</p>
| 0 | 2008-10-18T05:19:05Z | [
"python",
"exception",
"sqlite"
] |
Using SQLite in a Python program | 211,501 | <p>I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production.</p>
<p>What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better).</p>
<p>I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn).</p>
<p>Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.</p>
| 13 | 2008-10-17T09:02:12Z | 1,416,903 | <p>See this solution at SourceForge which covers your question in a tutorial manner, with instructive source code :</p>
<p>y_serial.py module :: warehouse Python objects with SQLite</p>
<p>"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data."</p>
<p><a href="http://yserial.sourceforge.net" rel="nofollow">http://yserial.sourceforge.net</a></p>
| 2 | 2009-09-13T05:07:20Z | [
"python",
"exception",
"sqlite"
] |
What is an easy way to create a trivial one-off Python object? | 211,695 | <p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p>
<pre><code>options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False
# Then, elsewhere in the code...
if options.VERBOSE:
...
</code></pre>
<p>Of course I could use a dictionary, but <code>options.VERBOSE</code> is more readable and easier to type than <code>options['VERBOSE']</code>.</p>
<p>I <em>thought</em> that I should be able to do</p>
<pre><code>options = object()
</code></pre>
<p>, since <code>object</code> is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using <code>object()</code> doesn't have a <code>__dict__</code> member, and so one cannot add attributes to it:</p>
<pre><code>options.VERBOSE = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'VERBOSE'
</code></pre>
<p>What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?</p>
| 9 | 2008-10-17T10:47:49Z | 211,774 | <p>The <a href="http://docs.python.org/library/collections.html" rel="nofollow">collections module</a> has grown a <em>namedtuple</em> function in 2.6:</p>
<pre><code>import collections
opt=collections.namedtuple('options','VERBOSE IGNORE_WARNINGS')
myoptions=opt(True, False)
>>> myoptions
options(VERBOSE=True, IGNORE_WARNINGS=False)
>>> myoptions.VERBOSE
True
</code></pre>
<p>A <em>namedtuple</em> is immutable, so you can only assign field values when you create it.</p>
<p>In earlier <em>Python</em> versions, you can create an empty class:</p>
<pre><code>class options(object):
pass
myoptions=options()
myoptions.VERBOSE=True
myoptions.IGNORE_WARNINGS=False
>>> myoptions.IGNORE_WARNINGS,myoptions.VERBOSE
(False, True)
</code></pre>
| 14 | 2008-10-17T11:17:06Z | [
"python"
] |
What is an easy way to create a trivial one-off Python object? | 211,695 | <p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p>
<pre><code>options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False
# Then, elsewhere in the code...
if options.VERBOSE:
...
</code></pre>
<p>Of course I could use a dictionary, but <code>options.VERBOSE</code> is more readable and easier to type than <code>options['VERBOSE']</code>.</p>
<p>I <em>thought</em> that I should be able to do</p>
<pre><code>options = object()
</code></pre>
<p>, since <code>object</code> is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using <code>object()</code> doesn't have a <code>__dict__</code> member, and so one cannot add attributes to it:</p>
<pre><code>options.VERBOSE = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'VERBOSE'
</code></pre>
<p>What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?</p>
| 9 | 2008-10-17T10:47:49Z | 211,918 | <p>I use <a href="http://code.activestate.com/recipes/361668/">attrdict</a>:</p>
<pre><code>class attrdict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
</code></pre>
<p>Depending on your point of view, you probably think it's either a big kludge or quite clever. But whatever you think, it does make for nice looking code, and is compatible with a dict:</p>
<pre><code>>>> ad = attrdict({'foo': 100, 'bar': 200})
>>> ad.foo
100
>>> ad.bar
200
>>> ad.baz = 'hello'
>>> ad.baz
'hello'
>>> ad
{'baz': 'hello', 'foo': 100, 'bar': 200}
>>> isinstance(ad, dict)
True
</code></pre>
| 5 | 2008-10-17T12:19:07Z | [
"python"
] |
What is an easy way to create a trivial one-off Python object? | 211,695 | <p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p>
<pre><code>options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False
# Then, elsewhere in the code...
if options.VERBOSE:
...
</code></pre>
<p>Of course I could use a dictionary, but <code>options.VERBOSE</code> is more readable and easier to type than <code>options['VERBOSE']</code>.</p>
<p>I <em>thought</em> that I should be able to do</p>
<pre><code>options = object()
</code></pre>
<p>, since <code>object</code> is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using <code>object()</code> doesn't have a <code>__dict__</code> member, and so one cannot add attributes to it:</p>
<pre><code>options.VERBOSE = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'VERBOSE'
</code></pre>
<p>What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?</p>
| 9 | 2008-10-17T10:47:49Z | 211,970 | <p>Simplifying <a href="http://stackoverflow.com/questions/211695/what-is-an-easy-way-to-create-a-trivial-one-off-python-object#211918">davraamides's suggestion</a>, one could use the following:</p>
<pre><code>class attrdict2(object):
def __init__(self, *args, **kwargs):
self.__dict__.update(*args, **kwargs)
</code></pre>
<p>which</p>
<ol>
<li><p>Isn't so kludgy.</p></li>
<li><p>Doesn't contaminate the namespace of each object with the standard methods of <code>dict</code>; for example, <code>ad.has_key</code> is not defined for objects of type <code>attrdict2</code>.</p></li>
</ol>
<p>By the way, it is even easier to initialize instances of <code>attrdict</code> or <code>attrdict2</code>:</p>
<pre><code>>>> ad = attrdict2(foo = 100, bar = 200)
</code></pre>
<p>Granted, <code>attrdict2</code> is not compatible with a <code>dict</code>.</p>
<p>If you don't need the magic initialization behavior, you can even use</p>
<pre><code>class attrdict3(object):
pass
ad = attrdict3()
ad.foo = 100
ad.bar = 200
</code></pre>
<p>But I was still hoping for a solution that doesn't require an auxiliary class.</p>
| 2 | 2008-10-17T12:44:22Z | [
"python"
] |
What is an easy way to create a trivial one-off Python object? | 211,695 | <p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p>
<pre><code>options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False
# Then, elsewhere in the code...
if options.VERBOSE:
...
</code></pre>
<p>Of course I could use a dictionary, but <code>options.VERBOSE</code> is more readable and easier to type than <code>options['VERBOSE']</code>.</p>
<p>I <em>thought</em> that I should be able to do</p>
<pre><code>options = object()
</code></pre>
<p>, since <code>object</code> is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using <code>object()</code> doesn't have a <code>__dict__</code> member, and so one cannot add attributes to it:</p>
<pre><code>options.VERBOSE = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'VERBOSE'
</code></pre>
<p>What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?</p>
| 9 | 2008-10-17T10:47:49Z | 212,010 | <p>One can use</p>
<pre><code>class options(object):
VERBOSE = True
IGNORE_WARNINGS = False
options.VERBOSE = False
if options.VERBOSE:
...
</code></pre>
<p>, using the class object itself (not an instance of the class!) as the place to store individual options. This is terse and satisfies all of the requirements, but it seems like a misuse of the class concept. It would also lead to confusion if a user instantiated the <code>options</code> class.</p>
<p>(If multiple instances of the options-holding objects were needed, this would be a very nice solution--the class definition supplies default values, which can be overridden in individual instances.)</p>
| 1 | 2008-10-17T12:58:34Z | [
"python"
] |
What is an easy way to create a trivial one-off Python object? | 211,695 | <p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p>
<pre><code>options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False
# Then, elsewhere in the code...
if options.VERBOSE:
...
</code></pre>
<p>Of course I could use a dictionary, but <code>options.VERBOSE</code> is more readable and easier to type than <code>options['VERBOSE']</code>.</p>
<p>I <em>thought</em> that I should be able to do</p>
<pre><code>options = object()
</code></pre>
<p>, since <code>object</code> is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using <code>object()</code> doesn't have a <code>__dict__</code> member, and so one cannot add attributes to it:</p>
<pre><code>options.VERBOSE = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'VERBOSE'
</code></pre>
<p>What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?</p>
| 9 | 2008-10-17T10:47:49Z | 212,144 | <p>The absolutely simplest class to do the job is:</p>
<pre><code>class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
</code></pre>
<p>It can be later used as:</p>
<pre><code>john = Struct(name='john doe', salary=34000)
print john.salary
</code></pre>
<p><code>namedtuple</code> (as another commented suggested) is a more advanced class that gives you more functionality. If you're still using Python 2.5, the implementation 2.6's <code>namedtuple</code> is based on can be found at <a href="http://code.activestate.com/recipes/500261/" rel="nofollow">http://code.activestate.com/recipes/500261/</a></p>
| 1 | 2008-10-17T13:37:37Z | [
"python"
] |
What is an easy way to create a trivial one-off Python object? | 211,695 | <p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p>
<pre><code>options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False
# Then, elsewhere in the code...
if options.VERBOSE:
...
</code></pre>
<p>Of course I could use a dictionary, but <code>options.VERBOSE</code> is more readable and easier to type than <code>options['VERBOSE']</code>.</p>
<p>I <em>thought</em> that I should be able to do</p>
<pre><code>options = object()
</code></pre>
<p>, since <code>object</code> is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using <code>object()</code> doesn't have a <code>__dict__</code> member, and so one cannot add attributes to it:</p>
<pre><code>options.VERBOSE = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'VERBOSE'
</code></pre>
<p>What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?</p>
| 9 | 2008-10-17T10:47:49Z | 212,187 | <p>If you insist on not having to define a class, you can abuse some existing classes. Most objects belong to "new-style" classes which don't have a dict, but functions can have arbitrary attributes:</p>
<pre><code>>>> x = lambda: 0 # any function will do
>>> x.foo = 'bar'
>>> x.bar = 0
>>> x.xyzzy = x
>>> x.foo
'bar'
>>> x.bar
0
>>> x.xyzzy
<function <lambda> at 0x6cf30>
</code></pre>
<p>One problem is that functions already have some attributes, so dir(x) is a little messy:</p>
<pre><code>>>> dir(x)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__',
'__get__', '__getattribute__', '__hash__', '__init__',
'__module__', '__name__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', 'foo',
'func_closure', 'func_code', 'func_defaults', 'func_dict',
'func_doc', 'func_globals', 'func_name', 'xyzzy']
</code></pre>
| 6 | 2008-10-17T13:46:37Z | [
"python"
] |
What is an easy way to create a trivial one-off Python object? | 211,695 | <p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p>
<pre><code>options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False
# Then, elsewhere in the code...
if options.VERBOSE:
...
</code></pre>
<p>Of course I could use a dictionary, but <code>options.VERBOSE</code> is more readable and easier to type than <code>options['VERBOSE']</code>.</p>
<p>I <em>thought</em> that I should be able to do</p>
<pre><code>options = object()
</code></pre>
<p>, since <code>object</code> is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using <code>object()</code> doesn't have a <code>__dict__</code> member, and so one cannot add attributes to it:</p>
<pre><code>options.VERBOSE = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'VERBOSE'
</code></pre>
<p>What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?</p>
| 9 | 2008-10-17T10:47:49Z | 212,299 | <p>Given your requirements, I'd say the custom class is your best bet:</p>
<pre><code>class options(object):
VERBOSE = True
IGNORE_WARNINGS = True
if options.VERBOSE:
# ...
</code></pre>
<p>To be complete, another approach would be using a separate module, i.e. <code>options.py</code> to encapsulate your option defaults.</p>
<p><code>options.py</code>:</p>
<pre><code>VERBOSE = True
IGNORE_WARNINGS = True
</code></pre>
<p>Then, in <code>main.py</code>:</p>
<pre><code>import options
if options.VERBOSE:
# ...
</code></pre>
<p>This has the feature of removing some clutter from your script. The default values are easy to find and change, as they are cordoned off in their own module. If later your application has grown, you can easily access the options from other modules.</p>
<p>This is a pattern that I frequently use, and would heartily recommend if you don't mind your application growing larger than a single module. Or, start with a custom class, and expand to a module later if your app grows to multiple modules.</p>
| 8 | 2008-10-17T14:10:03Z | [
"python"
] |
What is an easy way to create a trivial one-off Python object? | 211,695 | <p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p>
<pre><code>options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False
# Then, elsewhere in the code...
if options.VERBOSE:
...
</code></pre>
<p>Of course I could use a dictionary, but <code>options.VERBOSE</code> is more readable and easier to type than <code>options['VERBOSE']</code>.</p>
<p>I <em>thought</em> that I should be able to do</p>
<pre><code>options = object()
</code></pre>
<p>, since <code>object</code> is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using <code>object()</code> doesn't have a <code>__dict__</code> member, and so one cannot add attributes to it:</p>
<pre><code>options.VERBOSE = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'VERBOSE'
</code></pre>
<p>What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?</p>
| 9 | 2008-10-17T10:47:49Z | 212,357 | <p>Just make a module called Options.py, and import it. Put your default options values in there as global variables.</p>
| 3 | 2008-10-17T14:23:15Z | [
"python"
] |
What is an easy way to create a trivial one-off Python object? | 211,695 | <p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p>
<pre><code>options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False
# Then, elsewhere in the code...
if options.VERBOSE:
...
</code></pre>
<p>Of course I could use a dictionary, but <code>options.VERBOSE</code> is more readable and easier to type than <code>options['VERBOSE']</code>.</p>
<p>I <em>thought</em> that I should be able to do</p>
<pre><code>options = object()
</code></pre>
<p>, since <code>object</code> is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using <code>object()</code> doesn't have a <code>__dict__</code> member, and so one cannot add attributes to it:</p>
<pre><code>options.VERBOSE = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'VERBOSE'
</code></pre>
<p>What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?</p>
| 9 | 2008-10-17T10:47:49Z | 212,959 | <p>Why not just use <a href="http://docs.python.org/library/optparse.html#module-optparse" rel="nofollow">optparse</a>:</p>
<pre><code>from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
(options, args) = parser.parse_args()
file = options.filename
if options.quiet == True:
[...]
</code></pre>
| 7 | 2008-10-17T16:56:19Z | [
"python"
] |
What is an easy way to create a trivial one-off Python object? | 211,695 | <p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p>
<pre><code>options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False
# Then, elsewhere in the code...
if options.VERBOSE:
...
</code></pre>
<p>Of course I could use a dictionary, but <code>options.VERBOSE</code> is more readable and easier to type than <code>options['VERBOSE']</code>.</p>
<p>I <em>thought</em> that I should be able to do</p>
<pre><code>options = object()
</code></pre>
<p>, since <code>object</code> is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using <code>object()</code> doesn't have a <code>__dict__</code> member, and so one cannot add attributes to it:</p>
<pre><code>options.VERBOSE = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'VERBOSE'
</code></pre>
<p>What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?</p>
| 9 | 2008-10-17T10:47:49Z | 216,453 | <p>As best practices go, you're really better off with one of the options in <a href="http://stackoverflow.com/questions/211695/what-is-an-easy-way-to-create-a-trivial-one-off-python-object#212299">David Eyk's answer</a>. </p>
<p>However, to answer your question, you can create a one-off class using the <code>type</code> function:</p>
<pre><code>options = type('Options', (object,), { 'VERBOSE': True })()
options.IGNORE_WARNINGS = False
</code></pre>
<p>Note that you can provide an initial dictionary, or just leave it empty .</p>
<pre><code>Options = type('Options', (object,), {})
options = Options()
options.VERBOSE = True
options.IGNORE_WARNINGS = False
</code></pre>
<p>Not very pythonic.</p>
| 4 | 2008-10-19T13:54:18Z | [
"python"
] |
What is an easy way to create a trivial one-off Python object? | 211,695 | <p>I would like to create a trivial one-off Python object to hold some command-line options. I would like to do something like this:</p>
<pre><code>options = ??????
options.VERBOSE = True
options.IGNORE_WARNINGS = False
# Then, elsewhere in the code...
if options.VERBOSE:
...
</code></pre>
<p>Of course I could use a dictionary, but <code>options.VERBOSE</code> is more readable and easier to type than <code>options['VERBOSE']</code>.</p>
<p>I <em>thought</em> that I should be able to do</p>
<pre><code>options = object()
</code></pre>
<p>, since <code>object</code> is the base type of all class objects and therefore should be something like a class with no attributes. But it doesn't work, because an object created using <code>object()</code> doesn't have a <code>__dict__</code> member, and so one cannot add attributes to it:</p>
<pre><code>options.VERBOSE = True
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'VERBOSE'
</code></pre>
<p>What is the simplest "pythonic" way to create an object that can be used this way, preferably without having to create an extra helper class?</p>
| 9 | 2008-10-17T10:47:49Z | 6,465,039 | <p>simple object and named tuples are the way to go</p>
| -2 | 2011-06-24T08:09:38Z | [
"python"
] |
Turning a GqlQuery result set into a python dictionary | 212,125 | <p>Let's say I have a model like this</p>
<pre><code>class Foo(db.Model):
id = db.StringProperty()
bar = db.StringProperty()
baz = db.StringProperty()
</code></pre>
<p>And I'm going a GqlQuery like this</p>
<pre><code>foos = db.GqlQuery("SELECT * FROM Foo")
</code></pre>
<p><strong>I want to take the results of the GqlQuery and turn into some sort of JSON string that I can manipulate from different languages.</strong></p>
<p><hr /></p>
<p>Here's how I'm doing it now</p>
<ol>
<li><p>Add a method to the <strong>Foo</strong> class that converts it into a dictionary</p>
<pre><code>def toDict(self):
return {
'id': self.id,
'bar': self.bar,
'baz': self'baz
}
</code></pre></li>
<li><p>Loop through the GqlQuery results and manually add each Foo instance to a dictionary</p>
<pre><code>fooDict = {}
for foo in foos:
fooDict[foo.id] = foo.toDict()
return simplejson.dumps(fooDict)
</code></pre></li>
</ol>
<p><hr /></p>
<p>My approach above works but it feels kind of gross.</p>
<p>Is there a cleaner, more "Pythonic" way to handle this?</p>
<p><strong>The end format doesn't have to be exactly what I've done above. It just has to be something that converts nicely to JSON so I can deal with it from Javascript/PHP/whatever.</strong></p>
| 3 | 2008-10-17T13:34:03Z | 212,351 | <p>I can't do too much better than that, but here are a couple of ideas:</p>
<pre><code>class Foo:
id = db.StringProperty() # etc.
json_attrs = 'id bar baz'.split()
# Depending on how easy it is to identify string properties, there
# might also be a way to assign json_attrs programmatically after the
# definition of Foo, like this
Foo.json_attrs = [attr for attr in dir(Foo)
if isStringProperty(getattr(Foo, attr))]
fooDict=dict((foo.id,dict(getattr(foo, attr)
for attr in Foo.json_attrs))
for foo in foos)
</code></pre>
| 1 | 2008-10-17T14:21:25Z | [
"python",
"google-app-engine",
"gqlquery"
] |
Turning a GqlQuery result set into a python dictionary | 212,125 | <p>Let's say I have a model like this</p>
<pre><code>class Foo(db.Model):
id = db.StringProperty()
bar = db.StringProperty()
baz = db.StringProperty()
</code></pre>
<p>And I'm going a GqlQuery like this</p>
<pre><code>foos = db.GqlQuery("SELECT * FROM Foo")
</code></pre>
<p><strong>I want to take the results of the GqlQuery and turn into some sort of JSON string that I can manipulate from different languages.</strong></p>
<p><hr /></p>
<p>Here's how I'm doing it now</p>
<ol>
<li><p>Add a method to the <strong>Foo</strong> class that converts it into a dictionary</p>
<pre><code>def toDict(self):
return {
'id': self.id,
'bar': self.bar,
'baz': self'baz
}
</code></pre></li>
<li><p>Loop through the GqlQuery results and manually add each Foo instance to a dictionary</p>
<pre><code>fooDict = {}
for foo in foos:
fooDict[foo.id] = foo.toDict()
return simplejson.dumps(fooDict)
</code></pre></li>
</ol>
<p><hr /></p>
<p>My approach above works but it feels kind of gross.</p>
<p>Is there a cleaner, more "Pythonic" way to handle this?</p>
<p><strong>The end format doesn't have to be exactly what I've done above. It just has to be something that converts nicely to JSON so I can deal with it from Javascript/PHP/whatever.</strong></p>
| 3 | 2008-10-17T13:34:03Z | 212,682 | <p>Take a look at <a href="http://code.google.com/p/googleappengine/source/browse/trunk/google/appengine/api/datastore.py" rel="nofollow">google.appengine.api.datastore</a>. It's the lower level datastore API that google.appengine.ext.db builds on, and it returns Entity objects, which subclass dict. You can query it using GQL with <a href="http://code.google.com/p/googleappengine/source/browse/trunk/google/appengine/ext/gql/__init__.py" rel="nofollow">google.appengine.ext.gql</a>, or (my personal preference) use the Query class, which avoids the need for you to construct text strings for the GQL parser to parse. The Query class in api.datastore behaves exactly like the one <a href="http://code.google.com/appengine/docs/datastore/queryclass.html" rel="nofollow">documented here</a> (but returns the lower level Entity objects instead of Model instances).</p>
<p>As an example, your query above can be reformulated as "datastore.Query("Foo").all()".</p>
| 2 | 2008-10-17T15:37:18Z | [
"python",
"google-app-engine",
"gqlquery"
] |
Turning a GqlQuery result set into a python dictionary | 212,125 | <p>Let's say I have a model like this</p>
<pre><code>class Foo(db.Model):
id = db.StringProperty()
bar = db.StringProperty()
baz = db.StringProperty()
</code></pre>
<p>And I'm going a GqlQuery like this</p>
<pre><code>foos = db.GqlQuery("SELECT * FROM Foo")
</code></pre>
<p><strong>I want to take the results of the GqlQuery and turn into some sort of JSON string that I can manipulate from different languages.</strong></p>
<p><hr /></p>
<p>Here's how I'm doing it now</p>
<ol>
<li><p>Add a method to the <strong>Foo</strong> class that converts it into a dictionary</p>
<pre><code>def toDict(self):
return {
'id': self.id,
'bar': self.bar,
'baz': self'baz
}
</code></pre></li>
<li><p>Loop through the GqlQuery results and manually add each Foo instance to a dictionary</p>
<pre><code>fooDict = {}
for foo in foos:
fooDict[foo.id] = foo.toDict()
return simplejson.dumps(fooDict)
</code></pre></li>
</ol>
<p><hr /></p>
<p>My approach above works but it feels kind of gross.</p>
<p>Is there a cleaner, more "Pythonic" way to handle this?</p>
<p><strong>The end format doesn't have to be exactly what I've done above. It just has to be something that converts nicely to JSON so I can deal with it from Javascript/PHP/whatever.</strong></p>
| 3 | 2008-10-17T13:34:03Z | 214,766 | <p><a href="http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55" rel="nofollow">http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55</a></p>
<p>The encoder method will solve your GQL-to-JSON needs nicely. I'd recommend getting rid of some of the excessive datetime options....out time as an epoch? really?</p>
| 0 | 2008-10-18T08:41:26Z | [
"python",
"google-app-engine",
"gqlquery"
] |
Turning a GqlQuery result set into a python dictionary | 212,125 | <p>Let's say I have a model like this</p>
<pre><code>class Foo(db.Model):
id = db.StringProperty()
bar = db.StringProperty()
baz = db.StringProperty()
</code></pre>
<p>And I'm going a GqlQuery like this</p>
<pre><code>foos = db.GqlQuery("SELECT * FROM Foo")
</code></pre>
<p><strong>I want to take the results of the GqlQuery and turn into some sort of JSON string that I can manipulate from different languages.</strong></p>
<p><hr /></p>
<p>Here's how I'm doing it now</p>
<ol>
<li><p>Add a method to the <strong>Foo</strong> class that converts it into a dictionary</p>
<pre><code>def toDict(self):
return {
'id': self.id,
'bar': self.bar,
'baz': self'baz
}
</code></pre></li>
<li><p>Loop through the GqlQuery results and manually add each Foo instance to a dictionary</p>
<pre><code>fooDict = {}
for foo in foos:
fooDict[foo.id] = foo.toDict()
return simplejson.dumps(fooDict)
</code></pre></li>
</ol>
<p><hr /></p>
<p>My approach above works but it feels kind of gross.</p>
<p>Is there a cleaner, more "Pythonic" way to handle this?</p>
<p><strong>The end format doesn't have to be exactly what I've done above. It just has to be something that converts nicely to JSON so I can deal with it from Javascript/PHP/whatever.</strong></p>
| 3 | 2008-10-17T13:34:03Z | 259,334 | <p>You can use web2py on GAE and do:</p>
<pre><code>db.define_table('foo',SQLField('bar'),SQLField('baz'))
rows=db(db.foo.id>0).select()
### rows is a list, rows.response is a list of tuples
for row in rows: print dict(row)
</code></pre>
<p>Runs on Oracle, Postgresql, Mssql, mysql, etc... too.</p>
| -1 | 2008-11-03T17:15:14Z | [
"python",
"google-app-engine",
"gqlquery"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 212,413 | <p>Why not look at the code for bisect_left/right and adapt it to suit your purpose.</p>
<p>like this:</p>
<pre class="lang-py prettyprint-override"><code>def binary_search(a, x, lo=0, hi=None):
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
midval = a[mid]
if midval < x:
lo = mid+1
elif midval > x:
hi = mid
else:
return mid
return -1
</code></pre>
| 51 | 2008-10-17T14:36:49Z | [
"python",
"binary-search",
"bisection"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 212,541 | <p>If you just want to see if it's present, try turning the list into a dict:</p>
<pre><code># Generate a list
l = [n*n for n in range(1000)]
# Convert to dict - doesn't matter what you map values to
d = dict((x, 1) for x in l)
count = 0
for n in range(1000000):
# Compare with "if n in l"
if n in d:
count += 1
</code></pre>
<p>On my machine, "if n in l" took 37 seconds, while "if n in d" took 0.4 seconds.</p>
| 3 | 2008-10-17T15:03:30Z | [
"python",
"binary-search",
"bisection"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 212,971 | <p>This is a little off-topic (since Moe's answer seems complete to the OP's question), but it might be worth looking at the complexity for your whole procedure from end to end. If you're storing thing in a sorted lists (which is where a binary search would help), and then just checking for existence, you're incurring (worst-case, unless specified):</p>
<p><strong>Sorted Lists</strong></p>
<ul>
<li>O( n log n) to initially create the list (if it's unsorted data. O(n), if it's sorted )</li>
<li>O( log n) lookups (this is the binary search part)</li>
<li>O( n ) insert / delete (might be O(1) or O(log n) average case, depending on your pattern)</li>
</ul>
<p>Whereas with a <a href="http://docs.python.org/library/stdtypes.html#set"><code>set()</code></a>, you're incurring</p>
<ul>
<li>O(n) to create</li>
<li>O(1) lookup</li>
<li>O(1) insert / delete</li>
</ul>
<p>The thing a sorted list really gets you are "next", "previous", and "ranges" (including inserting or deleting ranges), which are O(1) or O(|range|), given a starting index. If you aren't using those sorts of operations often, then storing as sets, and sorting for display might be a better deal overall. <a href="http://docs.python.org/library/stdtypes.html#set"><code>set()</code></a> incurs very little additional overhead in python. </p>
| 32 | 2008-10-17T16:59:57Z | [
"python",
"binary-search",
"bisection"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 213,834 | <p>Using a dict wouldn't like double your memory usage unless the objects you're storing are really tiny, since the values are only pointers to the actual objects:</p>
<pre><code>>>> a = 'foo'
>>> b = [a]
>>> c = [a]
>>> b[0] is c[0]
True
</code></pre>
<p>In that example, 'foo' is only stored once. Does that make a difference for you? And exactly how many items are we talking about anyway?</p>
| 1 | 2008-10-17T21:01:17Z | [
"python",
"binary-search",
"bisection"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 530,397 | <p>Simplest is to use <a href="http://docs.python.org/library/bisect.html" rel="nofollow">bisect</a> and check one position back to see if the item is there:</p>
<pre><code>def binary_search(a,x,lo=0,hi=-1):
i = bisect(a,x,lo,hi)
if i == 0:
return -1
elif a[i-1] == x:
return i-1
else:
return -1
</code></pre>
| 10 | 2009-02-09T22:41:14Z | [
"python",
"binary-search",
"bisection"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 2,233,940 | <pre><code>from bisect import bisect_left
def binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi
hi = hi if hi is not None else len(a) # hi defaults to len(a)
pos = bisect_left(a,x,lo,hi) # find insertion position
return (pos if pos != hi and a[pos] == x else -1) # don't walk off the end
</code></pre>
| 170 | 2010-02-10T02:05:27Z | [
"python",
"binary-search",
"bisection"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 5,763,198 | <p>It might be worth mentioning that the bisect docs now provide searching examples:
<a href="http://docs.python.org/library/bisect.html#searching-sorted-lists">http://docs.python.org/library/bisect.html#searching-sorted-lists</a></p>
<p>(Raising ValueError instead of returning -1 or None is more pythonic â list.index() does it, for example. But of course you can adapt the examples to your needs.)</p>
| 10 | 2011-04-23T08:36:45Z | [
"python",
"binary-search",
"bisection"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 10,390,802 | <p><p>This code works with integer lists in a recursive way. Looks for the simplest case scenario, which is: list length less than 2. It means the answer is already there and a test is performed to check for the correct answer.
If not, a middle value is set and tested to be the correct, if not bisection is performed by calling again the function, but setting middle value as the upper or lower limit, by shifting it to the left or right</p></p>
<pre>
def binary_search(intList, intValue, lowValue, highValue):
if(highValue - lowValue) < 2:
return intList[lowValue] == intValue or intList[highValue] == intValue
middleValue = lowValue + ((highValue - lowValue)/2)
if intList[middleValue] == intValue:
return True
if intList[middleValue] > intValue:
return binary_search(intList, intValue, lowValue, middleValue - 1)
return binary_search(intList, intValue, middleValue + 1, highValue)
</pre>
| 1 | 2012-04-30T21:25:18Z | [
"python",
"binary-search",
"bisection"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 10,555,553 | <pre><code>'''
Only used if set your position as global
'''
position #set global
def bst(array,taget): # just pass the array and target
global position
low = 0
high = len(array)
while low <= high:
mid = (lo+hi)//2
if a[mid] == target:
position = mid
return -1
elif a[mid] < target:
high = mid+1
else:
low = mid-1
return -1
</code></pre>
<p>I guess this is much better and effective. please correct me :) . Thank you</p>
| 0 | 2012-05-11T16:54:56Z | [
"python",
"binary-search",
"bisection"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 10,578,346 | <p>Check out the examples on Wikipedia <a href="http://en.wikipedia.org/wiki/Binary_search_algorithm" rel="nofollow">http://en.wikipedia.org/wiki/Binary_search_algorithm</a></p>
<pre><code>def binary_search(a, key, imin=0, imax=None):
if imax is None:
# if max amount not set, get the total
imax = len(a) - 1
while imin <= imax:
# calculate the midpoint
mid = (imin + imax)//2
midval = a[mid]
# determine which subarray to search
if midval < key:
# change min index to search upper subarray
imin = mid + 1
elif midval > key:
# change max index to search lower subarray
imax = mid - 1
else:
# return index number
return mid
raise ValueError
</code></pre>
| 1 | 2012-05-14T06:26:24Z | [
"python",
"binary-search",
"bisection"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 18,678,361 | <p>Dave Abrahams' solution is good. Although I have would have done it minimalistic:</p>
<pre><code>def binary_search(L, x):
i = bisect.bisect_left(L, x)
if i == len(L) or L[i] != x:
return -1
return i
</code></pre>
| 1 | 2013-09-07T22:08:09Z | [
"python",
"binary-search",
"bisection"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 18,681,876 | <p>I agree that <a href="http://stackoverflow.com/a/2233940/2484194">@DaveAbrahams's answer</a> using the bisect module is the correct approach. He did not mention one important detail in his answer.</p>
<p>From the <a href="http://docs.python.org/2/library/bisect.html#searching-sorted-lists">docs</a> <code>bisect.bisect_left(a, x, lo=0, hi=len(a))</code></p>
<p>The bisection module does not require the search array to be precomputed ahead of time. You can just present the endpoints to the <code>bisect.bisect_left</code> instead of it using the defaults of <code>0</code> and <code>len(a)</code>.</p>
<p>Even more important for my use, looking for a value X such that the error of a given function is minimized. To do that, I needed a way to have the bisect_left's algorithm call my computation instead. This is really simple.</p>
<p>Just provide an object that defines <code>__getitem__</code> as <code>a</code></p>
<p>For example, we could use the bisect algorithm to find a square root with arbitrary precision!</p>
<pre><code>import bisect
class sqrt_array(object):
def __init__(self, digits):
self.precision = float(10**(digits))
def __getitem__(self, key):
return (key/self.precision)**2.0
sa = sqrt_array(4)
# "search" in the range of 0 to 10 with a "precision" of 0.0001
index = bisect.bisect_left(sa, 7, 0, 10*10**4)
print 7**0.5
print index/(10**4.0)
</code></pre>
| 6 | 2013-09-08T08:28:55Z | [
"python",
"binary-search",
"bisection"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 20,007,672 | <p>While there's no explicit binary search algorithm in Python, there is a module - <code>bisect</code> - designed to find the insertion point for an element in a sorted list using a binary search. This can be "tricked" into performing a binary search. The biggest advantage of this is the same advantage most library code has - it's high-performing, well-tested and just works (binary searches in particular can be <a href="http://en.wikipedia.org/wiki/Binary_search_algorithm#Implementation_issues" rel="nofollow">quite difficult to implement successfully</a> - particularly if edge cases aren't carefully considered).</p>
<h1>Basic Types</h1>
<p>For basic types like Strings or ints it's pretty easy - all you need is the <code>bisect</code> module and a sorted list:</p>
<pre><code>>>> import bisect
>>> names = ['bender', 'fry', 'leela', 'nibbler', 'zoidberg']
>>> bisect.bisect_left(names, 'fry')
1
>>> keyword = 'fry'
>>> x = bisect.bisect_left(names, keyword)
>>> names[x] == keyword
True
>>> keyword = 'arnie'
>>> x = bisect.bisect_left(names, keyword)
>>> names[x] == keyword
False
</code></pre>
<p>You can also use this to find duplicates:</p>
<pre><code>...
>>> names = ['bender', 'fry', 'fry', 'fry', 'leela', 'nibbler', 'zoidberg']
>>> keyword = 'fry'
>>> leftIndex = bisect.bisect_left(names, keyword)
>>> rightIndex = bisect.bisect_right(names, keyword)
>>> names[leftIndex:rightIndex]
['fry', 'fry', 'fry']
</code></pre>
<p>Obviously you could just return the index rather than the value at that index if desired.</p>
<h1>Objects</h1>
<p>For custom types or objects, things are a little bit trickier: you have to make sure to implement rich comparison methods to get bisect to compare correctly.</p>
<pre><code>>>> import bisect
>>> class Tag(object): # a simple wrapper around strings
... def __init__(self, tag):
... self.tag = tag
... def __lt__(self, other):
... return self.tag < other.tag
... def __gt__(self, other):
... return self.tag > other.tag
...
>>> tags = [Tag('bender'), Tag('fry'), Tag('leela'), Tag('nibbler'), Tag('zoidbe
rg')]
>>> key = Tag('fry')
>>> leftIndex = bisect.bisect_left(tags, key)
>>> rightIndex = bisect.bisect_right(tags, key)
>>> print([tag.tag for tag in tags[leftIndex:rightIndex]])
['fry']
</code></pre>
<p>This should work in at least Python 2.7 -> 3.3</p>
| 2 | 2013-11-15T18:03:48Z | [
"python",
"binary-search",
"bisection"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 20,827,948 | <p>This is right from the manual:</p>
<p><a href="http://docs.python.org/2/library/bisect.html">http://docs.python.org/2/library/bisect.html</a></p>
<p>8.5.1. Searching Sorted Lists</p>
<p>The above bisect() functions are useful for finding insertion points but can be tricky or awkward to use for common searching tasks. The following five functions show how to transform them into the standard lookups for sorted lists:</p>
<pre><code>def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError
</code></pre>
<p>So with the slight modification your code should be:</p>
<pre><code>def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
return -1
</code></pre>
| 5 | 2013-12-29T17:20:44Z | [
"python",
"binary-search",
"bisection"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 27,843,077 | <ul>
<li><code>s</code> is a list. </li>
<li><code>binary(s, 0, len(s) - 1, find)</code> is the initial call.</li>
<li><p>Function returns an index of the queried item. If there is no such item it returns <code>-1</code>.</p>
<pre><code>def binary(s,p,q,find):
if find==s[(p+q)/2]:
return (p+q)/2
elif p==q-1 or p==q:
if find==s[q]:
return q
else:
return -1
elif find < s[(p+q)/2]:
return binary(s,p,(p+q)/2,find)
elif find > s[(p+q)/2]:
return binary(s,(p+q)/2+1,q,find)
</code></pre></li>
</ul>
| 0 | 2015-01-08T15:01:25Z | [
"python",
"binary-search",
"bisection"
] |
Binary search (bisection) in Python | 212,358 | <p>Is there a library function that performs binary search on a list/tuple and return the position of the item if found and 'False' (-1, None, etc.) if not?</p>
<p>I found the functions bisect_left/right in the <a href="http://docs.python.org/library/bisect.html">bisect module</a>, but they still return a position even if the item is not in the list. That's perfectly fine for their intended usage, but I just want to know if an item is in the list or not (don't want to insert anything).</p>
<p>I thought of using <code>bisect_left</code> and then checking if the item at that position is equal to what I'm searching, but that seems cumbersome (and I also need to do bounds checking if the number can be larger than the largest number in my list). If there is a nicer method I'd like to know about it.</p>
<p><strong>Edit</strong> To clarify what I need this for: I'm aware that a dictionary would be very well suited for this, but I'm trying to keep the memory consumption as low as possible. My intended usage would be a sort of double-way look-up table. I have in the table a list of values and I need to be able to access the values based on their index. And also I want to be able to find the index of a particular value or None if the value is not in the list.</p>
<p>Using a dictionary for this would be the fastest way, but would (approximately) double the memory requirements.</p>
<p>I was asking this question thinking that I may have overlooked something in the Python libraries. It seems I'll have to write my own code, as Moe suggested.</p>
| 129 | 2008-10-17T14:23:17Z | 30,385,777 | <p>This one is:</p>
<ul>
<li>not recursive (which makes it more <strong>memory-efficient</strong> than most recursive approaches)</li>
<li>actually <strong>working</strong></li>
<li>fast since it <strong>runs without any unnecessary <em>if's</em> and conditions</strong></li>
<li><strong>based on a mathematical assertion</strong> that <em>the floor of (low + high)/2</em> is always smaller than <em>high</em> where <em>low</em> is the lower limit and <em>high</em> is the upper limit.</li>
<li>tested :D</li>
</ul>
<hr>
<pre><code>def binsearch(t, key, low = 0, high = len(t) - 1):
# bisecting the range
while low < high:
mid = (low + high)//2
if t[mid] < key:
low = mid + 1
else:
high = mid
# at this point 'low' should point at the place
# where the value of 'key' is possibly stored.
return low if t[low] == key else -1
</code></pre>
| 2 | 2015-05-21T23:02:52Z | [
"python",
"binary-search",
"bisection"
] |
Opening a handle to a device in Python on Windows | 212,715 | <p>I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax:</p>
<pre class="lang-c prettyprint-override"><code> #define DRIVERNAME "\\\\.\\giveio"
HANDLE h = CreateFile(DRIVERNAME,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
</code></pre>
<p>but this does not seem to work in Python - I just get a "The specified path is invalid" error, for both</p>
<pre><code>f = os.open("\\\\.\\giveio", os.O_RDONLY)
</code></pre>
<p>and </p>
<pre><code>f = os.open("//./giveio", os.O_RDONLY)
</code></pre>
<p>Why doesn't this do the same thing?</p>
<p><strong>Edited</strong> to hopefully reduce confusion of ideas (thanks Will).
I did verify that the device driver is running via the batch files that come with AVRdude.</p>
<p><strong>Further edited</strong> to clarify SamB's bounty.</p>
| 12 | 2008-10-17T15:47:40Z | 214,066 | <p>You're question is very confusing to say the least. </p>
<p>1> The code you pasted is using a trick to communicate with the driver using its 'DOSNAME' i.e.</p>
<pre><code>\\.\DRIVERNAME
</code></pre>
<p>2> Have you created & loaded the 'giveio' driver ?</p>
<p>The reason the driver handles this calls is because of this</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms806162.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms806162.aspx</a></p>
| 2 | 2008-10-17T22:38:41Z | [
"python",
"windows",
"device"
] |
Opening a handle to a device in Python on Windows | 212,715 | <p>I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax:</p>
<pre class="lang-c prettyprint-override"><code> #define DRIVERNAME "\\\\.\\giveio"
HANDLE h = CreateFile(DRIVERNAME,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
</code></pre>
<p>but this does not seem to work in Python - I just get a "The specified path is invalid" error, for both</p>
<pre><code>f = os.open("\\\\.\\giveio", os.O_RDONLY)
</code></pre>
<p>and </p>
<pre><code>f = os.open("//./giveio", os.O_RDONLY)
</code></pre>
<p>Why doesn't this do the same thing?</p>
<p><strong>Edited</strong> to hopefully reduce confusion of ideas (thanks Will).
I did verify that the device driver is running via the batch files that come with AVRdude.</p>
<p><strong>Further edited</strong> to clarify SamB's bounty.</p>
| 12 | 2008-10-17T15:47:40Z | 214,727 | <p>I'm not sure if that's possible. As an alternative, you could write a C/C++ program that does all that kernel space work for you and interface with it in Python via <a href="http://www.python.org/doc/2.5.2/lib/module-subprocess.html" rel="nofollow">the subprocess module</a> or <a href="http://www.language-binding.net/" rel="nofollow">Python C/C++ bindings</a> (and <a href="http://wiki.cacr.caltech.edu/danse/index.php/Writing_C_extensions_for_Python" rel="nofollow">another link</a> for that).</p>
| 1 | 2008-10-18T07:54:21Z | [
"python",
"windows",
"device"
] |
Opening a handle to a device in Python on Windows | 212,715 | <p>I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax:</p>
<pre class="lang-c prettyprint-override"><code> #define DRIVERNAME "\\\\.\\giveio"
HANDLE h = CreateFile(DRIVERNAME,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
</code></pre>
<p>but this does not seem to work in Python - I just get a "The specified path is invalid" error, for both</p>
<pre><code>f = os.open("\\\\.\\giveio", os.O_RDONLY)
</code></pre>
<p>and </p>
<pre><code>f = os.open("//./giveio", os.O_RDONLY)
</code></pre>
<p>Why doesn't this do the same thing?</p>
<p><strong>Edited</strong> to hopefully reduce confusion of ideas (thanks Will).
I did verify that the device driver is running via the batch files that come with AVRdude.</p>
<p><strong>Further edited</strong> to clarify SamB's bounty.</p>
| 12 | 2008-10-17T15:47:40Z | 214,867 | <p>I don't know anything about Python, but I do know a bit about drivers. You're not trying to 'open a file in kernel space' at all - you're just trying to open a handle to a device which happens to be made to look a bit like opening a file.</p>
<p>CreateFile is a user-mode function, and everything you're doing here is user-mode, not kernel mode.</p>
<p>As xenon says, your call may be failing because you haven't loaded the driver yet, or because whatever Python call you're using to do the CreateFile is not passing the write parameters in.</p>
<p>I've never used giveio.sys myself, but personally I would establish that it was loaded correctly by using 'C' or C++ (or some pre-written app) before I tried to get it working via Python.</p>
| 3 | 2008-10-18T10:32:02Z | [
"python",
"windows",
"device"
] |
Opening a handle to a device in Python on Windows | 212,715 | <p>I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax:</p>
<pre class="lang-c prettyprint-override"><code> #define DRIVERNAME "\\\\.\\giveio"
HANDLE h = CreateFile(DRIVERNAME,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
</code></pre>
<p>but this does not seem to work in Python - I just get a "The specified path is invalid" error, for both</p>
<pre><code>f = os.open("\\\\.\\giveio", os.O_RDONLY)
</code></pre>
<p>and </p>
<pre><code>f = os.open("//./giveio", os.O_RDONLY)
</code></pre>
<p>Why doesn't this do the same thing?</p>
<p><strong>Edited</strong> to hopefully reduce confusion of ideas (thanks Will).
I did verify that the device driver is running via the batch files that come with AVRdude.</p>
<p><strong>Further edited</strong> to clarify SamB's bounty.</p>
| 12 | 2008-10-17T15:47:40Z | 218,562 | <p>Solution: in python you have to use win32file.CreateFile() instead of open(). Thanks everyone for telling me what I was trying to do, it helped me find the answer!</p>
| 5 | 2008-10-20T14:07:25Z | [
"python",
"windows",
"device"
] |
Opening a handle to a device in Python on Windows | 212,715 | <p>I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax:</p>
<pre class="lang-c prettyprint-override"><code> #define DRIVERNAME "\\\\.\\giveio"
HANDLE h = CreateFile(DRIVERNAME,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
</code></pre>
<p>but this does not seem to work in Python - I just get a "The specified path is invalid" error, for both</p>
<pre><code>f = os.open("\\\\.\\giveio", os.O_RDONLY)
</code></pre>
<p>and </p>
<pre><code>f = os.open("//./giveio", os.O_RDONLY)
</code></pre>
<p>Why doesn't this do the same thing?</p>
<p><strong>Edited</strong> to hopefully reduce confusion of ideas (thanks Will).
I did verify that the device driver is running via the batch files that come with AVRdude.</p>
<p><strong>Further edited</strong> to clarify SamB's bounty.</p>
| 12 | 2008-10-17T15:47:40Z | 5,870,770 | <p>There are 2 ways to do this.</p>
<p>The first way is using the win32 python bindings</p>
<pre><code>h = win32file.CreateFile
</code></pre>
<p>Or using ctypes</p>
| 2 | 2011-05-03T14:11:26Z | [
"python",
"windows",
"device"
] |
Opening a handle to a device in Python on Windows | 212,715 | <p>I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax:</p>
<pre class="lang-c prettyprint-override"><code> #define DRIVERNAME "\\\\.\\giveio"
HANDLE h = CreateFile(DRIVERNAME,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
</code></pre>
<p>but this does not seem to work in Python - I just get a "The specified path is invalid" error, for both</p>
<pre><code>f = os.open("\\\\.\\giveio", os.O_RDONLY)
</code></pre>
<p>and </p>
<pre><code>f = os.open("//./giveio", os.O_RDONLY)
</code></pre>
<p>Why doesn't this do the same thing?</p>
<p><strong>Edited</strong> to hopefully reduce confusion of ideas (thanks Will).
I did verify that the device driver is running via the batch files that come with AVRdude.</p>
<p><strong>Further edited</strong> to clarify SamB's bounty.</p>
| 12 | 2008-10-17T15:47:40Z | 5,891,868 | <p>It sounds to me like you're asking why os.open is not magically equal to calling CreateFile with a very specific set of parameters. Kostya's answer is practical in that it tells you that you can use the Win32 python bindings to call CreateFile which is a Win32 API, directly.</p>
<p>Anything other than doing direct CreateFile/readFile/writeFile IO is going to introduce another layer on top (the python file objects and their behaviours) that restricts you to the parameters that os.open supports. os.open creates a python file object, which is not exactly the same thing, and not intended to provide all of Win32 CreateFile's options.</p>
<p>That means, for example, that no exact analog of GENERIC_READ, or OPEN_EXISTING, or FILE_ATTRIBUTE_NORMAL are guaranteed to exist.</p>
<p>My best guess is that os.open is not intended to replace direct calls to CreateFile, for such odd purposes as the one you're using it for.</p>
<p>If you can read C, why not open up the sources for python and read the implementation of os.open. If you really must go through os.open, you're going to find out what parameters to pass to it, so that in the end, os.open's implementation (in C) calls CreateFile in Win32 API with the correct parameters above. All of that seems more like work, than just using Kostya's suggestion.</p>
| 2 | 2011-05-05T01:59:00Z | [
"python",
"windows",
"device"
] |
Keyboard interruptable blocking queue in Python | 212,797 | <p>It seems</p>
<pre><code>import Queue
Queue.Queue().get(timeout=10)
</code></pre>
<p>is keyboard interruptible (ctrl-c) whereas</p>
<pre><code>import Queue
Queue.Queue().get()
</code></pre>
<p>is not. I could always create a loop;</p>
<pre><code>import Queue
q = Queue()
while True:
try:
q.get(timeout=1000)
except Queue.Empty:
pass
</code></pre>
<p>but this seems like a strange thing to do.</p>
<p>So, is there a way of getting an indefinitely waiting but keyboard interruptible Queue.get()?</p>
| 11 | 2008-10-17T16:10:51Z | 212,975 | <p><code>Queue</code> objects have this behavior because they lock using <code>Condition</code> objects form the <code>threading</code> module. So your solution is really the only way to go.</p>
<p>However, if you really want a <code>Queue</code> method that does this, you can monkeypatch the <code>Queue</code> class. For example:</p>
<pre><code>def interruptable_get(self):
while True:
try:
return self.get(timeout=1000)
except Queue.Empty:
pass
Queue.interruptable_get = interruptable_get
</code></pre>
<p>This would let you say</p>
<pre><code>q.interruptable_get()
</code></pre>
<p>instead of</p>
<pre><code>interruptable_get(q)
</code></pre>
<p>although monkeypatching is generally discouraged by the Python community in cases such as these, since a regular function seems just as good.</p>
| 5 | 2008-10-17T17:01:03Z | [
"python",
"multithreading",
"concurrency",
"python-2.x"
] |
Keyboard interruptable blocking queue in Python | 212,797 | <p>It seems</p>
<pre><code>import Queue
Queue.Queue().get(timeout=10)
</code></pre>
<p>is keyboard interruptible (ctrl-c) whereas</p>
<pre><code>import Queue
Queue.Queue().get()
</code></pre>
<p>is not. I could always create a loop;</p>
<pre><code>import Queue
q = Queue()
while True:
try:
q.get(timeout=1000)
except Queue.Empty:
pass
</code></pre>
<p>but this seems like a strange thing to do.</p>
<p>So, is there a way of getting an indefinitely waiting but keyboard interruptible Queue.get()?</p>
| 11 | 2008-10-17T16:10:51Z | 216,719 | <p>This may not apply to your use case at all. But I've successfully used this pattern in several cases: (sketchy and likely buggy, but you get the point).</p>
<pre><code>STOP = object()
def consumer(q):
while True:
x = q.get()
if x is STOP:
return
consume(x)
def main()
q = Queue()
c=threading.Thread(target=consumer,args=[q])
try:
run_producer(q)
except KeybordInterrupt:
q.enqueue(STOP)
c.join()
</code></pre>
| 4 | 2008-10-19T17:40:36Z | [
"python",
"multithreading",
"concurrency",
"python-2.x"
] |
Using django-rest-interface | 212,941 | <p>I have a django application that I'd like to add some rest interfaces to. I've seen <a href="http://code.google.com/p/django-rest-interface/">http://code.google.com/p/django-rest-interface/</a> but it seems to be pretty simplistic. For instance it doesn't seem to have a way of enforcing security. How would I go about limiting what people can view and manipulate through the rest interface? Normally I'd put this kind of logic in my views. Is this the right place or should I be moving some more logic down into the model? Alternatively is there a better library out there or do I need to roll my own?</p>
| 20 | 2008-10-17T16:53:23Z | 214,383 | <p>Well, from the look of things, there's an <code>authentication</code> parameter to <code>Collection</code>. (see this example: <a href="http://django-rest-interface.googlecode.com/svn/trunk/django_restapi_tests/examples/authentication.py" rel="nofollow">authentication.py</a>)</p>
<p>Second, (even if Django doesn't have it yet,) there should probably be a middleware that does CSRF/XSRF form checking. (Oh, there seems to <a href="http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib-csrf" rel="nofollow">be one</a>.) You should also be able to use the <a href="http://docs.djangoproject.com/en/dev/topics/auth/#topics-auth" rel="nofollow"><code>login_required</code> and <code>permission_required</code> decorators</a> in the urls.py.</p>
| 3 | 2008-10-18T01:52:44Z | [
"python",
"django",
"rest"
] |
Using django-rest-interface | 212,941 | <p>I have a django application that I'd like to add some rest interfaces to. I've seen <a href="http://code.google.com/p/django-rest-interface/">http://code.google.com/p/django-rest-interface/</a> but it seems to be pretty simplistic. For instance it doesn't seem to have a way of enforcing security. How would I go about limiting what people can view and manipulate through the rest interface? Normally I'd put this kind of logic in my views. Is this the right place or should I be moving some more logic down into the model? Alternatively is there a better library out there or do I need to roll my own?</p>
| 20 | 2008-10-17T16:53:23Z | 214,946 | <p>Even with the Authentication parameter, you don't have fine-grained control over what people can do. The current implementation of the Django-REST interface doesn't track the user information, so you don't have this information available for doing fine-grained authorization checks.</p>
<p>See <a href="http://code.google.com/p/django-rest-interface/issues/detail?id=32" rel="nofollow">Issue #32</a>.</p>
<p>However, it's relatively easy to extend it to add some features. I use a lot of subclasses to add features.</p>
<p>Updating the request with login information, however, is tricky in Django. Rather than do that, I leave the information in the Collection.</p>
<p>Right now, I'd estimate that between patches and subclasses, what I've written is about as big as rolling my own RESTful view functions. </p>
<p>Django-REST, however, gracefully and neatly handles HTTP Digest Authentication. I don't look forward to replacing theirs with some kind of decorator for my Django view functions.</p>
<p>[Maybe we should open a source forge project and work out a clean replacement?]</p>
| 3 | 2008-10-18T11:49:51Z | [
"python",
"django",
"rest"
] |
Using django-rest-interface | 212,941 | <p>I have a django application that I'd like to add some rest interfaces to. I've seen <a href="http://code.google.com/p/django-rest-interface/">http://code.google.com/p/django-rest-interface/</a> but it seems to be pretty simplistic. For instance it doesn't seem to have a way of enforcing security. How would I go about limiting what people can view and manipulate through the rest interface? Normally I'd put this kind of logic in my views. Is this the right place or should I be moving some more logic down into the model? Alternatively is there a better library out there or do I need to roll my own?</p>
| 20 | 2008-10-17T16:53:23Z | 996,423 | <p>I would look into using django-piston <a href="http://bitbucket.org/jespern/django-piston/wiki/Home">http://bitbucket.org/jespern/django-piston/wiki/Home</a> application if security is your main concern. </p>
<p>I have used django-rest-interface in the past, its reliable and though simple can be quite powerful, however django-piston seems more flexible going forward.</p>
| 12 | 2009-06-15T14:28:37Z | [
"python",
"django",
"rest"
] |
Using django-rest-interface | 212,941 | <p>I have a django application that I'd like to add some rest interfaces to. I've seen <a href="http://code.google.com/p/django-rest-interface/">http://code.google.com/p/django-rest-interface/</a> but it seems to be pretty simplistic. For instance it doesn't seem to have a way of enforcing security. How would I go about limiting what people can view and manipulate through the rest interface? Normally I'd put this kind of logic in my views. Is this the right place or should I be moving some more logic down into the model? Alternatively is there a better library out there or do I need to roll my own?</p>
| 20 | 2008-10-17T16:53:23Z | 11,989,130 | <p>Please do have a look at django-rest-framework, I just stepped over from tastypie to this new framework, works great!</p>
<p><a href="http://django-rest-framework.org/" rel="nofollow">http://django-rest-framework.org/</a></p>
<p>Especially the class based views and the browsable api! and many other advantages (e..g. to upload images)</p>
| 2 | 2012-08-16T14:16:34Z | [
"python",
"django",
"rest"
] |
In Django, how could one use Django's update_object generic view to edit forms of inherited models? | 213,237 | <p>In Django, given excerpts from an application <em>animals</em> likeso:</p>
<p>A <em>animals/models.py</em> with: </p>
<pre><code>from django.db import models
from django.contrib.contenttypes.models import ContentType
class Animal(models.Model):
content_type = models.ForeignKey(ContentType,editable=False,null=True)
name = models.CharField()
class Dog(Animal):
is_lucky = models.BooleanField()
class Cat(Animal):
lives_left = models.IntegerField()
</code></pre>
<p>And an <em>animals/urls.py</em>:</p>
<pre><code>from django.conf.urls.default import *
from animals.models import Animal, Dog, Cat
dict = { 'model' : Animal }
urlpatterns = (
url(r'^edit/(?P<object_id>\d+)$', 'create_update.update_object', dict),
)
</code></pre>
<p>How can one use generic views to edit Dog and/or Cat using the same form?</p>
<p>I.e. The <em>form</em> object that is passed to *animals/animal_form.html* will be Animal, and thus won't contain any of the specifics for the derived classes Dog and Cat. How could I have Django automatically pass a form for the child class to *animal/animals_form.html*?</p>
<p>Incidentally, I'm using <a href="http://www.djangosnippets.org/snippets/1031/" rel="nofollow">Djangosnippets #1031</a> for ContentType management, so Animal would have a method named *as_leaf_class* that returns the derived class.</p>
<p>Clearly, one could create forms for each derived class, but that's quite a lot of unnecessary duplication (as the templates will all be generic -- essentially {{ form.as_p }}).</p>
<p>Incidentally, it's best to assume that Animal will probably be one of several unrelated base classes with the same problem, so an ideal solution would be generic.</p>
<p>Thank you in advance for the help.</p>
| 0 | 2008-10-17T18:16:07Z | 213,393 | <p>AFAICT, cats and dogs are on different DB tables, and maybe there's no Animal table. but you're using one URL pattern for all. somewhere you need to choose between each.</p>
<p>I'd use a different URL patter for cats and dogs, both would call <code>'create_update.update_object'</code>; but using a different <code>dict</code> for each. one with <code>'model':Dog</code> and the other with <code>'model':Cat</code></p>
<p>or maybe you want a single table where each record can be a cat or a dog? i don't think you can use inherited models for that.</p>
| 0 | 2008-10-17T18:51:06Z | [
"python",
"django",
"forms",
"inheritance",
"decorator"
] |
In Django, how could one use Django's update_object generic view to edit forms of inherited models? | 213,237 | <p>In Django, given excerpts from an application <em>animals</em> likeso:</p>
<p>A <em>animals/models.py</em> with: </p>
<pre><code>from django.db import models
from django.contrib.contenttypes.models import ContentType
class Animal(models.Model):
content_type = models.ForeignKey(ContentType,editable=False,null=True)
name = models.CharField()
class Dog(Animal):
is_lucky = models.BooleanField()
class Cat(Animal):
lives_left = models.IntegerField()
</code></pre>
<p>And an <em>animals/urls.py</em>:</p>
<pre><code>from django.conf.urls.default import *
from animals.models import Animal, Dog, Cat
dict = { 'model' : Animal }
urlpatterns = (
url(r'^edit/(?P<object_id>\d+)$', 'create_update.update_object', dict),
)
</code></pre>
<p>How can one use generic views to edit Dog and/or Cat using the same form?</p>
<p>I.e. The <em>form</em> object that is passed to *animals/animal_form.html* will be Animal, and thus won't contain any of the specifics for the derived classes Dog and Cat. How could I have Django automatically pass a form for the child class to *animal/animals_form.html*?</p>
<p>Incidentally, I'm using <a href="http://www.djangosnippets.org/snippets/1031/" rel="nofollow">Djangosnippets #1031</a> for ContentType management, so Animal would have a method named *as_leaf_class* that returns the derived class.</p>
<p>Clearly, one could create forms for each derived class, but that's quite a lot of unnecessary duplication (as the templates will all be generic -- essentially {{ form.as_p }}).</p>
<p>Incidentally, it's best to assume that Animal will probably be one of several unrelated base classes with the same problem, so an ideal solution would be generic.</p>
<p>Thank you in advance for the help.</p>
| 0 | 2008-10-17T18:16:07Z | 215,488 | <p>Alright, here's what I've done, and it seems to work and be a sensible design (though I stand to be corrected!).</p>
<p>In a core library (e.g. mysite.core.views.create_update), I've written a decorator:</p>
<pre><code>from django.contrib.contenttypes.models import ContentType
from django.views.generic import create_update
def update_object_as_child(parent_model_class):
"""
Given a base models.Model class, decorate a function to return
create_update.update_object, on the child class.
e.g.
@update_object(Animal)
def update_object(request, object_id):
pass
kwargs should have an object_id defined.
"""
def decorator(function):
def wrapper(request, **kwargs):
# may raise KeyError
id = kwargs['object_id']
parent_obj = parent_model_class.objects.get( pk=id )
# following http://www.djangosnippets.org/snippets/1031/
child_class = parent_obj.content_type.model_class()
kwargs['model'] = child_class
# rely on the generic code for testing/validation/404
return create_update.update_object(request, **kwargs)
return wrapper
return decorator
</code></pre>
<p>And in animals/views.py, I have:</p>
<pre><code>from mysite.core.views.create_update import update_object_as_child
@update_object_as_child(Animal)
def edit_animal(request, object_id):
pass
</code></pre>
<p>And in animals/urls.py, I have:</p>
<pre><code>urlpatterns += patterns('animals.views',
url(r'^edit/(?P<object_id>\d+)$', 'edit_animal', name="edit_animal"),
)
</code></pre>
<p>Now I only need a unique edit function for each base class, which is trivial to create with a decorator.</p>
<p>Hope someone finds that helpful, and I'd be delighted to have feedback.</p>
| 1 | 2008-10-18T19:40:12Z | [
"python",
"django",
"forms",
"inheritance",
"decorator"
] |
python threadsafe object cache | 213,455 | <p>I have implemented a python webserver. Each http request spawns a new thread.
I have a requirement of caching objects in memory and since its a webserver, I want the cache to be thread safe. Is there a standard implementatin of a thread safe object cache in python? I found the following </p>
<p><a href="http://freshmeat.net/projects/lrucache/">http://freshmeat.net/projects/lrucache/</a></p>
<p>This does not look to be thread safe. Can anybody point me to a good implementation of thread safe cache in python?</p>
<p>Thanks!</p>
| 9 | 2008-10-17T19:05:20Z | 213,695 | <p>You probably want to use memcached instead. It's very fast, very stable, very popular, has good python libraries, and will allow you to grow to a distributed cache should you need to:</p>
<p><a href="http://www.danga.com/memcached/" rel="nofollow">http://www.danga.com/memcached/</a></p>
| 4 | 2008-10-17T20:18:25Z | [
"python",
"multithreading",
"caching"
] |
python threadsafe object cache | 213,455 | <p>I have implemented a python webserver. Each http request spawns a new thread.
I have a requirement of caching objects in memory and since its a webserver, I want the cache to be thread safe. Is there a standard implementatin of a thread safe object cache in python? I found the following </p>
<p><a href="http://freshmeat.net/projects/lrucache/">http://freshmeat.net/projects/lrucache/</a></p>
<p>This does not look to be thread safe. Can anybody point me to a good implementation of thread safe cache in python?</p>
<p>Thanks!</p>
| 9 | 2008-10-17T19:05:20Z | 213,768 | <p>Thread per request is often a bad idea. If your server experiences huge spikes in load it will take the box to its knees. Consider using a thread pool that can grow to a limited size during peak usage and shrink to a smaller size when load is light.</p>
| 8 | 2008-10-17T20:39:48Z | [
"python",
"multithreading",
"caching"
] |
python threadsafe object cache | 213,455 | <p>I have implemented a python webserver. Each http request spawns a new thread.
I have a requirement of caching objects in memory and since its a webserver, I want the cache to be thread safe. Is there a standard implementatin of a thread safe object cache in python? I found the following </p>
<p><a href="http://freshmeat.net/projects/lrucache/">http://freshmeat.net/projects/lrucache/</a></p>
<p>This does not look to be thread safe. Can anybody point me to a good implementation of thread safe cache in python?</p>
<p>Thanks!</p>
| 9 | 2008-10-17T19:05:20Z | 215,329 | <p>Well a lot of operations in Python are thread-safe by default, so a standard dictionary should be ok (at least in certain respects). This is mostly due to the GIL, which will help avoid some of the more serious threading issues.</p>
<p>There's a list here: <a href="http://coreygoldberg.blogspot.com/2008/09/python-thread-synchronization-and.html" rel="nofollow">http://coreygoldberg.blogspot.com/2008/09/python-thread-synchronization-and.html</a> that might be useful.</p>
<p>Though atomic nature of those operation just means that you won't have an entirely inconsistent state if you have two threads accessing a dictionary at the same time. So you wouldn't have a corrupted value. However you would (as with most multi-threading programming) not be able to rely on the specific order of those atomic operations.</p>
<p>So to cut a long story short...</p>
<p>If you have fairly simple requirements and aren't to bothered about the ordering of what get written into the cache then you can use a dictionary and know that you'll always get a consistent/not-corrupted value (it just might be out of date).</p>
<p>If you want to ensure that things are a bit more consistent with regard to reading and writing then you might want to look at Django's local memory cache:</p>
<p><a href="http://code.djangoproject.com/browser/django/trunk/django/core/cache/backends/locmem.py" rel="nofollow">http://code.djangoproject.com/browser/django/trunk/django/core/cache/backends/locmem.py</a></p>
<p>Which uses a read/write lock for locking.</p>
| 7 | 2008-10-18T17:48:05Z | [
"python",
"multithreading",
"caching"
] |
python threadsafe object cache | 213,455 | <p>I have implemented a python webserver. Each http request spawns a new thread.
I have a requirement of caching objects in memory and since its a webserver, I want the cache to be thread safe. Is there a standard implementatin of a thread safe object cache in python? I found the following </p>
<p><a href="http://freshmeat.net/projects/lrucache/">http://freshmeat.net/projects/lrucache/</a></p>
<p>This does not look to be thread safe. Can anybody point me to a good implementation of thread safe cache in python?</p>
<p>Thanks!</p>
| 9 | 2008-10-17T19:05:20Z | 17,433,852 | <p>For a thread safe object you want threading.local:</p>
<pre><code>from threading import local
safe = local()
safe.cache = {}
</code></pre>
<p>You can then put and retrieve objects in <code>safe.cache</code> with thread safety.</p>
| 2 | 2013-07-02T19:09:51Z | [
"python",
"multithreading",
"caching"
] |
A good multithreaded python webserver? | 213,483 | <p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing. This is not possible in a multi-process web server environment. Storing this information in memcache is also not a good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of IPC.</p>
<p>I implemented a simple webserver using BaseHttpServer, it gives good performance but it gets stuck after a few hours time. I need some more matured webserver. Is it possible to configure apache to use mod_python under a thread model so that I can do some object caching?</p>
| 13 | 2008-10-17T19:12:38Z | 213,515 | <p>Not multithreaded, but <a href="http://twistedmatrix.com/trac/" rel="nofollow">twisted</a> might serve your needs.</p>
| 2 | 2008-10-17T19:22:28Z | [
"python",
"apache",
"webserver",
"mod-python"
] |
A good multithreaded python webserver? | 213,483 | <p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing. This is not possible in a multi-process web server environment. Storing this information in memcache is also not a good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of IPC.</p>
<p>I implemented a simple webserver using BaseHttpServer, it gives good performance but it gets stuck after a few hours time. I need some more matured webserver. Is it possible to configure apache to use mod_python under a thread model so that I can do some object caching?</p>
| 13 | 2008-10-17T19:12:38Z | 213,539 | <p>Perhaps you have a problem with your implementation in Python using <code>BaseHttpServer</code>. There's no reason for it to "get stuck", and implementing a simple threaded server using <code>BaseHttpServer</code> and <code>threading</code> shouldn't be difficult.</p>
<p>Also, see <a href="http://pymotw.com/2/BaseHTTPServer/index.html#module-BaseHTTPServer" rel="nofollow">http://pymotw.com/2/BaseHTTPServer/index.html#module-BaseHTTPServer</a> about implementing a simple multi-threaded server with <code>HTTPServer</code> and <code>ThreadingMixIn</code></p>
| 2 | 2008-10-17T19:27:36Z | [
"python",
"apache",
"webserver",
"mod-python"
] |
A good multithreaded python webserver? | 213,483 | <p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing. This is not possible in a multi-process web server environment. Storing this information in memcache is also not a good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of IPC.</p>
<p>I implemented a simple webserver using BaseHttpServer, it gives good performance but it gets stuck after a few hours time. I need some more matured webserver. Is it possible to configure apache to use mod_python under a thread model so that I can do some object caching?</p>
| 13 | 2008-10-17T19:12:38Z | 213,549 | <p>I use CherryPy both personally and professionally, and I'm extremely happy with it. I even do the kinds of thing you're describing, such as having global object caches, running other threads in the background, etc. And it integrates well with Apache; simply run CherryPy as a standalone server bound to localhost, then use Apache's <code>mod_proxy</code> and <code>mod_rewrite</code> to have Apache transparently forward your requests to CherryPy.</p>
<p>The CherryPy website is <a href="http://cherrypy.org/" rel="nofollow">http://cherrypy.org/</a></p>
| 0 | 2008-10-17T19:30:57Z | [
"python",
"apache",
"webserver",
"mod-python"
] |
A good multithreaded python webserver? | 213,483 | <p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing. This is not possible in a multi-process web server environment. Storing this information in memcache is also not a good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of IPC.</p>
<p>I implemented a simple webserver using BaseHttpServer, it gives good performance but it gets stuck after a few hours time. I need some more matured webserver. Is it possible to configure apache to use mod_python under a thread model so that I can do some object caching?</p>
| 13 | 2008-10-17T19:12:38Z | 213,551 | <p>You could instead use a distributed cache that is accessible from each process, <a href="http://www.danga.com/memcached/" rel="nofollow">memcached</a> being the example that springs to mind.</p>
| 2 | 2008-10-17T19:31:15Z | [
"python",
"apache",
"webserver",
"mod-python"
] |
A good multithreaded python webserver? | 213,483 | <p>I am looking for a python webserver which is multithreaded instead of being multi-process (as in case of mod_python for apache). I want it to be multithreaded because I want to have an in memory object cache that will be used by various http threads. My webserver does a lot of expensive stuff and computes some large arrays which needs to be cached in memory for future use to avoid recomputing. This is not possible in a multi-process web server environment. Storing this information in memcache is also not a good idea as the arrays are large and storing them in memcache would lead to deserialization of data coming from memcache apart from the additional overhead of IPC.</p>
<p>I implemented a simple webserver using BaseHttpServer, it gives good performance but it gets stuck after a few hours time. I need some more matured webserver. Is it possible to configure apache to use mod_python under a thread model so that I can do some object caching?</p>
| 13 | 2008-10-17T19:12:38Z | 213,563 | <p><a href="http://cherrypy.org/">CherryPy</a>. Features, as listed from the website:</p>
<ul>
<li>A fast, HTTP/1.1-compliant, WSGI thread-pooled webserver. Typically, CherryPy itself takes only 1-2ms per page!</li>
<li>Support for any other WSGI-enabled webserver or adapter, including Apache, IIS, lighttpd, mod_python, FastCGI, SCGI, and mod_wsgi</li>
<li>Easy to run multiple HTTP servers (e.g. on multiple ports) at once</li>
<li>A powerful configuration system for developers and deployers alike</li>
<li>A flexible plugin system</li>
<li>Built-in tools for caching, encoding, sessions, authorization, static content, and many more</li>
<li>A native mod_python adapter</li>
<li>A complete test suite</li>
<li>Swappable and customizable...everything.</li>
<li>Built-in profiling, coverage, and testing support. </li>
</ul>
| 16 | 2008-10-17T19:33:25Z | [
"python",
"apache",
"webserver",
"mod-python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.