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
Python, Evaluate a Variable value as a Variable
632,856
<p>I'd like to do something like below: particularly the 'f.eval(field)' part, such that it evaluates the value of the variable as the field name. How does one accomplish this in Python?</p> <pre><code>def punctuated_object_list(objects, field): field_list = [f.eval(field) for f in objects] if len(field_list) &gt; 0: if len(field_list) == 1: return field_list[0] else: return ', '.join(field_list[:-1]) + ' &amp; ' + field_list[-1] else: return u'' </code></pre>
4
2009-03-11T00:31:50Z
632,902
<p>To get at a list of all the fields in a Python object you can access its <code>__dict__</code> property.</p> <pre><code>class Testing(): def __init__(self): self.name = "Joe" self.age = 30 test = Testing() print test.__dict__ </code></pre> <p>results:</p> <pre><code>{'age': 30, 'name': 'Joe'} </code></pre>
0
2009-03-11T00:43:27Z
[ "python" ]
Python, Evaluate a Variable value as a Variable
632,856
<p>I'd like to do something like below: particularly the 'f.eval(field)' part, such that it evaluates the value of the variable as the field name. How does one accomplish this in Python?</p> <pre><code>def punctuated_object_list(objects, field): field_list = [f.eval(field) for f in objects] if len(field_list) &gt; 0: if len(field_list) == 1: return field_list[0] else: return ', '.join(field_list[:-1]) + ' &amp; ' + field_list[-1] else: return u'' </code></pre>
4
2009-03-11T00:31:50Z
632,911
<pre><code>getattr( object, 'field' ) #note that field is a string f = 'field_name' #... getattr( object, f ) #to get a list of fields in an object, you can use dir() dir( object ) </code></pre> <p>For more details, see: <a href="http://www.diveintopython.org/power_of_introspection/index.html" rel="nofollow">http://www.diveintopython.org/power_of_introspection/index.html</a></p> <p><strong>Don't use eval</strong>, even if the strings are safe in this particular case! Just don't get yourself used to it. If you're getting the string from the user it could be malicious code. </p> <p>Murphy's law: if things can go wrong, they will.</p>
4
2009-03-11T00:47:08Z
[ "python" ]
Unable to separate codes in one file to many files in AWK/Python
632,958
<p>I need to put different codes in one file to many files. The file is apparantly shared by AWK's creators at their homepage. The file is also <a href="http://dpaste.com/12282/" rel="nofollow">here</a> for easy use.</p> <p><strong>My attempt to the problem</strong></p> <p>I can get the lines where each code locate by</p> <pre><code>awk '{ print $1 }' </code></pre> <p>However, I do no know how</p> <ol> <li>to get the exact line numbers so that I can use them</li> <li>to collect codes between the specific lines so that the first word of each line is ignored</li> <li>to put these separate codes into new files which are named by the first word at the line</li> </ol> <p>I am sure that the problem can be solved by AWK and with Python too. Perhaps, we need to use them together. </p> <p><strong>[edit]</strong> after the first answer</p> <p>I get the following error when I try to execute it with awk</p> <pre><code>$awk awkcode.txt awk: syntax error at source line 1 context is &gt;&gt;&gt; awkcode &lt;&lt;&lt; .txt awk: bailing out at source line 1 </code></pre>
0
2009-03-11T01:06:34Z
633,000
<p>Are you trying to unpack a file in that format? It's a kind of shell archive. For more information, see <a href="http://en.wikipedia.org/wiki/Shar" rel="nofollow">http://en.wikipedia.org/wiki/Shar</a></p> <p>If you execute that program with awk, awk will create all those files. You don't need to write or rewrite much. You can simply run that awk program, and it should still work.</p> <p>First, view the file in "plain" format. <a href="http://dpaste.com/12282/plain/" rel="nofollow">http://dpaste.com/12282/plain/</a></p> <p>Second, save the plain version of the file as 'awkcode.shar'</p> <p>Third, I think you need to use the following command. </p> <pre><code>awk -f awkcode.shar </code></pre> <p><hr /></p> <p>If you want to replace it with a Python program, it would be something like this.</p> <pre><code>import urllib2, sys data= urllib2.urlopen( "http://dpaste.com/12282/plain/" ) currName, currFile = None, sys.stdout for line in data: fileName, _, text= line.strip().partition(' ') if fileName == currName: currFile.write(line+"\n") else: if currFile is not None: currFile.close() currName= fileName currFile= open( currName, "w" ) if currFile is not None: currFile.close() </code></pre>
2
2009-03-11T01:38:06Z
[ "python", "awk" ]
Unable to separate codes in one file to many files in AWK/Python
632,958
<p>I need to put different codes in one file to many files. The file is apparantly shared by AWK's creators at their homepage. The file is also <a href="http://dpaste.com/12282/" rel="nofollow">here</a> for easy use.</p> <p><strong>My attempt to the problem</strong></p> <p>I can get the lines where each code locate by</p> <pre><code>awk '{ print $1 }' </code></pre> <p>However, I do no know how</p> <ol> <li>to get the exact line numbers so that I can use them</li> <li>to collect codes between the specific lines so that the first word of each line is ignored</li> <li>to put these separate codes into new files which are named by the first word at the line</li> </ol> <p>I am sure that the problem can be solved by AWK and with Python too. Perhaps, we need to use them together. </p> <p><strong>[edit]</strong> after the first answer</p> <p>I get the following error when I try to execute it with awk</p> <pre><code>$awk awkcode.txt awk: syntax error at source line 1 context is &gt;&gt;&gt; awkcode &lt;&lt;&lt; .txt awk: bailing out at source line 1 </code></pre>
0
2009-03-11T01:06:34Z
634,062
<p>Did you try to:</p> <ol> <li>Create a file unbundle.awk with the following content:</li> </ol> <p>$1 != prev { close(prev); prev = $1 } { print substr($0, index($0, " ") + 1) >$1 }</p> <ol> <li><p>Remove the following lines form the file awkcode.txt:</p> <p><strong># unbundle - unpack a bundle into separate files</strong></p></li> </ol> <p>$1 != prev { close(prev); prev = $1 } { print substr($0, index($0, " ") + 1) >$1 }</p> <ol> <li>Run the following command:</li> </ol> <p>awk -f unbundle.awk awkcode.txt</p>
2
2009-03-11T10:56:35Z
[ "python", "awk" ]
Unable to separate codes in one file to many files in AWK/Python
632,958
<p>I need to put different codes in one file to many files. The file is apparantly shared by AWK's creators at their homepage. The file is also <a href="http://dpaste.com/12282/" rel="nofollow">here</a> for easy use.</p> <p><strong>My attempt to the problem</strong></p> <p>I can get the lines where each code locate by</p> <pre><code>awk '{ print $1 }' </code></pre> <p>However, I do no know how</p> <ol> <li>to get the exact line numbers so that I can use them</li> <li>to collect codes between the specific lines so that the first word of each line is ignored</li> <li>to put these separate codes into new files which are named by the first word at the line</li> </ol> <p>I am sure that the problem can be solved by AWK and with Python too. Perhaps, we need to use them together. </p> <p><strong>[edit]</strong> after the first answer</p> <p>I get the following error when I try to execute it with awk</p> <pre><code>$awk awkcode.txt awk: syntax error at source line 1 context is &gt;&gt;&gt; awkcode &lt;&lt;&lt; .txt awk: bailing out at source line 1 </code></pre>
0
2009-03-11T01:06:34Z
19,219,465
<p>Awk file awkcode.txt should not contain ANY BLANK line. If any blank line is encountered, the awk program fails. There is no error check to filter out blank line in the code. This I could find out after several days of struggle. </p>
0
2013-10-07T07:47:06Z
[ "python", "awk" ]
detecting fullscreen on mac
633,086
<p>I am writing an IM client for Mac (in python, but an Objective C / Cocoa solution here is fine). I want to detect whether or not the user is currently watching a movie or playing a game in the foreground, or doing anything else that takes up the entire screen. If so, I won't play a sound when a new IM comes in, but if not, I will play the sound.</p> <p>How can I detect this? Is there some way to get the foreground window with applescript and look at its dimensions? Or is there some other API call?</p> <p>Thanks.</p>
2
2009-03-11T02:11:41Z
633,164
<p>not entirely sure how to do this, but the <a href="http://developer.apple.com/documentation/Carbon/Reference/Dock%5FManager/Reference/reference.html#//apple%5Fref/c/func/GetSystemUIMode" rel="nofollow">apple docs</a> say:</p> <blockquote> <p>To track changes in the login session’s presentation mode, you may handle the <code>kEventAppSystemUIModeChanged</code> Carbon event</p> </blockquote>
2
2009-03-11T02:46:00Z
[ "python", "objective-c", "cocoa", "osx", "fullscreen" ]
detecting fullscreen on mac
633,086
<p>I am writing an IM client for Mac (in python, but an Objective C / Cocoa solution here is fine). I want to detect whether or not the user is currently watching a movie or playing a game in the foreground, or doing anything else that takes up the entire screen. If so, I won't play a sound when a new IM comes in, but if not, I will play the sound.</p> <p>How can I detect this? Is there some way to get the foreground window with applescript and look at its dimensions? Or is there some other API call?</p> <p>Thanks.</p>
2
2009-03-11T02:11:41Z
633,166
<p>To check for full-screen, call <a href="http://developer.apple.com/DOCUMENTATION/GraphicsImaging/Reference/Quartz%5FServices%5FRef/Reference/reference.html#//apple%5Fref/c/func/CGDisplayIsCaptured" rel="nofollow">CGDisplayIsCaptured(screenID)</a> on each screen.</p> <p>But I'm not sure if you're checking the right thing. For one thing, I could have one screen captured ("full screen") and a second screen uncaptured, what do you want to do in this case?</p> <p>Also, does fullscreen really mean anything? If I'm using GarageBand to work on a song, I probably don't want to hear random sounds, regardless of whether or not anything's full screen. Or I could be running a Windows VM full-screen, but still want to be notified of IMs.</p>
8
2009-03-11T02:48:50Z
[ "python", "objective-c", "cocoa", "osx", "fullscreen" ]
detecting fullscreen on mac
633,086
<p>I am writing an IM client for Mac (in python, but an Objective C / Cocoa solution here is fine). I want to detect whether or not the user is currently watching a movie or playing a game in the foreground, or doing anything else that takes up the entire screen. If so, I won't play a sound when a new IM comes in, but if not, I will play the sound.</p> <p>How can I detect this? Is there some way to get the foreground window with applescript and look at its dimensions? Or is there some other API call?</p> <p>Thanks.</p>
2
2009-03-11T02:11:41Z
633,718
<p>The two solutions posted so far apply to “real” full-screen, but it’s worth noting that many full-screen apps just put a window over the whole screen (or, as vasi points out, <em>a</em> whole screen). To be accurate, you’ll have to check both.</p>
0
2009-03-11T08:19:39Z
[ "python", "objective-c", "cocoa", "osx", "fullscreen" ]
detecting fullscreen on mac
633,086
<p>I am writing an IM client for Mac (in python, but an Objective C / Cocoa solution here is fine). I want to detect whether or not the user is currently watching a movie or playing a game in the foreground, or doing anything else that takes up the entire screen. If so, I won't play a sound when a new IM comes in, but if not, I will play the sound.</p> <p>How can I detect this? Is there some way to get the foreground window with applescript and look at its dimensions? Or is there some other API call?</p> <p>Thanks.</p>
2
2009-03-11T02:11:41Z
11,965,482
<p>In Mountain Lion (and probably earlier), you can track the presence of the menu bar by monitoring the distributed notifications com.apple.HIToolbox.hideMenuBarShown and com.apple.HIToolbox.hideMenuBarShown. No menu bar usually == fullscreen mode. This works across apps, so you can tell when, say, VLC goes fullscreen, or when someone switches to iCal in fullscreen mode.</p> <p>To do this, register for these two notifications:</p> <pre><code>[[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidEnterFullScreen:) name:@"com.apple.HIToolbox.hideMenuBarShown" object:nil]; [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidExitFullScreen:) name:@"com.apple.HIToolbox.frontMenuBarShown" object:nil]; </code></pre> <p>then create your own selectors to handle those cases. frontMenuBarShown fires all the time, so to catch a real return from fullscreen, watch for the first 'didExit' that follows a 'didEnter'...</p>
0
2012-08-15T07:23:56Z
[ "python", "objective-c", "cocoa", "osx", "fullscreen" ]
why am i getting errors while installing pysqlite2.5.3
633,601
<p>Am trying build pysqlite 2.5.3 package on SLSE 9, and am getting all sorts of compilation errors i.e.</p> <pre><code>... src/module.c:290: error: initializer element is not constant src/module.c:290: error: (near initialization for `_int_constants[27].constant_value') src/module.c:290: error: initializer element is not constant src/module.c:290: error: (near initialization for `_int_constants[27]') src/module.c:291: error: `SQLITE_ATTACH' undeclared here (not in a function) src/module.c:291: error: initializer element is not constant src/module.c:291: error: (near initialization for `_int_constants[28].constant_value') src/module.c:291: error: initializer element is not constant src/module.c:291: error: (near initialization for `_int_constants[28]') src/module.c:292: error: `SQLITE_DETACH' undeclared here (not in a function) src/module.c:292: error: initializer element is not constant src/module.c:292: error: (near initialization for `_int_constants[29].constant_value') src/module.c:292: error: initializer element is not constant src/module.c:292: error: (near initialization for `_int_constants[29]') src/module.c:300: error: initializer element is not constant src/module.c:300: error: (near initialization for `_int_constants[30]') src/module.c: In function `init_sqlite': src/module.c:419: warning: implicit declaration of function `sqlite3_libversion' src/module.c:419: warning: passing arg 1 of `PyString_FromString' makes pointer from integer without a cast error: command 'gcc' failed with exit status 1 </code></pre> <p>the things fails</p> <p>this is my setup.cfg file:</p> <pre><code>[build_ext] #define= #include_dirs=/usr/local/include #library_dirs=/usr/local/lib libraries=sqlite3 define= </code></pre> <p>SQLlite is running... when i do sqlite3, i get the command interface.</p> <p>What am i missing out?</p> <p>Gath</p>
1
2009-03-11T07:01:54Z
633,606
<p>Do you have the sqlite development headers installed?</p> <blockquote> <p>error: SQLITE_DETACH' undeclared here </p> </blockquote> <p>Looks like you need sqlite3-dev (or whatever your distro named it, perhaps sqlite3-devel?)</p> <p><strong>Edit:</strong></p> <p>After a good natured soul cleaned up your error trace a bit more, I'm quite sure you are missing the sqlite3 development headers. You have the library, just not the headers:</p> <blockquote> <p>src/module.c:419: warning: implicit declaration of function `sqlite3_libversion'</p> </blockquote> <p>If there is no header, there is no prototype. If there is no prototype, you'll see a warning complaining about an implicit declaration (if the compiler is set to issue sensible warnings).</p>
4
2009-03-11T07:04:21Z
[ "python", "linux", "sqlite" ]
Scalable polling of an AppEngine application from numerous "active" clients?
633,999
<p>I'm working on an application that will run on Google AppEngine.</p> <p>I plan to have the web interface of that application wait, among many other things, for notifications coming from the AppEngine server.</p> <p>Ideally I would have liked to use an XMLHttpRequest() to make a request to the server that would be waiting until the next notification comes from the application.</p> <p>However there does not appear to be in AppEngine to support this type of logic (correct me if I'm wrong). This means I appear to be limited to polling at periodic intervals.</p> <p>So the question is:</p> <ul> <li>Does anyone have a good suggestion of how to best design this polling mechanism in order to avoid running into CPU usage quotas of AppEngine? Scalability as the number of "active" clients takes off needs to be considered.</li> </ul> <p>I am specifically interested in suggestions for good management of the polling intervals from the client side and tips for efficient handling of the requests in the AppEngine application as the number of "active" clients grows.</p> <p><em>PS</em>: the type of information polled from the server will typically be JSON-encoded information about recently updated/added bits of information (read recently as: in the past few seconds or minutes).</p> <p><strong>Status Update</strong></p> <p>Here is a summary of my thoughts so far around this question:</p> <ul> <li>To minimize the CPU load required to answer each individual request generated by the polling approach: use the memcache to minimize the time it takes to collect the reply information. <strong>Need to find pointers to a good example of that</strong>.</li> <li>To minimize the number of requests generated to the server by the "active" clients I have several leads: <ul> <li>Make the wait between successive polling requests to the server progressively longer if the user is not actively interacting (i.e. not clicking on anything) within the client web page.</li> <li>Piggy back on other types of requests to the server, that is include the results of the polling requests into other request results to save on the number of requests.</li> </ul></li> </ul> <p>Comments and pointers to code examples welcome!</p>
2
2009-03-11T10:37:08Z
637,045
<p>You are correct; long-running connections are prohibited on App Engine. The model is request->response->connection closed, and as quickly as possible.</p> <p>There are certain kinds of applications that aren't feasible on App Engine due to this architecture. If you absolutely need a notification from the server within 5 seconds of an event, for example, your only real choice is to poll the server every 5 seconds. This is probably not practical for large numbers of users.</p> <p>Requests themselves don't necessarily generate a lot of CPU load. A handler that fetches a memcache key and returns it to the user can easily get under 50ms CPU time, for example. So part of your mission is to reduce the number of requests/min from your clients, but part of it is to ensure your python scripts execute and return as quickly as possible. For this to happen you need to make sure your imports are structured intelligently and do whatever you can to avoid accessing the datastore during user requests.</p> <p>As far as sample code, can you be a little bit more specific about what you're looking for? For a simple memcache key request, a response to a query can be as simple as:</p> <pre><code>from django.utils import simplejson from google.appengine.api import memcache jsonResponse = {} jsonResponse['theVal'] = memcache.get(key="testkey") self.response.out.write(simplejson.dumps(jsonResponse)) </code></pre> <p>Naturally if the memcache data is backed by the datastore, you'll want to take some actions if the key is not found in memcache. Depending on your application, datastore backing may or may not be appropriate.</p>
3
2009-03-12T01:16:53Z
[ "javascript", "python", "ajax", "google-app-engine" ]
Scalable polling of an AppEngine application from numerous "active" clients?
633,999
<p>I'm working on an application that will run on Google AppEngine.</p> <p>I plan to have the web interface of that application wait, among many other things, for notifications coming from the AppEngine server.</p> <p>Ideally I would have liked to use an XMLHttpRequest() to make a request to the server that would be waiting until the next notification comes from the application.</p> <p>However there does not appear to be in AppEngine to support this type of logic (correct me if I'm wrong). This means I appear to be limited to polling at periodic intervals.</p> <p>So the question is:</p> <ul> <li>Does anyone have a good suggestion of how to best design this polling mechanism in order to avoid running into CPU usage quotas of AppEngine? Scalability as the number of "active" clients takes off needs to be considered.</li> </ul> <p>I am specifically interested in suggestions for good management of the polling intervals from the client side and tips for efficient handling of the requests in the AppEngine application as the number of "active" clients grows.</p> <p><em>PS</em>: the type of information polled from the server will typically be JSON-encoded information about recently updated/added bits of information (read recently as: in the past few seconds or minutes).</p> <p><strong>Status Update</strong></p> <p>Here is a summary of my thoughts so far around this question:</p> <ul> <li>To minimize the CPU load required to answer each individual request generated by the polling approach: use the memcache to minimize the time it takes to collect the reply information. <strong>Need to find pointers to a good example of that</strong>.</li> <li>To minimize the number of requests generated to the server by the "active" clients I have several leads: <ul> <li>Make the wait between successive polling requests to the server progressively longer if the user is not actively interacting (i.e. not clicking on anything) within the client web page.</li> <li>Piggy back on other types of requests to the server, that is include the results of the polling requests into other request results to save on the number of requests.</li> </ul></li> </ul> <p>Comments and pointers to code examples welcome!</p>
2
2009-03-11T10:37:08Z
640,500
<p>OR...</p> <p>You might be interested in some pubsub implementation. Like the venerable <a href="http://code.google.com/p/pubsubhubbub/" rel="nofollow">pubsubhubbub</a>, made by guys from Google and Jaiku.</p>
1
2009-03-12T21:12:02Z
[ "javascript", "python", "ajax", "google-app-engine" ]
Why do Python's frameworks return dictionaries from controllers?
634,024
<p>Why (for example web2py) do you return data from a controller in a dictionary instead of variables (see Rails)? </p> <p>For example:</p> <pre><code>return dict(sape=4139, guido=4127, jack=4098) </code></pre> <p>instead of (that's the way Rails does it)</p> <pre><code>@var1 = "jello" @var2 = "hihi" </code></pre> <p>Is there any advantage using dictionaries over plain variables (speed-wise/code-wise)?</p> <p>Update: The above way is actually a correct way for creating a dictionary (at least in Python 2.6.1). The other way (that many people say it's the correct one)</p> <pre><code>return {"var1": "jello", "var2": "hihi"} </code></pre> <p>is not used a lot by python frameworks.</p> <p>From <a href="http://docs.python.org/tutorial/datastructures.html" rel="nofollow">Python's documentation</a>: "When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:"</p> <pre><code>dict(sape=4139, guido=4127, jack=4098) </code></pre>
2
2009-03-11T10:45:28Z
634,101
<p>The main advantage is that this is the only way in python to return a) more than a single value <strong>and</strong> b) give that value a name. Other options would be to use a class (extra code), return a tuple (no names, so you'd have to use indexes to access the values) or allow to return only a single value which would probably mean that everyone would return a dictionary since that's the most simple solution.</p> <p>It also allows to wrap several methods and join/merge their results. Lastly, it allows to return different sets of value/name pairs for each call easily, for example, omit optional values or return additional hints.</p>
5
2009-03-11T11:13:09Z
[ "python", "ruby-on-rails", "web2py" ]
Why do Python's frameworks return dictionaries from controllers?
634,024
<p>Why (for example web2py) do you return data from a controller in a dictionary instead of variables (see Rails)? </p> <p>For example:</p> <pre><code>return dict(sape=4139, guido=4127, jack=4098) </code></pre> <p>instead of (that's the way Rails does it)</p> <pre><code>@var1 = "jello" @var2 = "hihi" </code></pre> <p>Is there any advantage using dictionaries over plain variables (speed-wise/code-wise)?</p> <p>Update: The above way is actually a correct way for creating a dictionary (at least in Python 2.6.1). The other way (that many people say it's the correct one)</p> <pre><code>return {"var1": "jello", "var2": "hihi"} </code></pre> <p>is not used a lot by python frameworks.</p> <p>From <a href="http://docs.python.org/tutorial/datastructures.html" rel="nofollow">Python's documentation</a>: "When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:"</p> <pre><code>dict(sape=4139, guido=4127, jack=4098) </code></pre>
2
2009-03-11T10:45:28Z
634,120
<p>The nice thing is that a template engine like Jinja2 treats an object and a dict similarly, so if:</p> <pre><code>d = {'color': 'red'} o = Color(red) </code></pre> <p>then these all work in the template syntax:</p> <pre><code>d.color d['color'] o.color o['color'] </code></pre>
-1
2009-03-11T11:19:50Z
[ "python", "ruby-on-rails", "web2py" ]
Why do Python's frameworks return dictionaries from controllers?
634,024
<p>Why (for example web2py) do you return data from a controller in a dictionary instead of variables (see Rails)? </p> <p>For example:</p> <pre><code>return dict(sape=4139, guido=4127, jack=4098) </code></pre> <p>instead of (that's the way Rails does it)</p> <pre><code>@var1 = "jello" @var2 = "hihi" </code></pre> <p>Is there any advantage using dictionaries over plain variables (speed-wise/code-wise)?</p> <p>Update: The above way is actually a correct way for creating a dictionary (at least in Python 2.6.1). The other way (that many people say it's the correct one)</p> <pre><code>return {"var1": "jello", "var2": "hihi"} </code></pre> <p>is not used a lot by python frameworks.</p> <p>From <a href="http://docs.python.org/tutorial/datastructures.html" rel="nofollow">Python's documentation</a>: "When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:"</p> <pre><code>dict(sape=4139, guido=4127, jack=4098) </code></pre>
2
2009-03-11T10:45:28Z
634,173
<p>You can use local variables if you'd like:</p> <pre><code>def hello(): var1 = "whatever you like" var2 = "another value" return locals() # or vars() </code></pre> <p><code>hello.html</code>:</p> <pre><code>&lt;html&gt;&lt;body&gt; &lt;p&gt;var1 {{=var1}}&lt;/p&gt; &lt;p&gt;var2 {{=var2}}&lt;/p&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p><a href="http://mdp.cti.depaul.edu/AlterEgo/default/show/106" rel="nofollow">from PHP to web2py</a>:</p> <blockquote> <p>In web2py an HTTP request for "/app/c/f" is mapped into a call to the function f() in file (controller) c.py in the application "app". The file c.py is written in Python. The output of the function f() can be a string (in this case it is returned), or a set of variables (implemented as a python dictionary). In the latter case the variables are rendered into HTML by a file c/f.html, called a view.</p> </blockquote>
3
2009-03-11T11:37:08Z
[ "python", "ruby-on-rails", "web2py" ]
Python drag and drop
634,067
<p>Im working on a parser here that opens a file, reads it and prints data in another file.</p> <p>The input file is determined from sys.argv[1] to both handle commandline opening and drag and drop (in windows). However, when drag and dropping a file, it gives me</p> <pre><code>ioerror 13: Permission denied </code></pre> <p>Looking at what sys.argv contained, I did the following (from cmd.exe) to have it contain the same:</p> <pre><code>C:\&gt;python C:\test\iotest.py C:\test\iotestin.txt </code></pre> <p>It failed. However, the following works</p> <pre><code>C:\&gt;cd test C:\test&gt;python iotest.py iotestin.txt </code></pre> <p>To me, the above would/should be virtually the same.</p> <ul> <li>Why do I get the permission error? </li> <li>How do I make python able to handle fully specified paths? (If thats the problem.)</li> <li>How do I enable drag and drop?</li> </ul> <p>Oh, and if its unclear, I drag the input/txt file to the python file, not the other way around. As a coder, I always prefer a CLI, but the future users of this software do not, hence I need to get this working.</p> <p>Although extremely simple, heres some code to reproduce the problem:</p> <pre><code>import sys print sys.argv raw_input("") try: print "opening",sys.argv[1] infile = open(sys.argv[1]) outfile = open("out.txt", "w") raw_input("") except IndexError: print "usage:",sys.argv[0].split("\\")[-1],"FILE" raw_input("") exit() except IOError as (errno, strerror): print "I/O error({0}): {1}".format(errno, strerror) raw_input("") exit() raw_input("done") </code></pre>
0
2009-03-11T10:59:51Z
634,086
<p>You use <code>outfile = open("out.txt", "w")</code> - In the first example, this would go to c:\out.txt, which I'd imagine is the source of your error.</p>
4
2009-03-11T11:06:00Z
[ "python", "windows", "drag-and-drop", "permission-denied", "ioerror" ]
Python drag and drop
634,067
<p>Im working on a parser here that opens a file, reads it and prints data in another file.</p> <p>The input file is determined from sys.argv[1] to both handle commandline opening and drag and drop (in windows). However, when drag and dropping a file, it gives me</p> <pre><code>ioerror 13: Permission denied </code></pre> <p>Looking at what sys.argv contained, I did the following (from cmd.exe) to have it contain the same:</p> <pre><code>C:\&gt;python C:\test\iotest.py C:\test\iotestin.txt </code></pre> <p>It failed. However, the following works</p> <pre><code>C:\&gt;cd test C:\test&gt;python iotest.py iotestin.txt </code></pre> <p>To me, the above would/should be virtually the same.</p> <ul> <li>Why do I get the permission error? </li> <li>How do I make python able to handle fully specified paths? (If thats the problem.)</li> <li>How do I enable drag and drop?</li> </ul> <p>Oh, and if its unclear, I drag the input/txt file to the python file, not the other way around. As a coder, I always prefer a CLI, but the future users of this software do not, hence I need to get this working.</p> <p>Although extremely simple, heres some code to reproduce the problem:</p> <pre><code>import sys print sys.argv raw_input("") try: print "opening",sys.argv[1] infile = open(sys.argv[1]) outfile = open("out.txt", "w") raw_input("") except IndexError: print "usage:",sys.argv[0].split("\\")[-1],"FILE" raw_input("") exit() except IOError as (errno, strerror): print "I/O error({0}): {1}".format(errno, strerror) raw_input("") exit() raw_input("done") </code></pre>
0
2009-03-11T10:59:51Z
35,334,000
<p>The working directory may be in <code>C:\Window\System32</code> when get error: IOError: [Errno 2] No such file or directory: or 13: Permission denied. </p> <p>So you need to change to the script or input file directory firstly. Such as: </p> <p><code>os.chdir(os.path.split(sys.argv[0])[0])</code></p> <p>If you want to change to the folder of input file, try:</p> <p><code>os.chdir(os.path.split(sys.argv[1])[0])</code></p>
0
2016-02-11T08:17:03Z
[ "python", "windows", "drag-and-drop", "permission-denied", "ioerror" ]
Writing a socket-based server in Python, recommended strategies?
634,107
<p>I was recently reading <a href="http://www.kegel.com/c10k.html">this document</a> which lists a number of strategies that could be employed to implement a socket server. Namely, they are:</p> <ol> <li>Serve many clients with each thread, and use nonblocking I/O and level-triggered readiness notification</li> <li>Serve many clients with each thread, and use nonblocking I/O and readiness change notification</li> <li>Serve many clients with each server thread, and use asynchronous I/O</li> <li>serve one client with each server thread, and use blocking I/O</li> <li>Build the server code into the kernel </li> </ol> <p>Now, I would appreciate a hint on which should be used <strong>in CPython</strong>, which we know has some good points, and some bad points. I am mostly interested in performance under high concurrency, and yes a number of the current implementations are too slow.</p> <p>So if I may start with the easy one, "5" is out, as I am not going to be hacking anything into the kernel.</p> <p>"4" Also looks like it must be out because of the GIL. Of course, you could use multiprocessing in place of threads here, and that does give a significant boost. Blocking IO also has the advantage of being easier to understand.</p> <p>And here my knowledge wanes a bit:</p> <p>"1" is traditional select or poll which could be trivially combined with multiprocessing.</p> <p>"2" is the readiness-change notification, used by the newer epoll and kqueue</p> <p>"3" I am not sure there are any kernel implementations for this that have Python wrappers.</p> <p>So, in Python we have a bag of great tools like Twisted. Perhaps they are a better approach, though I have benchmarked Twisted and found it too slow on a multiple processor machine. Perhaps having 4 twisteds with a load balancer might do it, I don't know. Any advice would be appreciated.</p>
9
2009-03-11T11:15:27Z
634,166
<p><a href="http://docs.python.org/library/socketserver.html#asynchronous-mixins" rel="nofollow">http://docs.python.org/library/socketserver.html#asynchronous-mixins</a></p> <p>As for multi-processor (multi-core) machines. With CPython due to <a href="http://docs.python.org/glossary.html#term-global-interpreter-lock" rel="nofollow">GIL</a> you'll need at least one process per core, to scale. As you say that you need CPython, you might try to benchmark that with <code>ForkingMixIn</code>. With Linux 2.6 might give some interesting results.</p> <p>Other way is to use <a href="http://www.stackless.com/" rel="nofollow">Stackless Python</a>. That's <a href="http://www.slideshare.net/Arbow/stackless-python-in-eve" rel="nofollow">how EVE solved it</a>. But I understand that it's not always possible. </p>
1
2009-03-11T11:30:19Z
[ "python", "sockets", "asynchronous", "network-programming", "c10k" ]
Writing a socket-based server in Python, recommended strategies?
634,107
<p>I was recently reading <a href="http://www.kegel.com/c10k.html">this document</a> which lists a number of strategies that could be employed to implement a socket server. Namely, they are:</p> <ol> <li>Serve many clients with each thread, and use nonblocking I/O and level-triggered readiness notification</li> <li>Serve many clients with each thread, and use nonblocking I/O and readiness change notification</li> <li>Serve many clients with each server thread, and use asynchronous I/O</li> <li>serve one client with each server thread, and use blocking I/O</li> <li>Build the server code into the kernel </li> </ol> <p>Now, I would appreciate a hint on which should be used <strong>in CPython</strong>, which we know has some good points, and some bad points. I am mostly interested in performance under high concurrency, and yes a number of the current implementations are too slow.</p> <p>So if I may start with the easy one, "5" is out, as I am not going to be hacking anything into the kernel.</p> <p>"4" Also looks like it must be out because of the GIL. Of course, you could use multiprocessing in place of threads here, and that does give a significant boost. Blocking IO also has the advantage of being easier to understand.</p> <p>And here my knowledge wanes a bit:</p> <p>"1" is traditional select or poll which could be trivially combined with multiprocessing.</p> <p>"2" is the readiness-change notification, used by the newer epoll and kqueue</p> <p>"3" I am not sure there are any kernel implementations for this that have Python wrappers.</p> <p>So, in Python we have a bag of great tools like Twisted. Perhaps they are a better approach, though I have benchmarked Twisted and found it too slow on a multiple processor machine. Perhaps having 4 twisteds with a load balancer might do it, I don't know. Any advice would be appreciated.</p>
9
2009-03-11T11:15:27Z
634,237
<p><a href="http://docs.python.org/library/asyncore.html" rel="nofollow"><code>asyncore</code></a> is basically "1" - It uses <code>select</code> internally, and you just have one thread handling all requests. According to the docs it can also use <code>poll</code>. (EDIT: Removed Twisted reference, I thought it used asyncore, but I was wrong).</p> <p>"2" might be implemented with <a href="http://sourceforge.net/projects/pyepoll" rel="nofollow">python-epoll</a> (Just googled it - never seen it before). EDIT: (from the comments) In python 2.6 the <a href="http://docs.python.org/library/select.html" rel="nofollow">select module</a> has epoll, kqueue and kevent build-in (on supported platforms). So you don't need any external libraries to do edge-triggered serving.</p> <p>Don't rule out "4", as the GIL will be dropped when a thread is actually doing or waiting for IO-operations (most of the time probably). It doesn't make sense if you've got huge numbers of connections of course. If you've got lots of processing to do, then python may not make sense with any of these schemes.</p> <p>For flexibility maybe look at <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a>?</p> <p>In practice your problem boils down to how much processing you are going to do for requests. If you've got a lot of processing, and need to take advantage of multi-core parallel operation, then you'll probably need multiple processes. On the other hand if you just need to listen on lots of connections, then select or epoll, with a small number of threads should work.</p>
7
2009-03-11T12:07:05Z
[ "python", "sockets", "asynchronous", "network-programming", "c10k" ]
Writing a socket-based server in Python, recommended strategies?
634,107
<p>I was recently reading <a href="http://www.kegel.com/c10k.html">this document</a> which lists a number of strategies that could be employed to implement a socket server. Namely, they are:</p> <ol> <li>Serve many clients with each thread, and use nonblocking I/O and level-triggered readiness notification</li> <li>Serve many clients with each thread, and use nonblocking I/O and readiness change notification</li> <li>Serve many clients with each server thread, and use asynchronous I/O</li> <li>serve one client with each server thread, and use blocking I/O</li> <li>Build the server code into the kernel </li> </ol> <p>Now, I would appreciate a hint on which should be used <strong>in CPython</strong>, which we know has some good points, and some bad points. I am mostly interested in performance under high concurrency, and yes a number of the current implementations are too slow.</p> <p>So if I may start with the easy one, "5" is out, as I am not going to be hacking anything into the kernel.</p> <p>"4" Also looks like it must be out because of the GIL. Of course, you could use multiprocessing in place of threads here, and that does give a significant boost. Blocking IO also has the advantage of being easier to understand.</p> <p>And here my knowledge wanes a bit:</p> <p>"1" is traditional select or poll which could be trivially combined with multiprocessing.</p> <p>"2" is the readiness-change notification, used by the newer epoll and kqueue</p> <p>"3" I am not sure there are any kernel implementations for this that have Python wrappers.</p> <p>So, in Python we have a bag of great tools like Twisted. Perhaps they are a better approach, though I have benchmarked Twisted and found it too slow on a multiple processor machine. Perhaps having 4 twisteds with a load balancer might do it, I don't know. Any advice would be appreciated.</p>
9
2009-03-11T11:15:27Z
634,288
<p>I like Douglas' answer, but as an aside...</p> <p>You could use a centralized dispatch thread/process that listens for readiness notifications using <a href="http://docs.python.org/library/select.html?highlight=select#module-select" rel="nofollow"><code>select</code></a> and delegates to a pool of worker threads/<a href="http://docs.python.org/library/multiprocessing.html#module-multiprocessing" rel="nofollow">processes</a> to help accomplish your parallelism goals.</p> <p>As Douglas mentioned, however, the GIL won't be held during most lengthy I/O operations (since no Python-API things are happening), so if it's response latency you're concerned about you can try moving the critical portions of your code to CPython API.</p>
1
2009-03-11T12:22:29Z
[ "python", "sockets", "asynchronous", "network-programming", "c10k" ]
Writing a socket-based server in Python, recommended strategies?
634,107
<p>I was recently reading <a href="http://www.kegel.com/c10k.html">this document</a> which lists a number of strategies that could be employed to implement a socket server. Namely, they are:</p> <ol> <li>Serve many clients with each thread, and use nonblocking I/O and level-triggered readiness notification</li> <li>Serve many clients with each thread, and use nonblocking I/O and readiness change notification</li> <li>Serve many clients with each server thread, and use asynchronous I/O</li> <li>serve one client with each server thread, and use blocking I/O</li> <li>Build the server code into the kernel </li> </ol> <p>Now, I would appreciate a hint on which should be used <strong>in CPython</strong>, which we know has some good points, and some bad points. I am mostly interested in performance under high concurrency, and yes a number of the current implementations are too slow.</p> <p>So if I may start with the easy one, "5" is out, as I am not going to be hacking anything into the kernel.</p> <p>"4" Also looks like it must be out because of the GIL. Of course, you could use multiprocessing in place of threads here, and that does give a significant boost. Blocking IO also has the advantage of being easier to understand.</p> <p>And here my knowledge wanes a bit:</p> <p>"1" is traditional select or poll which could be trivially combined with multiprocessing.</p> <p>"2" is the readiness-change notification, used by the newer epoll and kqueue</p> <p>"3" I am not sure there are any kernel implementations for this that have Python wrappers.</p> <p>So, in Python we have a bag of great tools like Twisted. Perhaps they are a better approach, though I have benchmarked Twisted and found it too slow on a multiple processor machine. Perhaps having 4 twisteds with a load balancer might do it, I don't know. Any advice would be appreciated.</p>
9
2009-03-11T11:15:27Z
634,958
<p>Can I suggest additional links?</p> <p><a href="http://code.google.com/p/cogen/" rel="nofollow">cogen</a> is a crossplatform library for network oriented, coroutine based programming using the enhanced generators from python 2.5. On the main page of cogen project there're links to several projects with similar purpose.</p>
2
2009-03-11T15:06:58Z
[ "python", "sockets", "asynchronous", "network-programming", "c10k" ]
Writing a socket-based server in Python, recommended strategies?
634,107
<p>I was recently reading <a href="http://www.kegel.com/c10k.html">this document</a> which lists a number of strategies that could be employed to implement a socket server. Namely, they are:</p> <ol> <li>Serve many clients with each thread, and use nonblocking I/O and level-triggered readiness notification</li> <li>Serve many clients with each thread, and use nonblocking I/O and readiness change notification</li> <li>Serve many clients with each server thread, and use asynchronous I/O</li> <li>serve one client with each server thread, and use blocking I/O</li> <li>Build the server code into the kernel </li> </ol> <p>Now, I would appreciate a hint on which should be used <strong>in CPython</strong>, which we know has some good points, and some bad points. I am mostly interested in performance under high concurrency, and yes a number of the current implementations are too slow.</p> <p>So if I may start with the easy one, "5" is out, as I am not going to be hacking anything into the kernel.</p> <p>"4" Also looks like it must be out because of the GIL. Of course, you could use multiprocessing in place of threads here, and that does give a significant boost. Blocking IO also has the advantage of being easier to understand.</p> <p>And here my knowledge wanes a bit:</p> <p>"1" is traditional select or poll which could be trivially combined with multiprocessing.</p> <p>"2" is the readiness-change notification, used by the newer epoll and kqueue</p> <p>"3" I am not sure there are any kernel implementations for this that have Python wrappers.</p> <p>So, in Python we have a bag of great tools like Twisted. Perhaps they are a better approach, though I have benchmarked Twisted and found it too slow on a multiple processor machine. Perhaps having 4 twisteds with a load balancer might do it, I don't know. Any advice would be appreciated.</p>
9
2009-03-11T11:15:27Z
634,965
<p>How about "fork"? (I assume that is what the ForkingMixIn does) If the requests are handled in a "shared nothing" (other than DB or file system) architecture, fork() starts pretty quickly on most *nixes, and you don't have to worry about all the silly bugs and complications from threading.</p> <p>Threads are a design illness forced on us by OSes with too-heavy-weight processes, IMHO. Cloning a page table with copy-on-write attributes seems a small price, especially if you are running an interpreter anyway.</p> <p>Sorry I can't be more specific, but I'm more of a Perl-transitioning-to-Ruby programmer (when I'm not slaving over masses of Java at work)</p> <hr> <p>Update: I finally did some timings on thread vs fork in my "spare time". Check it out:</p> <p><a href="http://roboprogs.com/devel/2009.04.html" rel="nofollow">http://roboprogs.com/devel/2009.04.html</a></p> <p>Expanded: <a href="http://roboprogs.com/devel/2009.12.html" rel="nofollow">http://roboprogs.com/devel/2009.12.html</a></p>
3
2009-03-11T15:07:41Z
[ "python", "sockets", "asynchronous", "network-programming", "c10k" ]
Writing a socket-based server in Python, recommended strategies?
634,107
<p>I was recently reading <a href="http://www.kegel.com/c10k.html">this document</a> which lists a number of strategies that could be employed to implement a socket server. Namely, they are:</p> <ol> <li>Serve many clients with each thread, and use nonblocking I/O and level-triggered readiness notification</li> <li>Serve many clients with each thread, and use nonblocking I/O and readiness change notification</li> <li>Serve many clients with each server thread, and use asynchronous I/O</li> <li>serve one client with each server thread, and use blocking I/O</li> <li>Build the server code into the kernel </li> </ol> <p>Now, I would appreciate a hint on which should be used <strong>in CPython</strong>, which we know has some good points, and some bad points. I am mostly interested in performance under high concurrency, and yes a number of the current implementations are too slow.</p> <p>So if I may start with the easy one, "5" is out, as I am not going to be hacking anything into the kernel.</p> <p>"4" Also looks like it must be out because of the GIL. Of course, you could use multiprocessing in place of threads here, and that does give a significant boost. Blocking IO also has the advantage of being easier to understand.</p> <p>And here my knowledge wanes a bit:</p> <p>"1" is traditional select or poll which could be trivially combined with multiprocessing.</p> <p>"2" is the readiness-change notification, used by the newer epoll and kqueue</p> <p>"3" I am not sure there are any kernel implementations for this that have Python wrappers.</p> <p>So, in Python we have a bag of great tools like Twisted. Perhaps they are a better approach, though I have benchmarked Twisted and found it too slow on a multiple processor machine. Perhaps having 4 twisteds with a load balancer might do it, I don't know. Any advice would be appreciated.</p>
9
2009-03-11T11:15:27Z
3,221,702
<p>One sollution is gevent. <a href="http://www.gevent.org/" rel="nofollow">Gevent</a> maries a libevent based event polling with lightweight cooperative task switching implemented by greenlet.</p> <p>What you get is all the performance and scalability of an event system with the elegance and straightforward model of blocking IO programing.</p> <p>(I don't know what the SO convention about answering to realy old questions is, but decided I'd still add my 2 cents)</p>
3
2010-07-11T03:07:11Z
[ "python", "sockets", "asynchronous", "network-programming", "c10k" ]
Need help on making the recursive parser using pyparsing
634,432
<p>I am trying the python pyparsing for parsing. I got stuck up while making the recursive parser. </p> <p>Let me explain the problem </p> <p>I want to make the Cartesian product of the elements. The syntax is </p> <pre><code>cross({elements },{element}) </code></pre> <p>I put in more specific way</p> <pre><code>cross({a},{c1}) or cross({a,b},{c1}) or cross({a,b,c,d},{c1}) or </code></pre> <p>So the general form is first group will have n elements (a,b,c,d). The second group will have one element that so the final output will be Cartesian Product.</p> <p>The syntax is to be made recursive because it can go to n level like</p> <pre><code>cross(cross({a,b},{c1}),{c2}) </code></pre> <p>This means cross a,b with c1. Lets say outcome us y. We again cross y it with c2</p> <p>This can be till n level cross(cross(cross(cross......</p> <p>What i want is to have object to be initialized using setparseAction </p> <p>So i will have 2 class </p> <pre><code>class object1(object): This will be used by a,b,c,d class object2(object): This will hold cross elements </code></pre> <p>I need help on this i am not able to make the recursive parser.</p>
2
2009-03-11T13:07:53Z
634,460
<p>You should look at definitions of other languages to see how this is usually handled.</p> <p>For example, look at how multiplication is defined.</p> <p>It isn't</p> <pre><code>{expression} * {expression} </code></pre> <p>Because the recursion is hard to deal with, and there's no implied left-to-right ordering. What you see more often are things like</p> <pre><code>{term} + {factor} {factor} * {unary-expression} </code></pre> <p>Which puts priorities and a left-to-right ordering around the operators.</p> <p>Look at something like <a href="http://www.cs.man.ac.uk/~pjj/bnf/c_syntax.bnf" rel="nofollow">http://www.cs.man.ac.uk/~pjj/bnf/c_syntax.bnf</a> for examples of how things like this are commonly structured.</p>
6
2009-03-11T13:14:33Z
[ "python", "recursion", "parsing", "pyparsing" ]
Need help on making the recursive parser using pyparsing
634,432
<p>I am trying the python pyparsing for parsing. I got stuck up while making the recursive parser. </p> <p>Let me explain the problem </p> <p>I want to make the Cartesian product of the elements. The syntax is </p> <pre><code>cross({elements },{element}) </code></pre> <p>I put in more specific way</p> <pre><code>cross({a},{c1}) or cross({a,b},{c1}) or cross({a,b,c,d},{c1}) or </code></pre> <p>So the general form is first group will have n elements (a,b,c,d). The second group will have one element that so the final output will be Cartesian Product.</p> <p>The syntax is to be made recursive because it can go to n level like</p> <pre><code>cross(cross({a,b},{c1}),{c2}) </code></pre> <p>This means cross a,b with c1. Lets say outcome us y. We again cross y it with c2</p> <p>This can be till n level cross(cross(cross(cross......</p> <p>What i want is to have object to be initialized using setparseAction </p> <p>So i will have 2 class </p> <pre><code>class object1(object): This will be used by a,b,c,d class object2(object): This will hold cross elements </code></pre> <p>I need help on this i am not able to make the recursive parser.</p>
2
2009-03-11T13:07:53Z
634,725
<p>I agree with @S.Lott you should reconsider your grammar.</p> <p>Recursive definitions can be introduced using <code>Forward()</code>:</p> <pre><code>from pyparsing import (Literal, Word, OneOrMore, Forward, nums, alphas) def BNF(): """ element :: id elements :: '{' element [ ',' element ]+ '}' | 'cross' '(' elements ',' '{' element '}' ')' """ lcb, rcb, lb, rb, comma = [Literal(c).suppress() for c in '{}(),'] element = Word(alphas, alphas+nums+"_") # id elements = Forward() elements &lt;&lt; ((lcb + element + OneOrMore(comma + element) + rcb) | (Literal('cross') + lb + elements + comma + lcb + element + rcb + rb)) return elements print BNF().parseString("cross(cross({a,b},{c1}),{c2})") </code></pre> <p>Output:</p> <pre><code>['cross', 'cross', 'a', 'b', 'c1', 'c2'] </code></pre>
3
2009-03-11T14:24:58Z
[ "python", "recursion", "parsing", "pyparsing" ]
Need help on making the recursive parser using pyparsing
634,432
<p>I am trying the python pyparsing for parsing. I got stuck up while making the recursive parser. </p> <p>Let me explain the problem </p> <p>I want to make the Cartesian product of the elements. The syntax is </p> <pre><code>cross({elements },{element}) </code></pre> <p>I put in more specific way</p> <pre><code>cross({a},{c1}) or cross({a,b},{c1}) or cross({a,b,c,d},{c1}) or </code></pre> <p>So the general form is first group will have n elements (a,b,c,d). The second group will have one element that so the final output will be Cartesian Product.</p> <p>The syntax is to be made recursive because it can go to n level like</p> <pre><code>cross(cross({a,b},{c1}),{c2}) </code></pre> <p>This means cross a,b with c1. Lets say outcome us y. We again cross y it with c2</p> <p>This can be till n level cross(cross(cross(cross......</p> <p>What i want is to have object to be initialized using setparseAction </p> <p>So i will have 2 class </p> <pre><code>class object1(object): This will be used by a,b,c,d class object2(object): This will hold cross elements </code></pre> <p>I need help on this i am not able to make the recursive parser.</p>
2
2009-03-11T13:07:53Z
1,673,407
<p>I don't know if this is any help, but here is how you would do what you want in lepl. Since the grammar appears to be correct I assume that it would be easy to translate to pyparsing.</p> <pre><code>from lepl import * def compile_parser(): class Cross(Node): pass word = Token('[a-z0-9]+') par, en, bra, ket = [~Token('\\'+c) for c in '(){}'] comma = ~Token(',') cross = Delayed() vector = bra &amp; word[1:,comma] &amp; ket &gt; list arg = vector | cross cross += ~word('cross') &amp; par &amp; arg[2,comma] &amp; en &gt; Cross parser = cross.string_parser() return lambda expr: parser(expr)[0] if __name__ == '__main__': parser = compile_parser() print parser('cross({a},{c1})') print parser('cross({a,b},{c1})') print parser('cross({a,b,c,d},{c1})') print parser('cross(cross({a,b},{c1}),{c2})') </code></pre> <p>The output is:</p> <pre><code>Cross +- [u'a'] `- [u'c1'] Cross +- [u'a', u'b'] `- [u'c1'] Cross +- [u'a', u'b', u'c', u'd'] `- [u'c1'] Cross +- Cross | +- [u'a', u'b'] | `- [u'c1'] `- [u'c2'] </code></pre>
3
2009-11-04T12:08:47Z
[ "python", "recursion", "parsing", "pyparsing" ]
using wsgiref.simple_server in unittests
634,485
<p>I have some functions like this one:</p> <pre> <code> URL = 'http://localhost:8080' def func(): response = urlopen(URL) return process(response) </code> </pre> <p>And i want to test it with unittest.</p> <p>I did something like this:</p> <pre><code> from wsgiref.simple_server import make_server def app_200_hello(environ,start_response): stdout = StringIO('Hello world') start_response("200 OK", [('Content-Type','text/plain')]) return [stdout.getvalue()] s = make_server('localhost', 8080, app_200_hello) class TestFunc(unittest.TestCase): def setUp(self): s.handle_request() def test1(self): r = func() assert r, something if __name__ == '__main__': unittest.main() </code></pre> <p>At setUp() my tests stop because s.handle_request() waits for request. How i can get around that? Run s.handle_request() in another thread? or maybe there is another solution?</p> <p>EDIT: I want to test "func" function, not "app_200_hello"</p>
3
2009-03-11T13:22:09Z
634,571
<p>If you are testing a WSGI application, I can strongly recommend <a href="http://werkzeug.pocoo.org/documentation/test">werkzeug.test</a> which gets around these issues by testing the application itself without a server:</p> <pre><code>from werkzeug.test import Client # then in your test case def test1(self): client = Client(app_200_hello) appiter, status, headers = client.open() assert ''.join(appiter) == 'Hello World' assert status == '200 OK' </code></pre> <p>This approach just removes the need for a WSGI server altogether.</p> <p>Of course if you did want to start a server, you would have to use a separate thread or a process, but then you have to make sure you stop it afterwards. However, it strikes me that the only time you would want to test with a real server is for production integration testing, in which case your server won't be wsgiref, it will be a real server that you probably won't have to start-stop like this.</p>
7
2009-03-11T13:44:29Z
[ "python", "unit-testing", "wsgiref" ]
using wsgiref.simple_server in unittests
634,485
<p>I have some functions like this one:</p> <pre> <code> URL = 'http://localhost:8080' def func(): response = urlopen(URL) return process(response) </code> </pre> <p>And i want to test it with unittest.</p> <p>I did something like this:</p> <pre><code> from wsgiref.simple_server import make_server def app_200_hello(environ,start_response): stdout = StringIO('Hello world') start_response("200 OK", [('Content-Type','text/plain')]) return [stdout.getvalue()] s = make_server('localhost', 8080, app_200_hello) class TestFunc(unittest.TestCase): def setUp(self): s.handle_request() def test1(self): r = func() assert r, something if __name__ == '__main__': unittest.main() </code></pre> <p>At setUp() my tests stop because s.handle_request() waits for request. How i can get around that? Run s.handle_request() in another thread? or maybe there is another solution?</p> <p>EDIT: I want to test "func" function, not "app_200_hello"</p>
3
2009-03-11T13:22:09Z
634,622
<p>Your server must be a separate process.</p> <p>You'll want to start it with <code>subprocess.Popen()</code></p> <p>If you're using Python 2.6, you can then kill the subprocess during tearDown.</p> <pre><code>def setUp( self ): self.server= subprocess.Popen( "python","myserver","etc." ) def tearDown( self ): self.server.kill() </code></pre> <p>If you're not using Python 2.6, killing the server can be unpleasant. </p>
3
2009-03-11T13:59:16Z
[ "python", "unit-testing", "wsgiref" ]
using wsgiref.simple_server in unittests
634,485
<p>I have some functions like this one:</p> <pre> <code> URL = 'http://localhost:8080' def func(): response = urlopen(URL) return process(response) </code> </pre> <p>And i want to test it with unittest.</p> <p>I did something like this:</p> <pre><code> from wsgiref.simple_server import make_server def app_200_hello(environ,start_response): stdout = StringIO('Hello world') start_response("200 OK", [('Content-Type','text/plain')]) return [stdout.getvalue()] s = make_server('localhost', 8080, app_200_hello) class TestFunc(unittest.TestCase): def setUp(self): s.handle_request() def test1(self): r = func() assert r, something if __name__ == '__main__': unittest.main() </code></pre> <p>At setUp() my tests stop because s.handle_request() waits for request. How i can get around that? Run s.handle_request() in another thread? or maybe there is another solution?</p> <p>EDIT: I want to test "func" function, not "app_200_hello"</p>
3
2009-03-11T13:22:09Z
634,907
<p>My solution:</p> <pre> <code> URL = 'http://localhost:8085' def func(): response = urlopen(URL) return response.read() import unittest from wsgiref.simple_server import WSGIServer, WSGIRequestHandler import threading from urllib2 import urlopen from cStringIO import StringIO def app_200_hello(environ,start_response): stdout = StringIO('Hello world') start_response("200 OK", [('Content-Type','text/plain')]) return [stdout.getvalue()] server = WSGIServer(('localhost', 8085), WSGIRequestHandler) server.set_app(app_200_hello) t = threading.Thread(target=server.serve_forever) t.start() class TestFunc(unittest.TestCase): def setUp(self): pass def test1(self): r = func() self.assertEqual(r, 'Hello world') def __del__(self): server.shutdown() if __name__ == '__main__': unittest.main() </code> </pre> <p>I start "server" in another thread and shutdown it at TestFunc destructor.</p>
0
2009-03-11T14:58:23Z
[ "python", "unit-testing", "wsgiref" ]
using wsgiref.simple_server in unittests
634,485
<p>I have some functions like this one:</p> <pre> <code> URL = 'http://localhost:8080' def func(): response = urlopen(URL) return process(response) </code> </pre> <p>And i want to test it with unittest.</p> <p>I did something like this:</p> <pre><code> from wsgiref.simple_server import make_server def app_200_hello(environ,start_response): stdout = StringIO('Hello world') start_response("200 OK", [('Content-Type','text/plain')]) return [stdout.getvalue()] s = make_server('localhost', 8080, app_200_hello) class TestFunc(unittest.TestCase): def setUp(self): s.handle_request() def test1(self): r = func() assert r, something if __name__ == '__main__': unittest.main() </code></pre> <p>At setUp() my tests stop because s.handle_request() waits for request. How i can get around that? Run s.handle_request() in another thread? or maybe there is another solution?</p> <p>EDIT: I want to test "func" function, not "app_200_hello"</p>
3
2009-03-11T13:22:09Z
635,306
<p>You could also provide a mock version of <code>urlopen</code> that doesn't actually run the server.</p> <p>Assuming your original code was in <code>mycode.py</code>, in your test code you'd do something like:</p> <pre><code> import mycode class TestFunc(unittest.TestCase): def setUp(self): # patch mycode, to use mock version of urlopen self._original_urlopen = mycode.urlopen mycode.urlopen=self.mock_urlopen def tearDown(self): # unpatch urlopen mycode.urlopen=self._original_urlopen def mock_urlopen(self,url): # return whatever data you need urlopen to return def test1(self): r = func() assert r, something if __name__ == '__main__': unittest.main() </code></pre> <p>This is known as "monkey patching" which some frown upon, but for testing your code it can make life a lot easier, as you don't need to change your original code to make it testable.</p>
2
2009-03-11T16:28:20Z
[ "python", "unit-testing", "wsgiref" ]
using wsgiref.simple_server in unittests
634,485
<p>I have some functions like this one:</p> <pre> <code> URL = 'http://localhost:8080' def func(): response = urlopen(URL) return process(response) </code> </pre> <p>And i want to test it with unittest.</p> <p>I did something like this:</p> <pre><code> from wsgiref.simple_server import make_server def app_200_hello(environ,start_response): stdout = StringIO('Hello world') start_response("200 OK", [('Content-Type','text/plain')]) return [stdout.getvalue()] s = make_server('localhost', 8080, app_200_hello) class TestFunc(unittest.TestCase): def setUp(self): s.handle_request() def test1(self): r = func() assert r, something if __name__ == '__main__': unittest.main() </code></pre> <p>At setUp() my tests stop because s.handle_request() waits for request. How i can get around that? Run s.handle_request() in another thread? or maybe there is another solution?</p> <p>EDIT: I want to test "func" function, not "app_200_hello"</p>
3
2009-03-11T13:22:09Z
6,564,500
<p>Use multiprocessing to start the server in a separate process</p> <p>in setUp do something like: </p> <pre><code>self.port = 8000 server = make_server('', self.port, make_my_wsgi_ap()) self.server_process = multiprocessing.Process(target=server.serve_forever) self.server_process.start() </code></pre> <p>then in tearDown do:</p> <pre><code>self.server_process.terminate() self.server_process.join() del(self.server_process) </code></pre> <p>I've found that if you don't explicitly put the del() in there then subsequent server instances may have a problem with the port already being used.</p>
4
2011-07-03T17:49:28Z
[ "python", "unit-testing", "wsgiref" ]
Django: Calling custom Model method from Form clean method. "Unbound Method"?
634,857
<p>I'm having a problem while trying to call a custom Model method from my Form <code>clean</code> method.</p> <p>Here is [part of] my model:<br /> <a href="http://dpaste.com/hold/12695/" rel="nofollow">http://dpaste.com/hold/12695/</a></p> <p>Here is my Form:<br /> <a href="http://dpaste.com/hold/12699/" rel="nofollow">http://dpaste.com/hold/12699/</a></p> <p>I'm specifically having a problem with line 11 in my Form:<br /> <code>nzb_data = File.get_nzb_data(nzb_absolute)</code></p> <p>This raises the following error:</p> <pre><code>TypeError at /admin/main/file/add/ unbound method get_nzb_data() must be called with File instance as first argument (got str instance instead) </code></pre> <p>By this error I can assume I have to pass the method something (a File instance), however I don't really know what that means and how I can do it.</p> <p>Can you let me know what I'm doing wrong here, and what can be done to resolve the issue?</p> <p><hr /></p> <p><strong>Solved</strong> by making the <code>get_nzb_data</code> method a class method using the <code>@classmethod</code> decorator.</p>
1
2009-03-11T14:51:12Z
634,885
<p>You can't call </p> <pre><code>nzb_data = File.get_nzb_data(nzb_absolute) </code></pre> <p>because your using the class, not an object.</p> <p>You have two choices.</p> <ol> <li><p>Make <code>get_nzb_data</code> a <code>@classmethod</code>. See <a href="http://docs.python.org/library/functions.html#classmethod" rel="nofollow">http://docs.python.org/library/functions.html#classmethod</a></p></li> <li><p>Create an instance of File and use that. <code>temp_f= File(...)</code>. Then <code>temp_f.get_dnb_data</code>.</p></li> </ol>
3
2009-03-11T14:54:39Z
[ "python", "django" ]
Django: Calling custom Model method from Form clean method. "Unbound Method"?
634,857
<p>I'm having a problem while trying to call a custom Model method from my Form <code>clean</code> method.</p> <p>Here is [part of] my model:<br /> <a href="http://dpaste.com/hold/12695/" rel="nofollow">http://dpaste.com/hold/12695/</a></p> <p>Here is my Form:<br /> <a href="http://dpaste.com/hold/12699/" rel="nofollow">http://dpaste.com/hold/12699/</a></p> <p>I'm specifically having a problem with line 11 in my Form:<br /> <code>nzb_data = File.get_nzb_data(nzb_absolute)</code></p> <p>This raises the following error:</p> <pre><code>TypeError at /admin/main/file/add/ unbound method get_nzb_data() must be called with File instance as first argument (got str instance instead) </code></pre> <p>By this error I can assume I have to pass the method something (a File instance), however I don't really know what that means and how I can do it.</p> <p>Can you let me know what I'm doing wrong here, and what can be done to resolve the issue?</p> <p><hr /></p> <p><strong>Solved</strong> by making the <code>get_nzb_data</code> method a class method using the <code>@classmethod</code> decorator.</p>
1
2009-03-11T14:51:12Z
634,902
<p>I may be missing something here, but I think that your method ´get_nzb_data´ should have a @classmethod decorator. Otherwise, it expects the ´self´ argument of the type File, and this gives that error.</p>
1
2009-03-11T14:57:20Z
[ "python", "django" ]
svg diagrams using python
634,964
<p>I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found <a href="http://newcenturycomputers.net/projects/gdmodule.html">python-gd</a>, but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose.</p> <p>I am mostly thinking about simple line graphs, something like <a href="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg">this</a>: <img src="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg" alt="example line graph" title="days on market" /></p>
20
2009-03-11T15:07:39Z
634,998
<p>Here's a general purpose SVG library in Python: <a href="http://codeboje.de/pysvg/">pySVG</a>.</p>
7
2009-03-11T15:15:47Z
[ "python", "svg", "diagram" ]
svg diagrams using python
634,964
<p>I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found <a href="http://newcenturycomputers.net/projects/gdmodule.html">python-gd</a>, but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose.</p> <p>I am mostly thinking about simple line graphs, something like <a href="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg">this</a>: <img src="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg" alt="example line graph" title="days on market" /></p>
20
2009-03-11T15:07:39Z
635,001
<p>Try using <a href="http://matplotlib.sourceforge.net/">matplotlib</a>. You can configure it with a SVG <a href="http://matplotlib.sourceforge.net/faq/installing%5Ffaq.html#what-is-a-backend">backend</a>.</p>
9
2009-03-11T15:16:51Z
[ "python", "svg", "diagram" ]
svg diagrams using python
634,964
<p>I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found <a href="http://newcenturycomputers.net/projects/gdmodule.html">python-gd</a>, but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose.</p> <p>I am mostly thinking about simple line graphs, something like <a href="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg">this</a>: <img src="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg" alt="example line graph" title="days on market" /></p>
20
2009-03-11T15:07:39Z
635,002
<p><a href="http://home.gna.org/pychart/">PyChart</a> <em>"is a Python library for creating high quality Encapsulated Postscript, PDF, PNG, or <strong>SVG</strong> charts."</em></p>
9
2009-03-11T15:16:53Z
[ "python", "svg", "diagram" ]
svg diagrams using python
634,964
<p>I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found <a href="http://newcenturycomputers.net/projects/gdmodule.html">python-gd</a>, but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose.</p> <p>I am mostly thinking about simple line graphs, something like <a href="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg">this</a>: <img src="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg" alt="example line graph" title="days on market" /></p>
20
2009-03-11T15:07:39Z
635,096
<p><a href="http://cairographics.org/pycairo/">pyCairo</a> is an option worth looking at.</p>
8
2009-03-11T15:36:41Z
[ "python", "svg", "diagram" ]
svg diagrams using python
634,964
<p>I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found <a href="http://newcenturycomputers.net/projects/gdmodule.html">python-gd</a>, but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose.</p> <p>I am mostly thinking about simple line graphs, something like <a href="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg">this</a>: <img src="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg" alt="example line graph" title="days on market" /></p>
20
2009-03-11T15:07:39Z
635,149
<p>As you're looking for simple line graphics, probably, <a href="http://linil.wordpress.com/2008/09/16/cairoplot-11/">CairoPlot</a> will fit your needs as it can generate svg output files out of the box. Take a look at <a href="http://linil.files.wordpress.com/2008/06/cairoplot%5Fdotlineplot.png">this</a>.</p> <p><img src="http://linil.files.wordpress.com/2008/06/cairoplot%5Fdotlineplot.png?w=450h=300" alt="CairoPlot - DotLinePlot" /></p> <p>This example image shows only a few of its capabilities. Using the trunk version available at <a href="http://launchpad.net/cairoplot">launchpad</a> you'll be able to add a legend box and add axis titles.</p> <p>Besides that, using the trunk version, it's possible to generate:</p> <ul> <li>DotLine charts (the ones I believe you need)</li> <li>Scatter charts</li> <li>Pie/Donut charts</li> <li>Horizontal/Vertical Bar charts</li> <li>Gantt charts</li> </ul>
10
2009-03-11T15:50:55Z
[ "python", "svg", "diagram" ]
svg diagrams using python
634,964
<p>I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found <a href="http://newcenturycomputers.net/projects/gdmodule.html">python-gd</a>, but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose.</p> <p>I am mostly thinking about simple line graphs, something like <a href="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg">this</a>: <img src="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg" alt="example line graph" title="days on market" /></p>
20
2009-03-11T15:07:39Z
635,259
<p>You can use <a href="http://www.graphviz.org/" rel="nofollow">Graphviz</a> to generate diagrams in SVG format. There are Python bindings to Graphviz e.g., <a href="http://code.google.com/p/pydot/" rel="nofollow">pydot</a> -- Python interface to Graphviz's Dot language.</p>
6
2009-03-11T16:16:54Z
[ "python", "svg", "diagram" ]
svg diagrams using python
634,964
<p>I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found <a href="http://newcenturycomputers.net/projects/gdmodule.html">python-gd</a>, but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose.</p> <p>I am mostly thinking about simple line graphs, something like <a href="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg">this</a>: <img src="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg" alt="example line graph" title="days on market" /></p>
20
2009-03-11T15:07:39Z
2,937,225
<p>svgfig is worth a look:</p> <p><a href="http://code.google.com/p/svgfig/" rel="nofollow">http://code.google.com/p/svgfig/</a></p>
3
2010-05-30T01:36:32Z
[ "python", "svg", "diagram" ]
svg diagrams using python
634,964
<p>I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found <a href="http://newcenturycomputers.net/projects/gdmodule.html">python-gd</a>, but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose.</p> <p>I am mostly thinking about simple line graphs, something like <a href="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg">this</a>: <img src="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg" alt="example line graph" title="days on market" /></p>
20
2009-03-11T15:07:39Z
7,419,825
<p>Being not exactly related to SVG plots, but searching for the same thing I have found a good source of carefully collected useful info to answer your question: <a href="http://wiki.python.org/moin/NumericAndScientific/Plotting" rel="nofollow">http://wiki.python.org/moin/NumericAndScientific/Plotting</a></p>
0
2011-09-14T16:36:11Z
[ "python", "svg", "diagram" ]
svg diagrams using python
634,964
<p>I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found <a href="http://newcenturycomputers.net/projects/gdmodule.html">python-gd</a>, but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose.</p> <p>I am mostly thinking about simple line graphs, something like <a href="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg">this</a>: <img src="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg" alt="example line graph" title="days on market" /></p>
20
2009-03-11T15:07:39Z
7,831,808
<p>I have tried to collate a list of available charting libraries(its an ongoing work, wherein i keep updating the list) : <a href="http://blizzardzblogs.blogspot.com/2010/12/data-visualization-charts-and.html" rel="nofollow">http://blizzardzblogs.blogspot.com/2010/12/data-visualization-charts-and.html</a></p> <p>I feel that protovis would do the job for you. Its </p> <ul> <li>light weight, </li> <li>generates svg (which can be exported easily) and </li> <li>is javascript</li> </ul> <p>So nothing more to learn :)</p>
0
2011-10-20T06:11:43Z
[ "python", "svg", "diagram" ]
svg diagrams using python
634,964
<p>I am looking for a library to generate svg diagrams in python (I fetch data from a sql database). I have found <a href="http://newcenturycomputers.net/projects/gdmodule.html">python-gd</a>, but it has not much documentation and last update was in 2005 so I wonder if there are any other libraries that are good for this purpose.</p> <p>I am mostly thinking about simple line graphs, something like <a href="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg">this</a>: <img src="http://edynblog.files.wordpress.com/2007/07/line-graph-days-on-market.jpg" alt="example line graph" title="days on market" /></p>
20
2009-03-11T15:07:39Z
10,662,071
<p>Consider svgwrite <a href="http://packages.python.org/svgwrite/" rel="nofollow">http://packages.python.org/svgwrite/</a></p>
1
2012-05-19T03:27:07Z
[ "python", "svg", "diagram" ]
Django Admin
635,048
<p>I am using Django admin for managing my data. I have a Users, Groups and Domains tables Users table has many to many relationship with Groups and Domains tables. Domains table has one to many relationship with Groups table. and when I save the User data through admin I also need some addtional database updates in the users_group and the users_domains table. How do I do this? Where do I put the code. Thanks. </p>
0
2009-03-11T15:28:10Z
635,087
<p>I think you are looking for <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects" rel="nofollow">InlineModels</a>. They allow you to edit related models in the same page as the parent model. If you are looking for greater control than this, you can override the ModelAdmin <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#modeladmin-methods" rel="nofollow">save methods</a>.</p> <p>Also, always check out the <a href="http://docs.djangoproject.com/en/dev/" rel="nofollow">Manual</a> when you need something. It really is quite good.</p>
2
2009-03-11T15:33:25Z
[ "python", "django", "django-admin" ]
Django Admin
635,048
<p>I am using Django admin for managing my data. I have a Users, Groups and Domains tables Users table has many to many relationship with Groups and Domains tables. Domains table has one to many relationship with Groups table. and when I save the User data through admin I also need some addtional database updates in the users_group and the users_domains table. How do I do this? Where do I put the code. Thanks. </p>
0
2009-03-11T15:28:10Z
638,957
<p>The best way to update other database tables is to perform the necessary get and save operations. However, if you have a many-to-many relationship, by default, both sides of the relationship are accessible from a _set parameter. That is, user.group_set.all() will give you all Group objects associated with a user, while group.user_set.all() will give you all User objects associated with a group. So if you override the save method (or register a signal listener--whichever option sounds stylistically more pleasing), try:</p> <pre><code>for group in user.group_set.all(): #play with group object .... group.save() </code></pre>
0
2009-03-12T14:45:48Z
[ "python", "django", "django-admin" ]
Python urllib2, basic HTTP authentication, and tr.im
635,113
<p>I'm playing around, trying to write some code to use the <a href="http://www.programmableweb.com/api/tr.im">tr.im</a> APIs to shorten a URL.</p> <p>After reading <a href="http://docs.python.org/library/urllib2.html">http://docs.python.org/library/urllib2.html</a>, I tried:</p> <pre><code> TRIM_API_URL = 'http://api.tr.im/api' auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm='tr.im', uri=TRIM_API_URL, user=USERNAME, passwd=PASSWORD) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() </code></pre> <p>response.code is 200 (I think it should be 202). url is valid, but the basic HTTP authentication doesn't seem to have worked, because the shortened URL isn't in my list of URLs (at <a href="http://ttp://tr.im/?page=1">http://tr.im/?page=1</a>).</p> <p>After reading <a href="http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly">http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly</a> I also tried:</p> <pre><code> TRIM_API_URL = 'api.tr.im/api' password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, TRIM_API_URL, USERNAME, PASSWORD) auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('http://%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() </code></pre> <p>But I get the same results. (response.code is 200 and url is valid, but not recorded in my account at <a href="http://tr.im/">http://tr.im/</a>.)</p> <p>If I use query string parameters instead of basic HTTP authentication, like this:</p> <pre><code> TRIM_API_URL = 'http://api.tr.im/api' response = urllib2.urlopen('%s/trim_simple?url=%s&amp;username=%s&amp;password=%s' % (TRIM_API_URL, url_to_trim, USERNAME, PASSWORD)) url = response.read().strip() </code></pre> <p>...then not only is url valid but it's recorded in my tr.im account. (Though response.code is still 200.)</p> <p>There must be something wrong with my code though (and not tr.im's API), because</p> <pre><code>$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk </code></pre> <p>...returns:</p> <pre><code>{"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"200","message":"tr.im URL Added."},"date_time":"2009-03-11T10:15:35-04:00"} </code></pre> <p>...and the URL does appear in my list of URLs on <a href="http://ttp://tr.im/?page=1">http://tr.im/?page=1</a>.</p> <p>And if I run:</p> <pre><code>$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk </code></pre> <p>...again, I get:</p> <pre><code>{"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"201","message":"tr.im URL Already Created [yacitus]."},"date_time":"2009-03-11T10:15:35-04:00"} </code></pre> <p>Note code is 201, and message is "tr.im URL Already Created [yacitus]."</p> <p>I must not be doing the basic HTTP authentication correctly (in either attempt). Can you spot my problem? Perhaps I should look and see what's being sent over the wire? I've never done that before. Are there Python APIs I can use (perhaps in pdb)? Or is there another tool (preferably for Mac OS X) I can use?</p>
62
2009-03-11T15:43:10Z
635,146
<p>Really cheap solution:</p> <pre><code>urllib.urlopen('http://user:xxxx@api.tr.im/api') </code></pre> <p>(which you may decide is not suitable for a number of reasons, like security of the url) </p> <p><a href="https://developer.github.com/v3/auth/#via-oauth-tokens">Github API example</a>:</p> <pre><code>&gt;&gt;&gt; import urllib, json &gt;&gt;&gt; result = urllib.urlopen('https://personal-access-token:x-oauth-basic@api.github.com/repos/:owner/:repo') &gt;&gt;&gt; r = json.load(result.fp) &gt;&gt;&gt; result.close() </code></pre>
16
2009-03-11T15:50:08Z
[ "python", "http", "authentication" ]
Python urllib2, basic HTTP authentication, and tr.im
635,113
<p>I'm playing around, trying to write some code to use the <a href="http://www.programmableweb.com/api/tr.im">tr.im</a> APIs to shorten a URL.</p> <p>After reading <a href="http://docs.python.org/library/urllib2.html">http://docs.python.org/library/urllib2.html</a>, I tried:</p> <pre><code> TRIM_API_URL = 'http://api.tr.im/api' auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm='tr.im', uri=TRIM_API_URL, user=USERNAME, passwd=PASSWORD) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() </code></pre> <p>response.code is 200 (I think it should be 202). url is valid, but the basic HTTP authentication doesn't seem to have worked, because the shortened URL isn't in my list of URLs (at <a href="http://ttp://tr.im/?page=1">http://tr.im/?page=1</a>).</p> <p>After reading <a href="http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly">http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly</a> I also tried:</p> <pre><code> TRIM_API_URL = 'api.tr.im/api' password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, TRIM_API_URL, USERNAME, PASSWORD) auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('http://%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() </code></pre> <p>But I get the same results. (response.code is 200 and url is valid, but not recorded in my account at <a href="http://tr.im/">http://tr.im/</a>.)</p> <p>If I use query string parameters instead of basic HTTP authentication, like this:</p> <pre><code> TRIM_API_URL = 'http://api.tr.im/api' response = urllib2.urlopen('%s/trim_simple?url=%s&amp;username=%s&amp;password=%s' % (TRIM_API_URL, url_to_trim, USERNAME, PASSWORD)) url = response.read().strip() </code></pre> <p>...then not only is url valid but it's recorded in my tr.im account. (Though response.code is still 200.)</p> <p>There must be something wrong with my code though (and not tr.im's API), because</p> <pre><code>$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk </code></pre> <p>...returns:</p> <pre><code>{"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"200","message":"tr.im URL Added."},"date_time":"2009-03-11T10:15:35-04:00"} </code></pre> <p>...and the URL does appear in my list of URLs on <a href="http://ttp://tr.im/?page=1">http://tr.im/?page=1</a>.</p> <p>And if I run:</p> <pre><code>$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk </code></pre> <p>...again, I get:</p> <pre><code>{"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"201","message":"tr.im URL Already Created [yacitus]."},"date_time":"2009-03-11T10:15:35-04:00"} </code></pre> <p>Note code is 201, and message is "tr.im URL Already Created [yacitus]."</p> <p>I must not be doing the basic HTTP authentication correctly (in either attempt). Can you spot my problem? Perhaps I should look and see what's being sent over the wire? I've never done that before. Are there Python APIs I can use (perhaps in pdb)? Or is there another tool (preferably for Mac OS X) I can use?</p>
62
2009-03-11T15:43:10Z
4,188,709
<p>This seems to work really well (taken from another thread)</p> <pre><code>import urllib2, base64 request = urllib2.Request("http://api.foursquare.com/v1/user") base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') request.add_header("Authorization", "Basic %s" % base64string) result = urllib2.urlopen(request) </code></pre>
210
2010-11-15T20:52:54Z
[ "python", "http", "authentication" ]
Python urllib2, basic HTTP authentication, and tr.im
635,113
<p>I'm playing around, trying to write some code to use the <a href="http://www.programmableweb.com/api/tr.im">tr.im</a> APIs to shorten a URL.</p> <p>After reading <a href="http://docs.python.org/library/urllib2.html">http://docs.python.org/library/urllib2.html</a>, I tried:</p> <pre><code> TRIM_API_URL = 'http://api.tr.im/api' auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm='tr.im', uri=TRIM_API_URL, user=USERNAME, passwd=PASSWORD) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() </code></pre> <p>response.code is 200 (I think it should be 202). url is valid, but the basic HTTP authentication doesn't seem to have worked, because the shortened URL isn't in my list of URLs (at <a href="http://ttp://tr.im/?page=1">http://tr.im/?page=1</a>).</p> <p>After reading <a href="http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly">http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly</a> I also tried:</p> <pre><code> TRIM_API_URL = 'api.tr.im/api' password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, TRIM_API_URL, USERNAME, PASSWORD) auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('http://%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() </code></pre> <p>But I get the same results. (response.code is 200 and url is valid, but not recorded in my account at <a href="http://tr.im/">http://tr.im/</a>.)</p> <p>If I use query string parameters instead of basic HTTP authentication, like this:</p> <pre><code> TRIM_API_URL = 'http://api.tr.im/api' response = urllib2.urlopen('%s/trim_simple?url=%s&amp;username=%s&amp;password=%s' % (TRIM_API_URL, url_to_trim, USERNAME, PASSWORD)) url = response.read().strip() </code></pre> <p>...then not only is url valid but it's recorded in my tr.im account. (Though response.code is still 200.)</p> <p>There must be something wrong with my code though (and not tr.im's API), because</p> <pre><code>$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk </code></pre> <p>...returns:</p> <pre><code>{"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"200","message":"tr.im URL Added."},"date_time":"2009-03-11T10:15:35-04:00"} </code></pre> <p>...and the URL does appear in my list of URLs on <a href="http://ttp://tr.im/?page=1">http://tr.im/?page=1</a>.</p> <p>And if I run:</p> <pre><code>$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk </code></pre> <p>...again, I get:</p> <pre><code>{"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"201","message":"tr.im URL Already Created [yacitus]."},"date_time":"2009-03-11T10:15:35-04:00"} </code></pre> <p>Note code is 201, and message is "tr.im URL Already Created [yacitus]."</p> <p>I must not be doing the basic HTTP authentication correctly (in either attempt). Can you spot my problem? Perhaps I should look and see what's being sent over the wire? I've never done that before. Are there Python APIs I can use (perhaps in pdb)? Or is there another tool (preferably for Mac OS X) I can use?</p>
62
2009-03-11T15:43:10Z
9,698,319
<p>Take a look at <a href="http://stackoverflow.com/a/7755057/1020470">this SO post answer</a> and also look at this <a href="http://www.voidspace.org.uk/python/articles/authentication.shtml">basic authentication tutorial</a> from the <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml">urllib2 missing manual</a>.</p> <p>In order for urllib2 basic authentication to work, the http response must contain HTTP code 401 Unauthorized <strong><em>and</em></strong> a key <code>"WWW-Authenticate"</code> with the value <code>"Basic"</code> otherwise, Python won't send your login info, and you will need to either use <a href="http://docs.python-requests.org/en/v0.10.7/index.html">Requests</a>, or <code>urllib.urlopen(url)</code> with your login in the url, or add a the header like in <a href="http://stackoverflow.com/users/352452/flowpoke">@Flowpoke's</a> <a href="http://stackoverflow.com/a/4188709/1020470">answer</a>.</p> <p>You can view your error by putting your <code>urlopen</code> in a try block:</p> <pre><code>try: urllib2.urlopen(urllib2.Request(url)) except urllib2.HTTPError, e: print e.headers print e.headers.has_key('WWW-Authenticate') </code></pre>
11
2012-03-14T08:35:25Z
[ "python", "http", "authentication" ]
Python urllib2, basic HTTP authentication, and tr.im
635,113
<p>I'm playing around, trying to write some code to use the <a href="http://www.programmableweb.com/api/tr.im">tr.im</a> APIs to shorten a URL.</p> <p>After reading <a href="http://docs.python.org/library/urllib2.html">http://docs.python.org/library/urllib2.html</a>, I tried:</p> <pre><code> TRIM_API_URL = 'http://api.tr.im/api' auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm='tr.im', uri=TRIM_API_URL, user=USERNAME, passwd=PASSWORD) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() </code></pre> <p>response.code is 200 (I think it should be 202). url is valid, but the basic HTTP authentication doesn't seem to have worked, because the shortened URL isn't in my list of URLs (at <a href="http://ttp://tr.im/?page=1">http://tr.im/?page=1</a>).</p> <p>After reading <a href="http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly">http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly</a> I also tried:</p> <pre><code> TRIM_API_URL = 'api.tr.im/api' password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, TRIM_API_URL, USERNAME, PASSWORD) auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('http://%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() </code></pre> <p>But I get the same results. (response.code is 200 and url is valid, but not recorded in my account at <a href="http://tr.im/">http://tr.im/</a>.)</p> <p>If I use query string parameters instead of basic HTTP authentication, like this:</p> <pre><code> TRIM_API_URL = 'http://api.tr.im/api' response = urllib2.urlopen('%s/trim_simple?url=%s&amp;username=%s&amp;password=%s' % (TRIM_API_URL, url_to_trim, USERNAME, PASSWORD)) url = response.read().strip() </code></pre> <p>...then not only is url valid but it's recorded in my tr.im account. (Though response.code is still 200.)</p> <p>There must be something wrong with my code though (and not tr.im's API), because</p> <pre><code>$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk </code></pre> <p>...returns:</p> <pre><code>{"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"200","message":"tr.im URL Added."},"date_time":"2009-03-11T10:15:35-04:00"} </code></pre> <p>...and the URL does appear in my list of URLs on <a href="http://ttp://tr.im/?page=1">http://tr.im/?page=1</a>.</p> <p>And if I run:</p> <pre><code>$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk </code></pre> <p>...again, I get:</p> <pre><code>{"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"201","message":"tr.im URL Already Created [yacitus]."},"date_time":"2009-03-11T10:15:35-04:00"} </code></pre> <p>Note code is 201, and message is "tr.im URL Already Created [yacitus]."</p> <p>I must not be doing the basic HTTP authentication correctly (in either attempt). Can you spot my problem? Perhaps I should look and see what's being sent over the wire? I've never done that before. Are there Python APIs I can use (perhaps in pdb)? Or is there another tool (preferably for Mac OS X) I can use?</p>
62
2009-03-11T15:43:10Z
13,328,157
<p>Try <a href="http://docs.python-requests.org/en/latest/" rel="nofollow">python-request</a> or <a href="https://bitbucket.org/lorien/grab" rel="nofollow">python-grab</a></p>
1
2012-11-11T02:44:58Z
[ "python", "http", "authentication" ]
Python urllib2, basic HTTP authentication, and tr.im
635,113
<p>I'm playing around, trying to write some code to use the <a href="http://www.programmableweb.com/api/tr.im">tr.im</a> APIs to shorten a URL.</p> <p>After reading <a href="http://docs.python.org/library/urllib2.html">http://docs.python.org/library/urllib2.html</a>, I tried:</p> <pre><code> TRIM_API_URL = 'http://api.tr.im/api' auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm='tr.im', uri=TRIM_API_URL, user=USERNAME, passwd=PASSWORD) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() </code></pre> <p>response.code is 200 (I think it should be 202). url is valid, but the basic HTTP authentication doesn't seem to have worked, because the shortened URL isn't in my list of URLs (at <a href="http://ttp://tr.im/?page=1">http://tr.im/?page=1</a>).</p> <p>After reading <a href="http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly">http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly</a> I also tried:</p> <pre><code> TRIM_API_URL = 'api.tr.im/api' password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, TRIM_API_URL, USERNAME, PASSWORD) auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('http://%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() </code></pre> <p>But I get the same results. (response.code is 200 and url is valid, but not recorded in my account at <a href="http://tr.im/">http://tr.im/</a>.)</p> <p>If I use query string parameters instead of basic HTTP authentication, like this:</p> <pre><code> TRIM_API_URL = 'http://api.tr.im/api' response = urllib2.urlopen('%s/trim_simple?url=%s&amp;username=%s&amp;password=%s' % (TRIM_API_URL, url_to_trim, USERNAME, PASSWORD)) url = response.read().strip() </code></pre> <p>...then not only is url valid but it's recorded in my tr.im account. (Though response.code is still 200.)</p> <p>There must be something wrong with my code though (and not tr.im's API), because</p> <pre><code>$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk </code></pre> <p>...returns:</p> <pre><code>{"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"200","message":"tr.im URL Added."},"date_time":"2009-03-11T10:15:35-04:00"} </code></pre> <p>...and the URL does appear in my list of URLs on <a href="http://ttp://tr.im/?page=1">http://tr.im/?page=1</a>.</p> <p>And if I run:</p> <pre><code>$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk </code></pre> <p>...again, I get:</p> <pre><code>{"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"201","message":"tr.im URL Already Created [yacitus]."},"date_time":"2009-03-11T10:15:35-04:00"} </code></pre> <p>Note code is 201, and message is "tr.im URL Already Created [yacitus]."</p> <p>I must not be doing the basic HTTP authentication correctly (in either attempt). Can you spot my problem? Perhaps I should look and see what's being sent over the wire? I've never done that before. Are there Python APIs I can use (perhaps in pdb)? Or is there another tool (preferably for Mac OS X) I can use?</p>
62
2009-03-11T15:43:10Z
24,049,022
<p>Same solutions as <a href="http://stackoverflow.com/questions/2407126/python-urllib2-basic-auth-problem">Python urllib2 Basic Auth Problem</a> apply.</p> <p>see <a href="http://stackoverflow.com/a/24048852/1733117">http://stackoverflow.com/a/24048852/1733117</a>; you can subclass <code>urllib2.HTTPBasicAuthHandler</code> to add the <code>Authorization</code> header to each request that matches the known url.</p> <pre><code>class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler): '''Preemptive basic auth. Instead of waiting for a 403 to then retry with the credentials, send the credentials if the url is handled by the password manager. Note: please use realm=None when calling add_password.''' def http_request(self, req): url = req.get_full_url() realm = None # this is very similar to the code from retry_http_basic_auth() # but returns a request object. user, pw = self.passwd.find_user_password(realm, url) if pw: raw = "%s:%s" % (user, pw) auth = 'Basic %s' % base64.b64encode(raw).strip() req.add_unredirected_header(self.auth_header, auth) return req https_request = http_request </code></pre>
2
2014-06-04T23:02:31Z
[ "python", "http", "authentication" ]
Python urllib2, basic HTTP authentication, and tr.im
635,113
<p>I'm playing around, trying to write some code to use the <a href="http://www.programmableweb.com/api/tr.im">tr.im</a> APIs to shorten a URL.</p> <p>After reading <a href="http://docs.python.org/library/urllib2.html">http://docs.python.org/library/urllib2.html</a>, I tried:</p> <pre><code> TRIM_API_URL = 'http://api.tr.im/api' auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm='tr.im', uri=TRIM_API_URL, user=USERNAME, passwd=PASSWORD) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() </code></pre> <p>response.code is 200 (I think it should be 202). url is valid, but the basic HTTP authentication doesn't seem to have worked, because the shortened URL isn't in my list of URLs (at <a href="http://ttp://tr.im/?page=1">http://tr.im/?page=1</a>).</p> <p>After reading <a href="http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly">http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly</a> I also tried:</p> <pre><code> TRIM_API_URL = 'api.tr.im/api' password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, TRIM_API_URL, USERNAME, PASSWORD) auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('http://%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() </code></pre> <p>But I get the same results. (response.code is 200 and url is valid, but not recorded in my account at <a href="http://tr.im/">http://tr.im/</a>.)</p> <p>If I use query string parameters instead of basic HTTP authentication, like this:</p> <pre><code> TRIM_API_URL = 'http://api.tr.im/api' response = urllib2.urlopen('%s/trim_simple?url=%s&amp;username=%s&amp;password=%s' % (TRIM_API_URL, url_to_trim, USERNAME, PASSWORD)) url = response.read().strip() </code></pre> <p>...then not only is url valid but it's recorded in my tr.im account. (Though response.code is still 200.)</p> <p>There must be something wrong with my code though (and not tr.im's API), because</p> <pre><code>$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk </code></pre> <p>...returns:</p> <pre><code>{"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"200","message":"tr.im URL Added."},"date_time":"2009-03-11T10:15:35-04:00"} </code></pre> <p>...and the URL does appear in my list of URLs on <a href="http://ttp://tr.im/?page=1">http://tr.im/?page=1</a>.</p> <p>And if I run:</p> <pre><code>$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk </code></pre> <p>...again, I get:</p> <pre><code>{"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"201","message":"tr.im URL Already Created [yacitus]."},"date_time":"2009-03-11T10:15:35-04:00"} </code></pre> <p>Note code is 201, and message is "tr.im URL Already Created [yacitus]."</p> <p>I must not be doing the basic HTTP authentication correctly (in either attempt). Can you spot my problem? Perhaps I should look and see what's being sent over the wire? I've never done that before. Are there Python APIs I can use (perhaps in pdb)? Or is there another tool (preferably for Mac OS X) I can use?</p>
62
2009-03-11T15:43:10Z
25,775,523
<p>I would suggest that the current solution is to use my package <a href="https://pypi.python.org/pypi/urllib2_prior_auth/" rel="nofollow">urllib2_prior_auth</a> which solves this pretty nicely (I work on <a href="http://bugs.python.org/issue19494" rel="nofollow">inclusion</a> to the standard lib.</p>
2
2014-09-10T21:38:56Z
[ "python", "http", "authentication" ]
Python urllib2, basic HTTP authentication, and tr.im
635,113
<p>I'm playing around, trying to write some code to use the <a href="http://www.programmableweb.com/api/tr.im">tr.im</a> APIs to shorten a URL.</p> <p>After reading <a href="http://docs.python.org/library/urllib2.html">http://docs.python.org/library/urllib2.html</a>, I tried:</p> <pre><code> TRIM_API_URL = 'http://api.tr.im/api' auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm='tr.im', uri=TRIM_API_URL, user=USERNAME, passwd=PASSWORD) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() </code></pre> <p>response.code is 200 (I think it should be 202). url is valid, but the basic HTTP authentication doesn't seem to have worked, because the shortened URL isn't in my list of URLs (at <a href="http://ttp://tr.im/?page=1">http://tr.im/?page=1</a>).</p> <p>After reading <a href="http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly">http://www.voidspace.org.uk/python/articles/authentication.shtml#doing-it-properly</a> I also tried:</p> <pre><code> TRIM_API_URL = 'api.tr.im/api' password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, TRIM_API_URL, USERNAME, PASSWORD) auth_handler = urllib2.HTTPBasicAuthHandler(password_mgr) opener = urllib2.build_opener(auth_handler) urllib2.install_opener(opener) response = urllib2.urlopen('http://%s/trim_simple?url=%s' % (TRIM_API_URL, url_to_trim)) url = response.read().strip() </code></pre> <p>But I get the same results. (response.code is 200 and url is valid, but not recorded in my account at <a href="http://tr.im/">http://tr.im/</a>.)</p> <p>If I use query string parameters instead of basic HTTP authentication, like this:</p> <pre><code> TRIM_API_URL = 'http://api.tr.im/api' response = urllib2.urlopen('%s/trim_simple?url=%s&amp;username=%s&amp;password=%s' % (TRIM_API_URL, url_to_trim, USERNAME, PASSWORD)) url = response.read().strip() </code></pre> <p>...then not only is url valid but it's recorded in my tr.im account. (Though response.code is still 200.)</p> <p>There must be something wrong with my code though (and not tr.im's API), because</p> <pre><code>$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk </code></pre> <p>...returns:</p> <pre><code>{"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"200","message":"tr.im URL Added."},"date_time":"2009-03-11T10:15:35-04:00"} </code></pre> <p>...and the URL does appear in my list of URLs on <a href="http://ttp://tr.im/?page=1">http://tr.im/?page=1</a>.</p> <p>And if I run:</p> <pre><code>$ curl -u yacitus:xxxx http://api.tr.im/api/trim_url.json?url=http://www.google.co.uk </code></pre> <p>...again, I get:</p> <pre><code>{"trimpath":"hfhb","reference":"nH45bftZDWOX0QpVojeDbOvPDnaRaJ","trimmed":"11\/03\/2009","destination":"http:\/\/www.google.co.uk\/","trim_path":"hfhb","domain":"google.co.uk","url":"http:\/\/tr.im\/hfhb","visits":0,"status":{"result":"OK","code":"201","message":"tr.im URL Already Created [yacitus]."},"date_time":"2009-03-11T10:15:35-04:00"} </code></pre> <p>Note code is 201, and message is "tr.im URL Already Created [yacitus]."</p> <p>I must not be doing the basic HTTP authentication correctly (in either attempt). Can you spot my problem? Perhaps I should look and see what's being sent over the wire? I've never done that before. Are there Python APIs I can use (perhaps in pdb)? Or is there another tool (preferably for Mac OS X) I can use?</p>
62
2009-03-11T15:43:10Z
33,509,568
<p><a href="https://docs.python.org/3/library/urllib.request.html#module-urllib.request" rel="nofollow">The recommended way</a> is to use <a href="http://docs.python-requests.org/en/latest/" rel="nofollow"><code>requests</code> module</a>: </p> <pre><code>#!/usr/bin/env python import requests # $ python -m pip install requests ####from pip._vendor import requests # bundled with python url = 'https://httpbin.org/hidden-basic-auth/user/passwd' user, password = 'user', 'passwd' r = requests.get(url, auth=(user, password)) # send auth unconditionally r.raise_for_status() # raise an exception if the authentication fails </code></pre> <p>Here's a single source Python 2/3 compatible <code>urllib2</code>-based variant:</p> <pre><code>#!/usr/bin/env python import base64 try: from urllib.request import Request, urlopen except ImportError: # Python 2 from urllib2 import Request, urlopen credentials = '{user}:{password}'.format(**vars()).encode() urlopen(Request(url, headers={'Authorization': # send auth unconditionally b'Basic ' + base64.b64encode(credentials)})).close() </code></pre> <p><a href="https://docs.python.org/3.5/whatsnew/3.5.html#urllib" rel="nofollow">Python 3.5+ introduces <code>HTTPPasswordMgrWithPriorAuth()</code></a> that allows:</p> <blockquote> <p>..to eliminate unnecessary 401 response handling, or to unconditionally send credentials on the first request in order to communicate with servers that return a 404 response instead of a 401 if the Authorization header is not sent..</p> </blockquote> <pre><code>#!/usr/bin/env python3 import urllib.request as urllib2 password_manager = urllib2.HTTPPasswordMgrWithPriorAuth() password_manager.add_password(None, url, user, password, is_authenticated=True) # to handle 404 variant auth_manager = urllib2.HTTPBasicAuthHandler(password_manager) opener = urllib2.build_opener(auth_manager) opener.open(url).close() </code></pre> <p>It is easy to replace <code>HTTPBasicAuthHandler()</code> with <code>ProxyBasicAuthHandler()</code> if necessary in this case.</p>
4
2015-11-03T21:39:08Z
[ "python", "http", "authentication" ]
Web frameworks performance comparison
635,159
<p>I'm looking for real life benchmarks comparing web frameworks based on dynamic languages (Python, Ruby, Groovy and Lua). Even better if they're compared up against classic solutions based on PHP, Java, ASP.NET maybe even Perl. I'm particularly interested in:</p> <ul> <li>Django</li> <li>Ruby on Rails</li> <li>Grails</li> <li>Zend Framework</li> <li>Struts2</li> </ul> <p>EDIT: As for Sean's answer:</p> <ol> <li>It's more hypothetical question, in real life I've gotta choose based on more constrains then just raw speed.</li> <li>Speed is not the only, and not even the most important parameter to take in account. It's actually more interesting how these frameworks <strong>scale</strong>.</li> <li>Using standard, well know framework have advantages, that in most cases <em>(unless you're doing something like EVE on-line)</em> out-weight raw speed improvement. </li> </ol> <p>Let me quote book <a href="http://www.manning.com/dbrown/" rel="nofollow">"Struts2 in Action"</a> by D. Brown, C.M. Davis and S. Stanlick:</p> <p><em>"If you want, you could roll your own framework. This is actually not a bad plan. It assumes a couple of things though. First, you have lots of really smart developers. Two, they have the time and money to spend on a big project that might seem off topic from the perspective of the business requirements. Even if you have the rare trinity of really smart people, time and money, there are still some drawbacks. I've done work for a company whose product is built on an in-house framework. The framework is not bad. But a couple of glaring points can't be overlooked. First, new developers will always have to learn the framework from the ground up. If you are using a mainstream framework, there’s a trained work force waiting for you to hire them. Second, the in-house framework is unlikely to see elegant revisions that keep up with the pace of industry. In fact, in-house frameworks seem to be suspect to architectural erosion as the years pass and too many extensions are less elegantly tacked on than one would hope."</em></p> <p>I couldn't agree more.</p>
0
2009-03-11T15:52:26Z
636,427
<p>If your project has a serious, identifiable, need for speed, to the point where your framework is a consideration, taking a general-purpose framework is a bad idea to begin with. They're all going to be too slow, by virtue of being high-level, general purpose &amp; extensible.</p> <p>If your project does not have a hard requirement for an ultra-efficient framework, then you probably wasted more time typing in the question than you'd actually save by going with the 'fastest' framework.</p>
15
2009-03-11T21:19:36Z
[ "java", "php", "python", "performance" ]
Web frameworks performance comparison
635,159
<p>I'm looking for real life benchmarks comparing web frameworks based on dynamic languages (Python, Ruby, Groovy and Lua). Even better if they're compared up against classic solutions based on PHP, Java, ASP.NET maybe even Perl. I'm particularly interested in:</p> <ul> <li>Django</li> <li>Ruby on Rails</li> <li>Grails</li> <li>Zend Framework</li> <li>Struts2</li> </ul> <p>EDIT: As for Sean's answer:</p> <ol> <li>It's more hypothetical question, in real life I've gotta choose based on more constrains then just raw speed.</li> <li>Speed is not the only, and not even the most important parameter to take in account. It's actually more interesting how these frameworks <strong>scale</strong>.</li> <li>Using standard, well know framework have advantages, that in most cases <em>(unless you're doing something like EVE on-line)</em> out-weight raw speed improvement. </li> </ol> <p>Let me quote book <a href="http://www.manning.com/dbrown/" rel="nofollow">"Struts2 in Action"</a> by D. Brown, C.M. Davis and S. Stanlick:</p> <p><em>"If you want, you could roll your own framework. This is actually not a bad plan. It assumes a couple of things though. First, you have lots of really smart developers. Two, they have the time and money to spend on a big project that might seem off topic from the perspective of the business requirements. Even if you have the rare trinity of really smart people, time and money, there are still some drawbacks. I've done work for a company whose product is built on an in-house framework. The framework is not bad. But a couple of glaring points can't be overlooked. First, new developers will always have to learn the framework from the ground up. If you are using a mainstream framework, there’s a trained work force waiting for you to hire them. Second, the in-house framework is unlikely to see elegant revisions that keep up with the pace of industry. In fact, in-house frameworks seem to be suspect to architectural erosion as the years pass and too many extensions are less elegantly tacked on than one would hope."</em></p> <p>I couldn't agree more.</p>
0
2009-03-11T15:52:26Z
16,544,086
<p><strong>Techempower benchmark:</strong> </p> <p><a href="http://www.techempower.com/benchmarks" rel="nofollow">http://www.techempower.com/benchmarks</a></p> <p>They are comparing a lot of frameworks and accept new frameworks for comparison. Interface very intuitive. In my view, it is the best benchmark now. </p> <p><strong>World wide wait - 1 hour speech</strong></p> <p><a href="http://www.parleys.com/#id=2942&amp;st=5" rel="nofollow">http://www.parleys.com/#id=2942&amp;st=5</a></p> <p>Django is not here, it's only benchmark of JVM frameworks. But still, it is quite scientific, worth it. </p>
2
2013-05-14T13:09:00Z
[ "java", "php", "python", "performance" ]
Visual Studio 2005 Build of Python with Debug .lib
635,200
<p>I am looking for the Visual Studio 2005 build of Python 2.4, 2.5 or 2.6, I also need the python2x_d.lib (the debug version of the .lib) since I embed the interpreter into my app and the python libs implicitly link to the python2x_d.lib with pragmas (grrr).</p> <p>Any hints where I can find those builds ?</p> <p>Regards,</p> <p>Paul</p>
0
2009-03-11T16:00:22Z
635,239
<p>I would recommend that you <a href="http://python.org/download/" rel="nofollow">download the Python source</a> (tgz and tar.bz2 zipped versions available) and compile it yourself. It comes with a VS2005 solution so it isn't difficult. I had to do this for a SWIG project I was working on.</p>
1
2009-03-11T16:10:09Z
[ "python", "visual-studio-2005" ]
Visual Studio 2005 Build of Python with Debug .lib
635,200
<p>I am looking for the Visual Studio 2005 build of Python 2.4, 2.5 or 2.6, I also need the python2x_d.lib (the debug version of the .lib) since I embed the interpreter into my app and the python libs implicitly link to the python2x_d.lib with pragmas (grrr).</p> <p>Any hints where I can find those builds ?</p> <p>Regards,</p> <p>Paul</p>
0
2009-03-11T16:00:22Z
635,245
<p>If you have trouble finding the debug builds, you can try and build your own. Browse the <a href="http://svn.python.org/view/python/trunk/PCbuild/" rel="nofollow">build directory</a>, for project files like <code>python.vcproj</code> - to locate versions that will work with Visual Studio 2005.</p>
0
2009-03-11T16:13:56Z
[ "python", "visual-studio-2005" ]
Visual Studio 2005 Build of Python with Debug .lib
635,200
<p>I am looking for the Visual Studio 2005 build of Python 2.4, 2.5 or 2.6, I also need the python2x_d.lib (the debug version of the .lib) since I embed the interpreter into my app and the python libs implicitly link to the python2x_d.lib with pragmas (grrr).</p> <p>Any hints where I can find those builds ?</p> <p>Regards,</p> <p>Paul</p>
0
2009-03-11T16:00:22Z
635,266
<p>I recall, some time ago, giving IronPython a 'whirl' in VS2005. I ran into all kinds of 'esoteric' errors until I figured out that to compile and run I had to add the C++ libraries and tools of VS2005 as well (add/remove). Maybe this is something similar ?</p>
0
2009-03-11T16:18:53Z
[ "python", "visual-studio-2005" ]
code documentation for python
635,419
<p>What is out there on conventions and tools for documenting python source code?</p>
16
2009-03-11T16:54:41Z
635,428
<p>Conventions: <a href="http://www.python.org/dev/peps/pep-0257/">PEP 257</a> and <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a>. Note, that docstrings can be written in <a href="http://docutils.sourceforge.net/rst.html">reStructuredText</a></p> <p>Tools for generating documentation: for example <a href="http://sphinx.pocoo.org/">Sphinx</a> </p>
33
2009-03-11T16:56:58Z
[ "python", "documentation", "documentation-generation" ]
code documentation for python
635,419
<p>What is out there on conventions and tools for documenting python source code?</p>
16
2009-03-11T16:54:41Z
635,445
<p>It's very nice to put code documentation in the code itself. See:</p> <ul> <li><a href="http://www.python.org/dev/peps/pep-0257/">PEP 257 -- Docstring Conventions </a></li> <li><a href="http://www.python.org/dev/peps/pep-0008/">PEP 8 -- Style Guide for Python Code</a></li> </ul>
6
2009-03-11T17:00:23Z
[ "python", "documentation", "documentation-generation" ]
code documentation for python
635,419
<p>What is out there on conventions and tools for documenting python source code?</p>
16
2009-03-11T16:54:41Z
635,473
<p><a href="http://epydoc.sourceforge.net/">Epydoc</a> is also a good tool for documenting source code, and handles cross-referencing classes, modules, variables, etc, into HTML, PDF, LaTeX. Draws some nice class inheritance diagrams too. It's used by a number of open-source projects, so it's fairly actively developed.</p>
8
2009-03-11T17:06:07Z
[ "python", "documentation", "documentation-generation" ]
code documentation for python
635,419
<p>What is out there on conventions and tools for documenting python source code?</p>
16
2009-03-11T16:54:41Z
635,482
<p>First, put comments in your docstrings using RestructuredText format.</p> <p>Second, get <a href="http://sphinx.pocoo.org/">sphinx</a>.</p> <p>Third, create an index that uses the <a href="http://sphinx.pocoo.org/ext/autodoc.html">autodoc extension</a>.</p> <p>Then, run Sphinx to get really nice documentation.</p>
14
2009-03-11T17:08:39Z
[ "python", "documentation", "documentation-generation" ]
code documentation for python
635,419
<p>What is out there on conventions and tools for documenting python source code?</p>
16
2009-03-11T16:54:41Z
22,247,361
<p>using doxypy filter with doxygen is a good thing also</p>
1
2014-03-07T10:20:16Z
[ "python", "documentation", "documentation-generation" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
635,498
<p>I find <code>setdefault</code> quite useful; It checks if a key is present and adds it if not:</p> <pre><code>d = {} d.setdefault('new jersey', {}).setdefault('mercer county', {})['plumbers'] = 3 </code></pre> <p><code>setdefault</code> always returns the relevant key, so you are actually updating the values of '<code>d</code>' in place.</p> <p>When it comes to iterating, I'm sure you could write a generator easily enough if one doesn't already exist in Python:</p> <pre><code>def iterateStates(d): # Let's count up the total number of "plumbers" / "dentists" / etc. # across all counties and states job_totals = {} # I guess this is the annoying nested stuff you were talking about? for (state, counties) in d.iteritems(): for (county, jobs) in counties.iteritems(): for (job, num) in jobs.iteritems(): # If job isn't already in job_totals, default it to zero job_totals[job] = job_totals.get(job, 0) + num # Now return an iterator of (job, number) tuples return job_totals.iteritems() # Display all jobs for (job, num) in iterateStates(d): print "There are %d %s in total" % (job, num) </code></pre>
7
2009-03-11T17:14:19Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
635,512
<p>As for "obnoxious try/catch blocks":</p> <pre><code>d = {} d.setdefault('key',{}).setdefault('inner key',{})['inner inner key'] = 'value' print d </code></pre> <p>yields</p> <pre><code>{'key': {'inner key': {'inner inner key': 'value'}}} </code></pre> <p>You can use this to convert from your flat dictionary format to structured format:</p> <pre><code>fd = {('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} for (k1,k2,k3), v in fd.iteritems(): d.setdefault(k1, {}).setdefault(k2, {})[k3] = v </code></pre>
4
2009-03-11T17:17:40Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
635,522
<p>I like the idea of wrapping this in a class and implementing <code>__getitem__</code> and <code>__setitem__</code> such that they implemented a simple query language:</p> <pre><code>&gt;&gt;&gt; d['new jersey/mercer county/plumbers'] = 3 &gt;&gt;&gt; d['new jersey/mercer county/programmers'] = 81 &gt;&gt;&gt; d['new jersey/mercer county/programmers'] 81 &gt;&gt;&gt; d['new jersey/mercer country'] &lt;view which implicitly adds 'new jersey/mercer county' to queries/mutations&gt; </code></pre> <p>If you wanted to get fancy you could also implement something like:</p> <pre><code>&gt;&gt;&gt; d['*/*/programmers'] &lt;view which would contain 'programmers' entries&gt; </code></pre> <p>but mostly I think such a thing would be really fun to implement :D </p>
1
2009-03-11T17:19:27Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
635,557
<p>Since you have a star-schema design, you might want to structure it more like a relational table and less like a dictionary.</p> <pre><code>import collections class Jobs( object ): def __init__( self, state, county, title, count ): self.state= state self.count= county self.title= title self.count= count facts = [ Jobs( 'new jersey', 'mercer county', 'plumbers', 3 ), ... def groupBy( facts, name ): total= collections.defaultdict( int ) for f in facts: key= getattr( f, name ) total[key] += f.count </code></pre> <p>That kind of thing can go a long way to creating a data warehouse-like design without the SQL overheads.</p>
17
2009-03-11T17:29:12Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
635,857
<pre><code>class JobDb(object): def __init__(self): self.data = [] self.all = set() self.free = [] self.index1 = {} self.index2 = {} self.index3 = {} def _indices(self,(key1,key2,key3)): indices = self.all.copy() wild = False for index,key in ((self.index1,key1),(self.index2,key2), (self.index3,key3)): if key is not None: indices &amp;= index.setdefault(key,set()) else: wild = True return indices, wild def __getitem__(self,key): indices, wild = self._indices(key) if wild: return dict(self.data[i] for i in indices) else: values = [self.data[i][-1] for i in indices] if values: return values[0] def __setitem__(self,key,value): indices, wild = self._indices(key) if indices: for i in indices: self.data[i] = key,value elif wild: raise KeyError(k) else: if self.free: index = self.free.pop(0) self.data[index] = key,value else: index = len(self.data) self.data.append((key,value)) self.all.add(index) self.index1.setdefault(key[0],set()).add(index) self.index2.setdefault(key[1],set()).add(index) self.index3.setdefault(key[2],set()).add(index) def __delitem__(self,key): indices,wild = self._indices(key) if not indices: raise KeyError self.index1[key[0]] -= indices self.index2[key[1]] -= indices self.index3[key[2]] -= indices self.all -= indices for i in indices: self.data[i] = None self.free.extend(indices) def __len__(self): return len(self.all) def __iter__(self): for key,value in self.data: yield key </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; db = JobDb() &gt;&gt;&gt; db['new jersey', 'mercer county', 'plumbers'] = 3 &gt;&gt;&gt; db['new jersey', 'mercer county', 'programmers'] = 81 &gt;&gt;&gt; db['new jersey', 'middlesex county', 'programmers'] = 81 &gt;&gt;&gt; db['new jersey', 'middlesex county', 'salesmen'] = 62 &gt;&gt;&gt; db['new york', 'queens county', 'plumbers'] = 9 &gt;&gt;&gt; db['new york', 'queens county', 'salesmen'] = 36 &gt;&gt;&gt; db['new york', None, None] {('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} &gt;&gt;&gt; db[None, None, 'plumbers'] {('new jersey', 'mercer county', 'plumbers'): 3, ('new york', 'queens county', 'plumbers'): 9} &gt;&gt;&gt; db['new jersey', 'mercer county', None] {('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81} &gt;&gt;&gt; db['new jersey', 'middlesex county', 'programmers'] 81 &gt;&gt;&gt; </code></pre> <p><strong>Edit:</strong> Now returning dictionaries when querying with wild cards (<code>None</code>), and single values otherwise.</p>
1
2009-03-11T18:52:03Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
636,109
<p>If the number of nesting levels is small, I use <code>collections.defaultdict</code> for this:</p> <pre><code>from collections import defaultdict def nested_dict_factory(): return defaultdict(int) def nested_dict_factory2(): return defaultdict(nested_dict_factory) db = defaultdict(nested_dict_factory2) db['new jersey']['mercer county']['plumbers'] = 3 db['new jersey']['mercer county']['programmers'] = 81 </code></pre> <p>Using <code>defaultdict</code> like this avoids a lot of messy <code>setdefault()</code>, <code>get()</code>, etc.</p>
12
2009-03-11T20:02:11Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
636,125
<p>For easy iterating over your nested dictionary, why not just write a simple generator?</p> <pre><code>def each_job(my_dict): for state, a in my_dict.items(): for county, b in a.items(): for job, value in b.items(): yield { 'state' : state, 'county' : county, 'job' : job, 'value' : value } </code></pre> <p>So then, if you have your compilicated nested dictionary, iterating over it becomes simple:</p> <pre><code>for r in each_job(my_dict): print "There are %d %s in %s, %s" % (r['value'], r['job'], r['county'], r['state']) </code></pre> <p>Obviously your generator can yield whatever format of data is useful to you.</p> <p>Why are you using try catch blocks to read the tree? It's easy enough (and probably safer) to query whether a key exists in a dict before trying to retrieve it. A function using guard clauses might look like this:</p> <pre><code>if not my_dict.has_key('new jersey'): return False nj_dict = my_dict['new jersey'] ... </code></pre> <p>Or, a perhaps somewhat verbose method, is to use the get method:</p> <pre><code>value = my_dict.get('new jersey', {}).get('middlesex county', {}).get('salesmen', 0) </code></pre> <p>But for a somewhat more succinct way, you might want to look at using a <a href="http://docs.python.org/library/collections.html#collections.defaultdict" rel="nofollow">collections.defaultdict</a>, which is part of the standard library since python 2.5.</p> <pre><code>import collections def state_struct(): return collections.defaultdict(county_struct) def county_struct(): return collections.defaultdict(job_struct) def job_struct(): return 0 my_dict = collections.defaultdict(state_struct) print my_dict['new jersey']['middlesex county']['salesmen'] </code></pre> <p>I'm making assumptions about the meaning of your data structure here, but it should be easy to adjust for what you actually want to do.</p>
3
2009-03-11T20:05:32Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
636,138
<p>You could create a YAML file and read it in using <a href="http://pyyaml.org/">PyYaml</a>.</p> <p>Step 1: Create a YAML file, "employment.yml":</p> <pre><code>new jersey: mercer county: pumbers: 3 programmers: 81 middlesex county: salesmen: 62 programmers: 81 new york: queens county: plumbers: 9 salesmen: 36 </code></pre> <p>Step 2: Read it in Python</p> <pre><code>import yaml file_handle = open("employment.yml") my_shnazzy_dictionary = yaml.safe_load(file_handle) file_handle.close() </code></pre> <p>and now <code>my_shnazzy_dictionary</code> has all your values. If you needed to do this on the fly, you can create the YAML as a string and feed that into <code>yaml.safe_load(...)</code>.</p>
21
2009-03-11T20:08:17Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
636,234
<p>Unless your dataset is going to stay pretty small, you might want to consider using a relational database. It will do exactly what you want: make it easy to add counts, selecting subsets of counts, and even aggregate counts by state, county, occupation, or any combination of these.</p>
1
2009-03-11T20:30:20Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
637,569
<p><code>collections.defaultdict</code> can be sub-classed to make a nested dict. Then add any useful iteration methods to that class.</p> <pre><code>&gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; class nesteddict(defaultdict): def __init__(self): defaultdict.__init__(self, nesteddict) def walk(self): for key, value in self.iteritems(): if isinstance(value, nesteddict): for tup in value.walk(): yield (key,) + tup else: yield key, value &gt;&gt;&gt; nd = nesteddict() &gt;&gt;&gt; nd['new jersey']['mercer county']['plumbers'] = 3 &gt;&gt;&gt; nd['new jersey']['mercer county']['programmers'] = 81 &gt;&gt;&gt; nd['new jersey']['middlesex county']['programmers'] = 81 &gt;&gt;&gt; nd['new jersey']['middlesex county']['salesmen'] = 62 &gt;&gt;&gt; nd['new york']['queens county']['plumbers'] = 9 &gt;&gt;&gt; nd['new york']['queens county']['salesmen'] = 36 &gt;&gt;&gt; for tup in nd.walk(): print tup ('new jersey', 'mercer county', 'programmers', 81) ('new jersey', 'mercer county', 'plumbers', 3) ('new jersey', 'middlesex county', 'programmers', 81) ('new jersey', 'middlesex county', 'salesmen', 62) ('new york', 'queens county', 'salesmen', 36) ('new york', 'queens county', 'plumbers', 9) </code></pre>
5
2009-03-12T06:27:52Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
644,500
<p>As others have suggested, a relational database could be more useful to you. You can use a in-memory sqlite3 database as a data structure to create tables and then query them.</p> <pre><code>import sqlite3 c = sqlite3.Connection(':memory:') c.execute('CREATE TABLE jobs (state, county, title, count)') c.executemany('insert into jobs values (?, ?, ?, ?)', [ ('New Jersey', 'Mercer County', 'Programmers', 81), ('New Jersey', 'Mercer County', 'Plumbers', 3), ('New Jersey', 'Middlesex County', 'Programmers', 81), ('New Jersey', 'Middlesex County', 'Salesmen', 62), ('New York', 'Queens County', 'Salesmen', 36), ('New York', 'Queens County', 'Plumbers', 9), ]) # some example queries print list(c.execute('SELECT * FROM jobs WHERE county = "Queens County"')) print list(c.execute('SELECT SUM(count) FROM jobs WHERE title = "Programmers"')) </code></pre> <p>This is just a simple example. You could define separate tables for states, counties and job titles.</p>
6
2009-03-13T20:24:47Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
652,284
<pre><code>class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value </code></pre> <p>Testing:</p> <pre><code>a = AutoVivification() a[1][2][3] = 4 a[1][3][3] = 5 a[1][2]['test'] = 6 print a </code></pre> <p>Output:</p> <pre><code>{1: {2: {'test': 6, 3: 4}, 3: {3: 5}}} </code></pre>
178
2009-03-16T21:53:36Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
5,222,457
<p><code>defaultdict()</code> is your friend!</p> <p>I didn't come up with this (see "<a href="http://slacy.com/blog/2010/05/python-multi-dimensional-dicts-using-defaultdict/">Python Multi-dimensional dicts using defaultdict</a>") but for a two dimensional dictionary you can do:</p> <pre><code>d = defaultdict(defaultdict) d[1][2] = 3 </code></pre> <p>For more dimensions you can: </p> <pre><code>d = defaultdict(lambda :defaultdict(defaultdict)) d[1][2][3] = 4 </code></pre>
6
2011-03-07T16:48:34Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
7,476,491
<p>Just because I haven't seen one this small, here's a dict that gets as nested as you like, no sweat:</p> <pre><code># yo dawg, i heard you liked dicts def yodict(): return defaultdict(yodict) </code></pre>
25
2011-09-19T19:51:07Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
12,980,572
<p>I have a similar thing going. I have a lot of cases where I do:</p> <pre><code>thedict = {} for item in ('foo', 'bar', 'baz'): mydict = thedict.get(item, {}) mydict = get_value_for(item) thedict[item] = mydict </code></pre> <p>But going many levels deep. It's the ".get(item, {})" that's the key as it'll make another dictionary if there isn't one already. Meanwhile, I've been thinking of ways to deal with this better. Right now, there's a lot of</p> <pre><code>value = mydict.get('foo', {}).get('bar', {}).get('baz', 0) </code></pre> <p>So instead, I made:</p> <pre><code>def dictgetter(thedict, default, *args): totalargs = len(args) for i,arg in enumerate(args): if i+1 == totalargs: thedict = thedict.get(arg, default) else: thedict = thedict.get(arg, {}) return thedict </code></pre> <p>Which has the same effect if you do:</p> <pre><code>value = dictgetter(mydict, 0, 'foo', 'bar', 'baz') </code></pre> <p>Better? I think so.</p>
0
2012-10-19T18:47:35Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
19,829,714
<blockquote> <h1>What is the best way to implement nested dictionaries in Python?</h1> </blockquote> <p>Implement <code>__missing__</code> on a <code>dict</code> subclass to set and return a new instance!</p> <p>Here is a more elegant approach that has been available <a href="http://docs.python.org/2/library/stdtypes.html#dict" rel="nofollow">(and documented)</a> since Python 2.5, and (particularly valuable to me) <strong>it pretty prints just like a normal dict</strong>, instead of the ugly printing of an autovivified defaultdict:</p> <pre><code>class Vividict(dict): def __missing__(self, key): value = self[key] = type(self)() return value </code></pre> <p>This is half the lines of code of what was the accepted answer until September 23, 2016.</p> <h1>Explanation:</h1> <p>We're just providing another nested instance of our class <code>Vividict</code> whenever a key is accessed but missing. (Returning the value assignment is useful because it avoids us additionally calling the getter on the dict, and unfortunately, we can't return it as it is being set.)</p> <p>Note, these are the same semantics as the most upvoted answer but in half the lines of code - nosklo's implementation:</p> <blockquote> <pre><code>class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value </code></pre> </blockquote> <h2>Demonstration of Usage</h2> <p>Below is just an example of how this dict could be easily used to create a nested dict structure on the fly. This can quickly create a hierarchical tree structure as deeply as you might want to go.</p> <pre><code>import pprint class Vividict(dict): def __missing__(self, key): value = self[key] = type(self)() return value d = Vividict() d['foo']['bar'] d['foo']['baz'] d['fizz']['buzz'] d['primary']['secondary']['tertiary']['quaternary'] pprint.pprint(d) </code></pre> <p>Which outputs: </p> <pre><code>{'fizz': {'buzz': {}}, 'foo': {'bar': {}, 'baz': {}}, 'primary': {'secondary': {'tertiary': {'quaternary': {}}}}} </code></pre> <p>And as the last line shows, it pretty prints beautifully and in order for manual inspection. But if you want to visually inspect your data, implementing <code>__missing__</code> to set a new instance of its class to the key and return it is a far better solution.</p> <h1>Other alternatives, for contrast:</h1> <h2><code>dict.setdefault</code></h2> <p>setdefault works great when used in loops and you don't know what you're going to get for keys, but repetitive usage becomes quite burdensome, and I don't think anyone would want to keep up the following:</p> <pre><code>d = dict() d.setdefault('foo', {}).setdefault('bar', {}) d.setdefault('foo', {}).setdefault('baz', {}) d.setdefault('fizz', {}).setdefault('buzz', {}) d.setdefault('primary', {}).setdefault('secondary', {}).setdefault('tertiary', {}).setdefault('quaternary', {}) </code></pre> <h2>An auto-vivified defaultdict</h2> <p>This is a clean looking implementation, and usage in a script that you're not inspecting the data on would be as useful as implementing <code>__missing__</code>:</p> <pre><code>from collections import defaultdict def vivdict(): return defaultdict(vivdict) </code></pre> <p>But if you need to inspect your data, the results of an auto-vivified defaultdict populated with data in the same way looks like this:</p> <pre><code>&gt;&gt;&gt; d = vivdict(); d['foo']['bar']; d['foo']['baz']; d['fizz']['buzz']; d['primary']['secondary']['tertiary']['quaternary']; import pprint; &gt;&gt;&gt; pprint.pprint(d) defaultdict(&lt;function vivdict at 0x17B01870&gt;, {'foo': defaultdict(&lt;function vivdict at 0x17B01870&gt;, {'baz': defaultdict(&lt;function vivdict at 0x17B01870&gt;, {}), 'bar': defaultdict(&lt;function vivdict at 0x17B01870&gt;, {})}), 'primary': defaultdict(&lt;function vivdict at 0x17B01870&gt;, {'secondary': defaultdict(&lt;function vivdict at 0x17B01870&gt;, {'tertiary': defaultdict(&lt;function vivdict at 0x17B01870&gt;, {'quaternary': defaultdict( &lt;function vivdict at 0x17B01870&gt;, {})})})}), 'fizz': defaultdict(&lt;function vivdict at 0x17B01870&gt;, {'buzz': defaultdict(&lt;function vivdict at 0x17B01870&gt;, {})})}) </code></pre> <p>This output is quite inelegant, and the results are quite unreadable. The solution typically given is to recursively convert back to a dict for manual inspection. This non-trivial solution is left as an exercise for the reader.</p> <h1>Performance</h1> <p>Finally, let's look at performance. I'm subtracting the costs of instantiation.</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; min(timeit.repeat(lambda: {}.setdefault('foo', {}))) - min(timeit.repeat(lambda: {})) 0.13612580299377441 &gt;&gt;&gt; min(timeit.repeat(lambda: vivdict()['foo'])) - min(timeit.repeat(lambda: vivdict())) 0.2936999797821045 &gt;&gt;&gt; min(timeit.repeat(lambda: Vividict()['foo'])) - min(timeit.repeat(lambda: Vividict())) 0.5354437828063965 &gt;&gt;&gt; min(timeit.repeat(lambda: AutoVivification()['foo'])) - min(timeit.repeat(lambda: AutoVivification())) 2.138362169265747 </code></pre> <p>Based on performance, <code>dict.setdefault</code> works the best. I'd highly recommend it for production code, in cases where you care about execution speed. </p> <p>If you need this for interactive use (in an IPython notebook, perhaps) then performance doesn't really matter - in which case, I'd go with Vividict for readability of the output. Compared to the AutoVivification object (which uses <code>__getitem__</code> instead of <code>__missing__</code>, which was made for this purpose) it is far superior.</p> <h1>Conclusion</h1> <p>Implementing <code>__missing__</code> on a subclassed <code>dict</code> to set and return a new instance is slightly more difficult than alternatives but has the benefits of</p> <ul> <li>easy instantiation</li> <li>easy data population</li> <li>easy data viewing</li> </ul> <p>and because it is less complicated and more performant than modifying <code>__getitem__</code>, it should be preferred to that method.</p>
88
2013-11-07T06:53:24Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
22,737,965
<p>This is a function that returns a nested dictionary of arbitrary depth:</p> <pre><code>from collections import defaultdict def make_dict(): return defaultdict(make_dict) </code></pre> <p>Use it like this:</p> <pre><code>d=defaultdict(make_dict) d["food"]["meat"]="beef" d["food"]["veggie"]="corn" d["food"]["sweets"]="ice cream" d["animal"]["pet"]["dog"]="collie" d["animal"]["pet"]["cat"]="tabby" d["animal"]["farm animal"]="chicken" </code></pre> <p>Iterate through everything with something like this:</p> <pre><code>def iter_all(d,depth=1): for k,v in d.iteritems(): print "-"*depth,k if type(v) is defaultdict: iter_all(v,depth+1) else: print "-"*(depth+1),v iter_all(d) </code></pre> <p>This prints out:</p> <pre><code>- food -- sweets --- ice cream -- meat --- beef -- veggie --- corn - animal -- pet --- dog ---- labrador --- cat ---- tabby -- farm animal --- chicken </code></pre> <p>You might eventually want to make it so that new items can not be added to the dict. It's easy to recursively convert all these <code>defaultdict</code>s to normal <code>dict</code>s.</p> <pre><code>def dictify(d): for k,v in d.iteritems(): if isinstance(v,defaultdict): d[k] = dictify(v) return dict(d) </code></pre>
8
2014-03-29T22:53:36Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
34,931,958
<p>You can use Addict: <a href="https://github.com/mewwts/addict" rel="nofollow">https://github.com/mewwts/addict</a></p> <pre><code>&gt;&gt;&gt; from addict import Dict &gt;&gt;&gt; my_new_shiny_dict = Dict() &gt;&gt;&gt; my_new_shiny_dict.a.b.c.d.e = 2 &gt;&gt;&gt; my_new_shiny_dict {'a': {'b': {'c': {'d': {'e': 2}}}}} </code></pre>
1
2016-01-21T18:50:09Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
What is the best way to implement nested dictionaries in Python?
635,483
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p> <pre><code>{'new jersey': {'mercer county': {'plumbers': 3, 'programmers': 81}, 'middlesex county': {'programmers': 81, 'salesmen': 62}}, 'new york': {'queens county': {'plumbers': 9, 'salesmen': 36}}} </code></pre> <p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p> <p>I could also use tuples as keys, like such:</p> <pre><code>{('new jersey', 'mercer county', 'plumbers'): 3, ('new jersey', 'mercer county', 'programmers'): 81, ('new jersey', 'middlesex county', 'programmers'): 81, ('new jersey', 'middlesex county', 'salesmen'): 62, ('new york', 'queens county', 'plumbers'): 9, ('new york', 'queens county', 'salesmen'): 36} </code></pre> <p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p> <p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p> <p>How could I do this better?</p> <p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p>
149
2009-03-11T17:09:21Z
36,512,749
<p>You can use recursion in lambdas and defaultdict, no need to define names:</p> <pre><code>a = defaultdict((lambda f: f(f))(lambda g: lambda:defaultdict(g(g)))) </code></pre> <p>Here's an example:</p> <pre><code>&gt;&gt;&gt; a['new jersey']['mercer county']['plumbers']=3 &gt;&gt;&gt; a['new jersey']['middlesex county']['programmers']=81 &gt;&gt;&gt; a['new jersey']['mercer county']['programmers']=81 &gt;&gt;&gt; a['new jersey']['middlesex county']['salesmen']=62 &gt;&gt;&gt; a defaultdict(&lt;function __main__.&lt;lambda&gt;&gt;, {'new jersey': defaultdict(&lt;function __main__.&lt;lambda&gt;&gt;, {'mercer county': defaultdict(&lt;function __main__.&lt;lambda&gt;&gt;, {'plumbers': 3, 'programmers': 81}), 'middlesex county': defaultdict(&lt;function __main__.&lt;lambda&gt;&gt;, {'programmers': 81, 'salesmen': 62})})}) </code></pre>
1
2016-04-09T04:25:21Z
[ "python", "data-structures", "dictionary", "mapping", "autovivification" ]
Django: Open uploaded file while still in memory; In the Form Clean method?
635,524
<p>I need to validate the contents of an uploaded XML file in my Form clean method, but I'm unable to open the file for validation. It seams, in the clean method, the file hasn't yet been moved from memory (or the temporary directory) to the destination directory.</p> <p>For example the following code doesn't work because the file hasn't been moved to that destination yet. It's still in memory (or the temporary directory):</p> <pre><code>xml_file = cleaned_data.get('xml_file') xml_file_absolute = '%(1)s%(2)s' % {'1': settings.MEDIA_ROOT, '2': xml_file} xml_size = str(os.path.getsize(xml_file_absolute)) </code></pre> <p>When I look at the "cleaned_data" variable it shows this: </p> <pre><code>{'xml_file': &lt;InMemoryUploadedFile: texting.nzb (application/octet-stream)&gt;} </code></pre> <p><code>cleaned_data.get('xml_file')</code> only returns "texting.nzb" as a string.</p> <p>Is there another way to access the the file in memory (or the temporary directory)?</p> <p><hr /></p> <p>Again, this is in my Form's <code>clean</code> method that's tied into the default administration view. I've been told time and time again that all validation should be handled in a Form, not the view. Correct?</p>
7
2009-03-11T17:20:30Z
635,559
<p>I'm assuming that you've bound your form to the files using:</p> <pre><code>my_form = MyFormClass(request.POST, request.FILES) </code></pre> <p>If you have, once the form has been validated, you can access the file content itself using the request.FILES dictionary:</p> <pre><code>if my_form.is_valid(): data = request.FILES['myfile'].read() </code></pre> <p>The request.FILES['myfile'] object is an UploadedFile object, so it supports file-like read/write operations.</p> <p>If you need to access the file contents from within the form's <code>clean</code> method (or any method of the cleaning machinery), you are doing it right. <code>cleaned_data.get('xml_file')</code> returns an <a href="http://docs.djangoproject.com/en/dev/topics/http/file-uploads/#uploadedfile-objects">UploadedFile</a> object. The <code>__str__</code> method of that object just prints out the string, which is why you see only the file name. However, you can get access to the entire contents:</p> <pre><code>xml_file = myform.cleaned_data.get('xml_file') print xml_file.read() </code></pre> <p>This section of the docs has some great examples: <a href="http://docs.djangoproject.com/en/dev/topics/http/file-uploads/">http://docs.djangoproject.com/en/dev/topics/http/file-uploads/</a></p>
12
2009-03-11T17:29:45Z
[ "python", "django" ]
Inserting A Heading Into A Django Form
635,583
<p>I would like my form to output something like this:</p> <pre><code>Name: ___________ Company: ___________ Interested in ------------- Foo: [ ] Bar: [ ] Baz: [ ] </code></pre> <p>That is to say, I would like to have the 'Interested In' title inserted in the middle of my form output.</p> <p>One way of doing this would be to write out the template code for each field, and insert the heading as appropriate. However, I'd prefer not to do this. I suspect that there is something to do with formsets that will do what I want.</p> <p><em>Is</em> there a way to do what I want, or do I just need to suck it up and accept that I need to write my template out longhand for this?</p>
2
2009-03-11T17:37:13Z
636,160
<p>With <a href="http://github.com/muhuk/django-formfieldset/tree/master" rel="nofollow"><code>FieldsetMixin</code></a> you get Admin-like fieldsets. You create your form like this:</p> <pre><code>from django.forms import Form from formfieldset.forms import FieldsetMixin class MyForm(Form, FieldsetMixin): fieldsets = ( (u'', {'fields': ['name', 'company']}), (u'Interested in', {'fields': ['foo', 'bar', 'baz']}), ) # rest of the form </code></pre>
3
2009-03-11T20:13:24Z
[ "python", "django", "forms" ]
Inserting A Heading Into A Django Form
635,583
<p>I would like my form to output something like this:</p> <pre><code>Name: ___________ Company: ___________ Interested in ------------- Foo: [ ] Bar: [ ] Baz: [ ] </code></pre> <p>That is to say, I would like to have the 'Interested In' title inserted in the middle of my form output.</p> <p>One way of doing this would be to write out the template code for each field, and insert the heading as appropriate. However, I'd prefer not to do this. I suspect that there is something to do with formsets that will do what I want.</p> <p><em>Is</em> there a way to do what I want, or do I just need to suck it up and accept that I need to write my template out longhand for this?</p>
2
2009-03-11T17:37:13Z
636,164
<p>The form fields retain the order with which you defined the form class or model if it's form for model. In the template you can iterate thru all the fields specifying how they are rendered, you can check for the one you are looking for with the ifequal tag and specify the different rendering.</p> <p>See:</p> <p><a href="http://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs#looping-over-the-form-s-fields" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/forms/?from=olddocs#looping-over-the-form-s-fields</a></p>
0
2009-03-11T20:14:44Z
[ "python", "django", "forms" ]
Inserting A Heading Into A Django Form
635,583
<p>I would like my form to output something like this:</p> <pre><code>Name: ___________ Company: ___________ Interested in ------------- Foo: [ ] Bar: [ ] Baz: [ ] </code></pre> <p>That is to say, I would like to have the 'Interested In' title inserted in the middle of my form output.</p> <p>One way of doing this would be to write out the template code for each field, and insert the heading as appropriate. However, I'd prefer not to do this. I suspect that there is something to do with formsets that will do what I want.</p> <p><em>Is</em> there a way to do what I want, or do I just need to suck it up and accept that I need to write my template out longhand for this?</p>
2
2009-03-11T17:37:13Z
636,200
<p>Django formsets are not the way to go: They are used if you need to edit multiple objects at the same time. HTML fieldsets are more like the correct way. I imagine you could group the name and company fields into one fieldset, and then the interest fields into another.</p> <p>On DjangoSnippets you can find a <a href="http://www.djangosnippets.org/snippets/663/" rel="nofollow">template tag that aids the grouping</a>.</p> <p>Using this snippet, you would define the grouping in your view as</p> <pre><code>fieldsets = ( ('', {'fields': ('name','company')}), ('Interested in', {'fields': ('foo','bar','baz')}) ) </code></pre> <p>Pass it to the template along with the form, and render the form with</p> <pre><code>{% draw_form form fieldsets %} </code></pre> <p>I would prefer not to define the grouping in the view, as it's mainly presentational issue and should belong to the view, but what the heck, this seems to do the job!</p> <p><em>muhuk</em>'s solution though looks more elegant than this...</p>
3
2009-03-11T20:22:21Z
[ "python", "django", "forms" ]
Inserting A Heading Into A Django Form
635,583
<p>I would like my form to output something like this:</p> <pre><code>Name: ___________ Company: ___________ Interested in ------------- Foo: [ ] Bar: [ ] Baz: [ ] </code></pre> <p>That is to say, I would like to have the 'Interested In' title inserted in the middle of my form output.</p> <p>One way of doing this would be to write out the template code for each field, and insert the heading as appropriate. However, I'd prefer not to do this. I suspect that there is something to do with formsets that will do what I want.</p> <p><em>Is</em> there a way to do what I want, or do I just need to suck it up and accept that I need to write my template out longhand for this?</p>
2
2009-03-11T17:37:13Z
24,209,246
<p>It's a bit of a hack, but you could define a <code>HeaderWidget</code> that just renders its value:</p> <pre><code>from django.forms.util import flatatt from django.utils.html import format_html class HeaderWidget(forms.widgets.Widget): def render(self, name, value, attrs=None): attrs.update(self.attrs) return format_html('&lt;div{0}&gt;{1}&lt;/div&gt;', flatatt(attrs), value) </code></pre> <p>and then add a field in the desired spot using that widget:</p> <pre><code>header = forms.CharField( widget=HeaderWidget(attrs={'class': 'my-css-class'}), initial='Interested in', required=False, label='') </code></pre> <p>A minor downside is that you'll get the header "value" posted with your form.</p>
0
2014-06-13T15:43:05Z
[ "python", "django", "forms" ]
tell whether a character is a combining diacritic mark
635,643
<p>if you're looping though the chars a unicode string in python (2.x), say:</p> <blockquote> <p>ak.sɛp.tɑ̃</p> </blockquote> <p>How can you tell whether the current char is a combining diacritic mark?</p> <p>For instance, the last char in the above string is actually a combining mark:</p> <blockquote> <p>ak.sɛp.tɑ̃ --> ̃</p> </blockquote>
3
2009-03-11T17:55:57Z
635,716
<p>Use the unicodedata module:</p> <pre><code>import unicodedata if unicodedata.combining(u'a'): print "is combining character" else: print "is not combining" </code></pre> <p>these posts are also relevant</p> <p><a href="http://stackoverflow.com/questions/446222/how-do-i-reverse-unicode-decomposition-using-python">http://stackoverflow.com/questions/446222/how-do-i-reverse-unicode-decomposition-using-python</a></p> <p><a href="http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string">http://stackoverflow.com/questions/517923/what-is-the-best-way-to-remove-accents-in-a-python-unicode-string</a></p>
7
2009-03-11T18:15:22Z
[ "python", "unicode", "diacritics" ]
python: problem using call.subprocess to use a file after writing it
635,946
<p>In python I am trying to write a script that will edit text files and then run executables that use those text files. It basically entails 1)opening and reading/writing to a text file, and 2)using the file I just wrote in a bash command. Here is a simple example:</p> <pre><code>import subprocess # write file a = ['1\n','2\n','3\n','4\n','5th and final line'] f = open('junk01.txt', 'wb') f.writelines(a) f.close # show file subprocess.call('cat junk01.txt', shell=True) </code></pre> <p>For some reason on that <code>subprocess.call</code> command it is not showing the contents of the junk01.txt file. However after I run this code and type <code>cat junk01.txt</code> in bash the file has been written properly. Similarly, I'm finding that after I open, write to, and close a text file and then try to use it in an executable, the file hasn't been written to yet. Any explanation on why this is and what I can do to fix it?</p>
0
2009-03-11T19:14:37Z
635,961
<p>Close the file by actually calling the close() method. This will implicitly flush the buffers to disk.</p> <pre><code>f.close() </code></pre> <p>rather than</p> <pre><code>f.close #this probably doesn't do anything, but if there was no close method it would raise an error. </code></pre>
9
2009-03-11T19:18:45Z
[ "python", "subprocess" ]
python: problem using call.subprocess to use a file after writing it
635,946
<p>In python I am trying to write a script that will edit text files and then run executables that use those text files. It basically entails 1)opening and reading/writing to a text file, and 2)using the file I just wrote in a bash command. Here is a simple example:</p> <pre><code>import subprocess # write file a = ['1\n','2\n','3\n','4\n','5th and final line'] f = open('junk01.txt', 'wb') f.writelines(a) f.close # show file subprocess.call('cat junk01.txt', shell=True) </code></pre> <p>For some reason on that <code>subprocess.call</code> command it is not showing the contents of the junk01.txt file. However after I run this code and type <code>cat junk01.txt</code> in bash the file has been written properly. Similarly, I'm finding that after I open, write to, and close a text file and then try to use it in an executable, the file hasn't been written to yet. Any explanation on why this is and what I can do to fix it?</p>
0
2009-03-11T19:14:37Z
20,544,443
<p>Although the first answer is most definitely correct and proper, you could also just set f to None instead of was was done as follows:</p> <pre><code>import subprocess # write file a = ['1\n','2\n','3\n','4\n','5th and final line\n'] f = open('junk01.txt', 'wb') f.writelines(a) f = None # show file subprocess.call('cat junk01.txt', shell=True) </code></pre> <p>~ </p> <p>Setting f to None takes the variable out of service and causes the file to be closed implicitly instead of being explicitly closed (as in the first preferred example) I don't advocate this style of writing code as its a bit sloppy, I just mention it as an alternative solution.</p> <pre><code>[centos@localhost ~/test/stack]$ python 1.py 1 2 3 4 5th and final line [centos@localhost ~/test/stack]$ </code></pre>
0
2013-12-12T13:08:19Z
[ "python", "subprocess" ]
What's different between Python and Javascript regular expressions?
636,485
<p>Are Python and JavaScript regular expression syntax identical? </p> <p>If not, then: </p> <ol> <li>What are the important differences between them</li> <li>Is there a python library that "implements" JavaScript regexps?</li> </ol>
25
2009-03-11T21:36:56Z
636,501
<p>There is a comparison table here:</p> <p><a href="http://www.regular-expressions.info/refflavors.html">Regex Flavor Comparison</a></p>
25
2009-03-11T21:42:55Z
[ "javascript", "python", "regex" ]
What's different between Python and Javascript regular expressions?
636,485
<p>Are Python and JavaScript regular expression syntax identical? </p> <p>If not, then: </p> <ol> <li>What are the important differences between them</li> <li>Is there a python library that "implements" JavaScript regexps?</li> </ol>
25
2009-03-11T21:36:56Z
636,506
<p><a href="http://www.regular-expressions.info/javascript.html" rel="nofollow">http://www.regular-expressions.info/javascript.html</a> vs <a href="http://www.regular-expressions.info/python.html" rel="nofollow">http://www.regular-expressions.info/python.html</a></p>
2
2009-03-11T21:44:12Z
[ "javascript", "python", "regex" ]
What's different between Python and Javascript regular expressions?
636,485
<p>Are Python and JavaScript regular expression syntax identical? </p> <p>If not, then: </p> <ol> <li>What are the important differences between them</li> <li>Is there a python library that "implements" JavaScript regexps?</li> </ol>
25
2009-03-11T21:36:56Z
636,523
<p><strong>Part 1</strong><br /> They are different; One difference is Python supports Unicode and Javascript doesn't. </p> <p><strong>Part 2</strong><br /> Read <a href="http://oreilly.com/catalog/9780596528126/" rel="nofollow">Mastering Regular Expressions</a>. It gives information on how to identify the back-end engines (DFA vs NFA vs Hybrid) that a regex flavour uses. It gives tons of information on the different regex flavours out there. </p> <p>There is <em>way</em> too much information to convey on a single SO answer, so you're better off having a solid piece of reference material on the subject.</p>
5
2009-03-11T21:48:57Z
[ "javascript", "python", "regex" ]
SELECT * in sqlalchemy?
636,548
<p>Is it possible to do <code>SELECT *</code> in sqlalchemy?</p> <p>Edit: Specifically, <code>SELECT * WHERE foo=1</code></p>
12
2009-03-11T21:56:49Z
636,571
<p>If you don't list any columns, you get all of them.</p> <pre><code>query = users.select() query = query.where(users.c.name=='jack') result = conn.execute(query) for row in result: print row </code></pre> <p>Should work.</p>
3
2009-03-11T22:05:48Z
[ "python", "sqlalchemy" ]
SELECT * in sqlalchemy?
636,548
<p>Is it possible to do <code>SELECT *</code> in sqlalchemy?</p> <p>Edit: Specifically, <code>SELECT * WHERE foo=1</code></p>
12
2009-03-11T21:56:49Z
636,596
<p>Turns out you can do:</p> <pre><code>sa.select('*', ...) </code></pre>
1
2009-03-11T22:13:53Z
[ "python", "sqlalchemy" ]
SELECT * in sqlalchemy?
636,548
<p>Is it possible to do <code>SELECT *</code> in sqlalchemy?</p> <p>Edit: Specifically, <code>SELECT * WHERE foo=1</code></p>
12
2009-03-11T21:56:49Z
636,631
<p>Is no one feeling the ORM love of SQLALchemy today? The presented answers correctly describe the lower level interface that SQLAlchemy provides. Just for completeness this is the more-likely <em>(for me)</em> real-world situation where you have a session instance and a User class that is orm mapped to the users table.</p> <pre><code>for user in session.query(User).filter_by(name='jack'): print user # ... </code></pre> <p>And this does an explicit select on all columns.</p>
19
2009-03-11T22:27:31Z
[ "python", "sqlalchemy" ]
SELECT * in sqlalchemy?
636,548
<p>Is it possible to do <code>SELECT *</code> in sqlalchemy?</p> <p>Edit: Specifically, <code>SELECT * WHERE foo=1</code></p>
12
2009-03-11T21:56:49Z
636,709
<p>Where <strong>Bar</strong> is the class mapped to your table and <strong>session</strong> is your sa session:</p> <pre><code>bars = session.query(Bar).filter(Bar.foo == 1)</code></pre>
7
2009-03-11T23:02:32Z
[ "python", "sqlalchemy" ]
SELECT * in sqlalchemy?
636,548
<p>Is it possible to do <code>SELECT *</code> in sqlalchemy?</p> <p>Edit: Specifically, <code>SELECT * WHERE foo=1</code></p>
12
2009-03-11T21:56:49Z
12,632,528
<p>If you're using the ORM, you can build a query using the normal ORM constructs and then execute it directly to get raw column values:</p> <pre><code>query = session.query(User).filter_by(name='jack') for cols in session.connection().execute(query): print cols </code></pre>
1
2012-09-28T01:50:06Z
[ "python", "sqlalchemy" ]
SELECT * in sqlalchemy?
636,548
<p>Is it possible to do <code>SELECT *</code> in sqlalchemy?</p> <p>Edit: Specifically, <code>SELECT * WHERE foo=1</code></p>
12
2009-03-11T21:56:49Z
16,064,769
<p>You can always use a raw SQL too:</p> <pre><code>str_sql = sql.text("YOUR STRING SQL") #if you have some args: args = { 'myarg1': yourarg1 'myarg2': yourarg2} #then call the execute method from your connection results = conn.execute(str_sql,args).fetchall() </code></pre>
2
2013-04-17T15:56:37Z
[ "python", "sqlalchemy" ]
SELECT * in sqlalchemy?
636,548
<p>Is it possible to do <code>SELECT *</code> in sqlalchemy?</p> <p>Edit: Specifically, <code>SELECT * WHERE foo=1</code></p>
12
2009-03-11T21:56:49Z
19,514,773
<p>For joins if columns are not defined manually, only columns of target table are returned. To get all columns for joins(User table joined with Group Table:</p> <pre class="lang-py prettyprint-override"><code>sql = User.select(from_obj(Group, User.c.group_id == Group.c.id)) # Add all coumns of Group table to select sql = sql.column(Group) session.connection().execute(sql) </code></pre>
3
2013-10-22T10:05:49Z
[ "python", "sqlalchemy" ]
SELECT * in sqlalchemy?
636,548
<p>Is it possible to do <code>SELECT *</code> in sqlalchemy?</p> <p>Edit: Specifically, <code>SELECT * WHERE foo=1</code></p>
12
2009-03-11T21:56:49Z
23,228,825
<p>The following selection works for me in the core expression language (returning a <a href="http://docs.sqlalchemy.org/en/latest/core/connections.html#sqlalchemy.engine.RowProxy" rel="nofollow">RowProxy object</a>):</p> <pre><code>foo_col = sqlalchemy.sql.column('foo') s = sqlalchemy.sql.select(['*']).where(foo_col == 1) </code></pre>
6
2014-04-22T19:48:44Z
[ "python", "sqlalchemy" ]