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
listlengths
1
5
Python: what kind of literal delimiter is "better" to use?
1,312,940
<p>What is the best literal delimiter in Python and why? Single ' or double "? And most important, why?</p> <p>I'm a beginner in Python and I'm trying to stick with just one. I know that in PHP, for example " is preferred, because PHP does not try to search for the 'string' variable. Is the same case in Python?</p>
2
2009-08-21T16:26:42Z
1,312,983
<p>Semantically there is no difference in Python; use either. Python also provides the handy triple string delimiter """ or ''' which can simplify multi-line quotes. There is also the raw string literal (r"..." or r'...') to inhibit \ escapes. The <a href="http://docs.python.org/reference/lexical%5Fanalysis.html#string-literals" rel="nofollow">Language Reference</a> has all the details.</p>
3
2009-08-21T16:35:00Z
[ "python", "string" ]
Python: what kind of literal delimiter is "better" to use?
1,312,940
<p>What is the best literal delimiter in Python and why? Single ' or double "? And most important, why?</p> <p>I'm a beginner in Python and I'm trying to stick with just one. I know that in PHP, for example " is preferred, because PHP does not try to search for the 'string' variable. Is the same case in Python?</p>
2
2009-08-21T16:26:42Z
1,313,334
<p>Other answers are about nested quoting. Another point of view I've come across, but I'm not sure I subscribe to, is to use single-quotes(') for characters (which are strings, but ord/chr are quick picky) and to use double-quotes for strings. Which disambiguates between a string that is supposed to be one character and one that just happens to be one character.</p> <p>Personally I find most touch typists aren't affected noticably by the "load" of using the shift-key. YMMV on that part. Going down the "it's faster to not use the shift" is a slippery slope. It's also faster to use hyper-condensed variable/function/class/module names. Everyone just so loves the fast and short 8.3 DOS files names too. :) Pick what makes semantic sense to you, then optimize.</p>
0
2009-08-21T17:49:58Z
[ "python", "string" ]
Python: what kind of literal delimiter is "better" to use?
1,312,940
<p>What is the best literal delimiter in Python and why? Single ' or double "? And most important, why?</p> <p>I'm a beginner in Python and I'm trying to stick with just one. I know that in PHP, for example " is preferred, because PHP does not try to search for the 'string' variable. Is the same case in Python?</p>
2
2009-08-21T16:26:42Z
1,314,042
<p>This is a rule I have heard about:</p> <p>") If the string is for human consuption, that is interface text or output, use ""</p> <p>') If the string is a specifier, like a dictionary key or an option, use ''</p> <p>I think a well-enforced rule like that can make sense for a project, but it's nothing that I would personally care much about. I like the above, since I read it, but I always use "" (since I learned C first wayy back?).</p>
0
2009-08-21T20:24:54Z
[ "python", "string" ]
Python: what kind of literal delimiter is "better" to use?
1,312,940
<p>What is the best literal delimiter in Python and why? Single ' or double "? And most important, why?</p> <p>I'm a beginner in Python and I'm trying to stick with just one. I know that in PHP, for example " is preferred, because PHP does not try to search for the 'string' variable. Is the same case in Python?</p>
2
2009-08-21T16:26:42Z
1,314,065
<p>I don't think there is a single best string delimiter. I like to use different delimiters to indicate different kinds of string. Specifically, I like to use <code>"..."</code> to delimit stings that are used for interpolation or that are natural language messages, and <code>'...'</code> to delimit small symbol-like strings. This gives me a subtle extra clue to the expected use for the string literal.</p> <p>I try to always use raw strings (<code>r"..."</code>) for regular expressions because (1) I don't have to escape backslash characters and (2) my editor recognises this convention and does syntax highlighting inside the regex.</p> <p>The stylistic issues of single- vs. double-quotes are covered in <a href="http://stackoverflow.com/questions/56011/single-quotes-vs-double-quotes-in-python">question 56011</a>.</p>
0
2009-08-21T20:32:07Z
[ "python", "string" ]
Inserting python tuple in a MySQL database
1,313,000
<p>I need to insert a python tuple (of floats) into a MySQL database. In principle I could pickle it and insert it as a string, but that would grant me the chance only to retrieve it through python. Alternative is to serialize the tuple to XML and store the XML string.</p> <p>What solutions do you think would be also possible, with an eye toward storing other stuff (e.g. a list, or an object). Recovering it from other languages is a plus.</p>
0
2009-08-21T16:39:03Z
1,313,012
<p>How about <a href="http://www.json.org/" rel="nofollow" title="JSON">JSON</a> ... it's compact, and there are interpreters available for it in most languages.</p>
2
2009-08-21T16:42:59Z
[ "python", "mysql" ]
Inserting python tuple in a MySQL database
1,313,000
<p>I need to insert a python tuple (of floats) into a MySQL database. In principle I could pickle it and insert it as a string, but that would grant me the chance only to retrieve it through python. Alternative is to serialize the tuple to XML and store the XML string.</p> <p>What solutions do you think would be also possible, with an eye toward storing other stuff (e.g. a list, or an object). Recovering it from other languages is a plus.</p>
0
2009-08-21T16:39:03Z
1,313,013
<p>Make another table and do one-to-many. Don't try to cram a programming language feature into a database as-is if you can avoid it.</p> <p>If you absolutely need to be able to store an object down the line, your options are a bit more limited. YAML is probably the best balance of human-readable and program-readable, and it has some syntax for specifying classes you might be able to use.</p>
3
2009-08-21T16:43:15Z
[ "python", "mysql" ]
Inserting python tuple in a MySQL database
1,313,000
<p>I need to insert a python tuple (of floats) into a MySQL database. In principle I could pickle it and insert it as a string, but that would grant me the chance only to retrieve it through python. Alternative is to serialize the tuple to XML and store the XML string.</p> <p>What solutions do you think would be also possible, with an eye toward storing other stuff (e.g. a list, or an object). Recovering it from other languages is a plus.</p>
0
2009-08-21T16:39:03Z
1,313,016
<p>I'd look at serializing it to JSON, using the simplejson package, or the built-in json package in python 2.6.</p> <p>It's simple to use in python, importable by practically every other language, and you don't have to make all of the "what tag should I use? what attributes should this have?" decisions that you might in XML.</p>
2
2009-08-21T16:44:01Z
[ "python", "mysql" ]
Porting python app to mobile platforms
1,313,164
<p>I have a python app running fine on Windows, Linux and Mac which I would like to port to multiple mobile platforms such as Blackberry, Windows Mobile, Palm, Android and iPhone.</p> <p>I have couple of ideas:</p> <ul> <li>port app to platform supporting some kind of Python like Android and Windows Mobile</li> <li>port app to Java to target most platforms right away</li> </ul> <p>What would you recommend ?</p>
3
2009-08-21T17:13:00Z
1,313,192
<p><a href="http://www.velocityreviews.com/forums/t321090-jython-and-j2me.html" rel="nofollow">Jython is out of the question</a>, so either go with supported phones (Windows Mobile, Android, Nokia S60), or rewrite in J2ME.</p>
1
2009-08-21T17:17:27Z
[ "python", "mobile", "porting" ]
Porting python app to mobile platforms
1,313,164
<p>I have a python app running fine on Windows, Linux and Mac which I would like to port to multiple mobile platforms such as Blackberry, Windows Mobile, Palm, Android and iPhone.</p> <p>I have couple of ideas:</p> <ul> <li>port app to platform supporting some kind of Python like Android and Windows Mobile</li> <li>port app to Java to target most platforms right away</li> </ul> <p>What would you recommend ?</p>
3
2009-08-21T17:13:00Z
1,313,234
<p>Here's what we're doing ...</p> <p>Make the app a generic web application/website. Host it on your server and have your server detect the type of browser. If it is a mobile browser, show the small-screen version of your app.</p> <p>Once you get that going, create individual apps for the particular phones/mobile hardware. Those will each have a single web browser control in them. The web browser will have a hardcoded URL which points to your web site.</p> <p>For example, write a java wrapper for Google Android. Write an Objective-C wrapper for Cocoa Touch (iPhone using XCode). Your wrapper for Windows Mobile will be in a .Net Framework app in C# or VB.Net (or IronPython for that matter).</p> <p>Here's how to do it for iPhone: <a href="http://www.iphonesdkarticles.com/2008/08/uiwebview-tutorial.html" rel="nofollow">http://www.iphonesdkarticles.com/2008/08/uiwebview-tutorial.html</a></p> <p>Here's how to do it for Android: <a href="http://developerlife.com/tutorials/?p=369" rel="nofollow">http://developerlife.com/tutorials/?p=369</a></p> <p>Here's how to do it for Windows Mobile: <a href="http://msdn.microsoft.com/en-us/library/ms229657.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms229657.aspx</a></p> <p>The wrapper can then access the phone's firmware for motion, GPS info, sounds, and so forth.</p> <p>The beauty of this is</p> <ol> <li><p>You can now submit each app to the individual platform's AppStore which is the #1 way to get new customers.</p></li> <li><p>You have one set of source and one place to upgrade. When you upgrade in one location, everyone gets it immediately.</p></li> </ol>
4
2009-08-21T17:27:11Z
[ "python", "mobile", "porting" ]
Porting python app to mobile platforms
1,313,164
<p>I have a python app running fine on Windows, Linux and Mac which I would like to port to multiple mobile platforms such as Blackberry, Windows Mobile, Palm, Android and iPhone.</p> <p>I have couple of ideas:</p> <ul> <li>port app to platform supporting some kind of Python like Android and Windows Mobile</li> <li>port app to Java to target most platforms right away</li> </ul> <p>What would you recommend ?</p>
3
2009-08-21T17:13:00Z
1,313,264
<p>Use JavaScript with <a href="http://www.appcelerator.com/products/titanium-mobile/" rel="nofollow">Titanium Mobile</a> to target iPhone and Android, and the Pre in the future. It compiles into native applications.</p>
0
2009-08-21T17:33:06Z
[ "python", "mobile", "porting" ]
Porting python app to mobile platforms
1,313,164
<p>I have a python app running fine on Windows, Linux and Mac which I would like to port to multiple mobile platforms such as Blackberry, Windows Mobile, Palm, Android and iPhone.</p> <p>I have couple of ideas:</p> <ul> <li>port app to platform supporting some kind of Python like Android and Windows Mobile</li> <li>port app to Java to target most platforms right away</li> </ul> <p>What would you recommend ?</p>
3
2009-08-21T17:13:00Z
1,313,550
<p>Use <a href="http://rhomobile.com/" rel="nofollow">RhoMobile's Rhodes</a>. Allows you to write the app in Ruby once and run it in multiple mobile platforms: iPhone, Symbian, Android, BlackBerry, and Windows Mobile.</p>
2
2009-08-21T18:26:19Z
[ "python", "mobile", "porting" ]
Django without additional tables?
1,313,362
<p>is it possible to write Django apps, for example for internal/personal use with existing databases, without having the 'overhead' of Djangos own tables that are usually installed when starting a project ? I would like to use existing tables via models, but not have all the other stuff that is surely useful on normal webpages. The reason would be to build small personal inspection/admin tools without being to invasive on legacy databases.</p>
1
2009-08-21T17:56:13Z
1,313,406
<p>Django doesn't install any tables by itself. It comes with some pre-fabricated applications, which install tables, but those are easily disabled by removing them from the <code>INSTALLED_APPS</code> setting.</p>
3
2009-08-21T18:03:50Z
[ "python", "database", "django", "table" ]
Django without additional tables?
1,313,362
<p>is it possible to write Django apps, for example for internal/personal use with existing databases, without having the 'overhead' of Djangos own tables that are usually installed when starting a project ? I would like to use existing tables via models, but not have all the other stuff that is surely useful on normal webpages. The reason would be to build small personal inspection/admin tools without being to invasive on legacy databases.</p>
1
2009-08-21T17:56:13Z
1,313,575
<p>Don't install any of Django's built-in apps and don't use any <code>models.py</code> in your apps. Your database will have zero tables in it.</p> <p>You won't have users, sites or sessions -- those are Django features that use the database.</p> <p>AFAIK you should still, however, have a SQLite database. I think that parts of Django assume you've got a database connection and it may try to establish this connection.</p> <p>It's an easy experiment to try.</p>
0
2009-08-21T18:32:33Z
[ "python", "database", "django", "table" ]
Django without additional tables?
1,313,362
<p>is it possible to write Django apps, for example for internal/personal use with existing databases, without having the 'overhead' of Djangos own tables that are usually installed when starting a project ? I would like to use existing tables via models, but not have all the other stuff that is surely useful on normal webpages. The reason would be to build small personal inspection/admin tools without being to invasive on legacy databases.</p>
1
2009-08-21T17:56:13Z
1,313,592
<p>The most noticable app with database tables defined is <code>django.contrib.auth</code>, which implements its own auth backend in the database. You could probably skip auth all together if your app is firewalled and you trust all the people that have access to it. If otherwise, you want to create your own auth mechanism using existing infrastructure, you most likely want to use another backend. If your web-server sets <code>REMOTE_USER</code>, you can use <a href="http://docs.djangoproject.com/en/dev/howto/auth-remote-user/#authentication-using-remote-user" rel="nofollow">another builtin backend</a> and you should be off and running. Otherwise you will have to implement your own to refer to other auth sources.</p> <p>From there you only need to set up your models to use existing database tables instead of letting them make their own. You can have very fine control over this, for example</p> <pre><code>class MyModel(django.db.Model): MyTextField = django.db.TextField(db_column="mytextfield", primary_key=True) class Meta: db_table = "my_table" </code></pre> <p>This way you can specify the exact table and columns from which each field of each model shall represent. Note that You can set the primary key to be a type other than integer. A limitation of django's ORM is that every model must have exactly one primary key, though. So if you don't have a primary key for your table, either add one, or you have to get along without the help of django's ORM. </p> <p>Also, since you are tying in to an existing data-set, possibly that relates to other apps, you won't likely want to use <code>./manage.py syncdb</code> since it may do some undesireable things.</p>
1
2009-08-21T18:36:11Z
[ "python", "database", "django", "table" ]
Django without additional tables?
1,313,362
<p>is it possible to write Django apps, for example for internal/personal use with existing databases, without having the 'overhead' of Djangos own tables that are usually installed when starting a project ? I would like to use existing tables via models, but not have all the other stuff that is surely useful on normal webpages. The reason would be to build small personal inspection/admin tools without being to invasive on legacy databases.</p>
1
2009-08-21T17:56:13Z
1,315,203
<p>Just commentize the <em>django</em> app strings of the INSTALLED_APPS tuple in your project settings.py file (at the beginning of the project, before running syncdb).</p>
0
2009-08-22T05:18:26Z
[ "python", "database", "django", "table" ]
Django without additional tables?
1,313,362
<p>is it possible to write Django apps, for example for internal/personal use with existing databases, without having the 'overhead' of Djangos own tables that are usually installed when starting a project ? I would like to use existing tables via models, but not have all the other stuff that is surely useful on normal webpages. The reason would be to build small personal inspection/admin tools without being to invasive on legacy databases.</p>
1
2009-08-21T17:56:13Z
3,186,831
<p>You can also just add an extra database (set it as default) for keeping the extra django overhead stuff in:</p> <pre><code>DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.sqlite', 'NAME' : 'djangoOverhead', 'USER' : '', 'PASSWORD' : '', 'HOST' : 'localhost' }, 'legacyAppTables': { 'ENGINE' : 'django.db.backends.mysql', 'NAME' : 'legacyAppTables', 'USER' : '', 'PASSWORD' : '', 'HOST' : 'someRemoteHost' }, } </code></pre>
2
2010-07-06T13:57:26Z
[ "python", "database", "django", "table" ]
Where is the best place to put cache-evicting logic in an AppEngine application?
1,313,626
<p>I've written an application for Google AppEngine, and I'd like to make use of the memcache API to cut down on per-request CPU time. I've profiled the application and found that a large chunk of the CPU time is in template rendering and API calls to the datastore, and after chatting with a co-worker I jumped (perhaps a bit early?) to the conclusion that caching a chunk of a page's rendered HTML would cut down on the CPU time per request significantly. The caching pattern is pretty clean, but the question of <em>where</em> to put this logic of caching and evicting is a bit of a mystery to me.</p> <p>For example, imagine an application's main page has an Announcements section. This section would need to be re-rendered after:</p> <ul> <li>first read for anyone in the account,</li> <li>a new announcement being added, and</li> <li>an old announcement being deleted</li> </ul> <p>Some options of where to put the <code>evict_announcements_section_from_cache()</code> method call:</p> <ul> <li>in the Announcement Model's <code>.delete()</code>, and <code>.put()</code> methods</li> <li>in the RequestHandler's <code>.post()</code> method</li> <li>anywhere else?</li> </ul> <p>Then in the RequestHandler's get page, I could potentially call <code>get_announcements_section()</code> which would follow the standard memcache pattern (check cache, add to cache on miss, return value) and pass that HTML down to the template for that chunk of the page.</p> <p>Is it the typical design pattern to put the cache-evicting logic in the Model, or the Controller/RequestHandler, or somewhere else? Ideally I'd like to avoid having evicting logic with tentacles all over the code.</p>
2
2009-08-21T18:44:29Z
1,314,437
<p>I've got just such a decorator up in an open source Github project:</p> <p><a href="http://github.com/jamslevy/gae%5Fmemoize/tree/master" rel="nofollow">http://github.com/jamslevy/gae%5Fmemoize/tree/master</a></p> <p>It's a bit more in-depth, allowing for things like forcing execution of the function (when you want to refresh the cache) or forcing caching locally...these were just things that I needed in my app, so I baked them into my memoize decorator.</p>
1
2009-08-21T22:13:02Z
[ "python", "google-app-engine", "optimization", "caching", "memcached" ]
Where is the best place to put cache-evicting logic in an AppEngine application?
1,313,626
<p>I've written an application for Google AppEngine, and I'd like to make use of the memcache API to cut down on per-request CPU time. I've profiled the application and found that a large chunk of the CPU time is in template rendering and API calls to the datastore, and after chatting with a co-worker I jumped (perhaps a bit early?) to the conclusion that caching a chunk of a page's rendered HTML would cut down on the CPU time per request significantly. The caching pattern is pretty clean, but the question of <em>where</em> to put this logic of caching and evicting is a bit of a mystery to me.</p> <p>For example, imagine an application's main page has an Announcements section. This section would need to be re-rendered after:</p> <ul> <li>first read for anyone in the account,</li> <li>a new announcement being added, and</li> <li>an old announcement being deleted</li> </ul> <p>Some options of where to put the <code>evict_announcements_section_from_cache()</code> method call:</p> <ul> <li>in the Announcement Model's <code>.delete()</code>, and <code>.put()</code> methods</li> <li>in the RequestHandler's <code>.post()</code> method</li> <li>anywhere else?</li> </ul> <p>Then in the RequestHandler's get page, I could potentially call <code>get_announcements_section()</code> which would follow the standard memcache pattern (check cache, add to cache on miss, return value) and pass that HTML down to the template for that chunk of the page.</p> <p>Is it the typical design pattern to put the cache-evicting logic in the Model, or the Controller/RequestHandler, or somewhere else? Ideally I'd like to avoid having evicting logic with tentacles all over the code.</p>
2
2009-08-21T18:44:29Z
1,348,633
<p>A couple of alternatives to regular eviction:</p> <ol> <li>The obvious one: Don't evict, and set a timer instead. Even a really short one - a few seconds - can cut down on effort a huge amount for a popular app, without users even noticing data may be a few seconds stale.</li> <li>Instead of evicting, generate the cache key based on criteria that change when the data does. For example, if retrieving the key of the most recent announcement is cheap, you could use that as part of the key of the cached data. When a new announcement is posted, you go looking for a key that doesn't exist, and create a new one as a result.</li> </ol>
1
2009-08-28T18:29:13Z
[ "python", "google-app-engine", "optimization", "caching", "memcached" ]
Parsing FLV header (duration) of remote file in Java
1,313,640
<p>I'm looking for an example of parsing an FLV header for duration specifically in Java. Given the URL of an FLV file I want to download the header only and parse out the duration. I have the FLV spec but I want an example. Python or PHP would be OK too but Java is preferred.</p>
5
2009-08-21T18:47:56Z
1,314,739
<p>Do you have problems downloading the header or parsing it? if it's downloading then use this code:</p> <pre><code>URL url = new URL(fileUrl); InputStream dis = url.openStream(); byte[] header = new byte[HEADER_SIZE]; dis.read(header); </code></pre> <p>You can wrap InputStream with DataInputStream if you want to read int's rather than bytes.</p> <p>After that just look at getInfo method from PHP-FLV Info or read the spec.</p>
1
2009-08-22T00:15:51Z
[ "java", "python", "flash", "flv" ]
Parsing FLV header (duration) of remote file in Java
1,313,640
<p>I'm looking for an example of parsing an FLV header for duration specifically in Java. Given the URL of an FLV file I want to download the header only and parse out the duration. I have the FLV spec but I want an example. Python or PHP would be OK too but Java is preferred.</p>
5
2009-08-21T18:47:56Z
3,670,931
<p>As <a href="http://stackoverflow.com/users/423943/the-alchemist">the-alchemist</a> states in <a href="http://stackoverflow.com/questions/3669109/how-to-get-flv-duration-in-java">this other question</a>:</p> <blockquote> <p>The <a href="https://code.google.com/p/red5/" rel="nofollow">Red5 project</a> has a class called <a href="http://red5.googlecode.com/svn-history/r3847/java/server/branches/xuggle_timestamp_fixes/src/org/red5/io/flv/impl/FLVReader.java" rel="nofollow"><code>FLVReader</code></a> which does what you want. It's LGPL licensed.</p> </blockquote> <p>I've tried it and it works fine. You'll need this libraries:</p> <ul> <li><a href="https://code.google.com/p/red5/downloads/list" rel="nofollow">Red5 library jar for use when building applications</a> </li> <li><a href="http://commons.apache.org/logging/download_logging.cgi" rel="nofollow">Apache Commons Logging</a></li> <li><a href="http://mina.apache.org/downloads.html" rel="nofollow">Apache MINA</a></li> </ul> <p>Getting the FLV video duration is as simple as this:</p> <pre><code>FLVReader flvReader = new FLVReader(...); // Can use a File or a ByteBuffer as input long duration = flvReader.getDuration(); // Returns the duration in milliseconds </code></pre>
0
2010-09-08T18:44:44Z
[ "java", "python", "flash", "flv" ]
What is this construct called in python: ( x, y )
1,313,805
<p>What is this called in python:</p> <pre><code>[('/', MainPage)] </code></pre> <p>Is that an array .. of ... erhm one dictionary? </p> <p>Is that</p> <pre><code>() </code></pre> <p>A tuple? ( or whatever they call it? ) </p>
5
2009-08-21T19:27:03Z
1,313,809
<p>Its a list with a single tuple.</p>
14
2009-08-21T19:28:11Z
[ "python" ]
What is this construct called in python: ( x, y )
1,313,805
<p>What is this called in python:</p> <pre><code>[('/', MainPage)] </code></pre> <p>Is that an array .. of ... erhm one dictionary? </p> <p>Is that</p> <pre><code>() </code></pre> <p>A tuple? ( or whatever they call it? ) </p>
5
2009-08-21T19:27:03Z
1,313,814
<p>Yes, it's a <a href="http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow">tuple</a>.</p> <p>They look like this:</p> <pre><code>() (foo,) (foo, bar) (foo, bar, baz) </code></pre> <p>etc.</p>
1
2009-08-21T19:28:40Z
[ "python" ]
What is this construct called in python: ( x, y )
1,313,805
<p>What is this called in python:</p> <pre><code>[('/', MainPage)] </code></pre> <p>Is that an array .. of ... erhm one dictionary? </p> <p>Is that</p> <pre><code>() </code></pre> <p>A tuple? ( or whatever they call it? ) </p>
5
2009-08-21T19:27:03Z
1,313,816
<p>That's a list of tuples.</p> <p>This is a list of integers: <code>[1, 2, 3, 4, 5]</code></p> <p>This is also a list of integers: <code>[1]</code></p> <p>This is a (string, integer) tuple: <code>("hello world", 42)</code></p> <p>This is a list of (string, integer) tuples: <code>[("a", 1), ("b", 2), ("c", 3)]</code></p> <p>And so is this: <code>[("a", 1)]</code></p> <p>In Python, there's not much difference between lists and tuples. However, they are conceptually different. An easy way to think of it is that a list contains lots of items of the same type (homogeneous) , and a tuple contains a fixed number of items of different types (heterogeneous). An easy way to remember this is that lists can be appended to, and tuples cannot, because appending to a list makes sense and appending to a tuple doesn't.</p> <p>Python doesn't enforce these distinctions -- in Python, you can append to a tuple with <code>+</code>, or store heterogeneous types in a list.</p>
2
2009-08-21T19:29:15Z
[ "python" ]
What is this construct called in python: ( x, y )
1,313,805
<p>What is this called in python:</p> <pre><code>[('/', MainPage)] </code></pre> <p>Is that an array .. of ... erhm one dictionary? </p> <p>Is that</p> <pre><code>() </code></pre> <p>A tuple? ( or whatever they call it? ) </p>
5
2009-08-21T19:27:03Z
1,313,820
<pre><code>[('/', MainPage)] </code></pre> <p>That's a list consisting of a two element tuple.</p> <pre><code>() </code></pre> <p>That's a zero element tuple.</p>
1
2009-08-21T19:30:02Z
[ "python" ]
What is this construct called in python: ( x, y )
1,313,805
<p>What is this called in python:</p> <pre><code>[('/', MainPage)] </code></pre> <p>Is that an array .. of ... erhm one dictionary? </p> <p>Is that</p> <pre><code>() </code></pre> <p>A tuple? ( or whatever they call it? ) </p>
5
2009-08-21T19:27:03Z
1,313,851
<p>Note that this:</p> <pre><code>("is not a tuple") </code></pre> <p>A tuple is defined by the commas, except in the case of the zero-length tuple. This:</p> <pre><code>"is a tuple", </code></pre> <p>because of the comma at the end. The parentheses just enforce grouping (again, except in the case of a zero-length tuple.</p>
3
2009-08-21T19:35:32Z
[ "python" ]
What is this construct called in python: ( x, y )
1,313,805
<p>What is this called in python:</p> <pre><code>[('/', MainPage)] </code></pre> <p>Is that an array .. of ... erhm one dictionary? </p> <p>Is that</p> <pre><code>() </code></pre> <p>A tuple? ( or whatever they call it? ) </p>
5
2009-08-21T19:27:03Z
1,313,900
<p>It is a list of tuple(s). You can verify that by</p> <pre><code>x=[('/', MainPage)] print type(x) # You will find a &lt;list&gt; type here print type(x[0]) # You will find a &lt;tuple&gt; type here </code></pre> <p>You can build a dictionary from this type of structure (may be more tuple inside the list) with this code</p> <pre><code>my_dict = dict(x) # x=[('/',MainPage)] </code></pre>
1
2009-08-21T19:45:46Z
[ "python" ]
What is this construct called in python: ( x, y )
1,313,805
<p>What is this called in python:</p> <pre><code>[('/', MainPage)] </code></pre> <p>Is that an array .. of ... erhm one dictionary? </p> <p>Is that</p> <pre><code>() </code></pre> <p>A tuple? ( or whatever they call it? ) </p>
5
2009-08-21T19:27:03Z
1,313,925
<p>It is a list of tuples containing one tuple.</p> <p>A tuple is just like a list except that it is immutable, meaning that it can't be changed once it's created. You can't add, remove, or change elements in a tuple. If you want your tuple to be different, you have to create a new tuple with the new data. This may sound like a pain but in reality tuples have many benefits both in code safety and speed.</p>
0
2009-08-21T19:51:41Z
[ "python" ]
What is this construct called in python: ( x, y )
1,313,805
<p>What is this called in python:</p> <pre><code>[('/', MainPage)] </code></pre> <p>Is that an array .. of ... erhm one dictionary? </p> <p>Is that</p> <pre><code>() </code></pre> <p>A tuple? ( or whatever they call it? ) </p>
5
2009-08-21T19:27:03Z
1,315,047
<p>Since no one has answered this bit yet:</p> <blockquote> <p>A tuple? ( or whatever they call it? ) </p> </blockquote> <p>The word "tuple" comes from maths. In maths, we might talk about (ordered) pairs, if we're doing 2d geometry. Moving to three dimensions means we need triples. In higher dimensions, we need quadruples, quintuples, and, uh, whatever the prefix is for six, and so on. This starts to get to be a pain, and mathematicians also love generalising ("let's work in n dimensions today!"), so they started using the term "n-tuple" for an ordered list of n things (usually numbers).</p> <p>After that, a bit of natural laziness is all you need to drop the "n-" and we end up with tuples.</p>
6
2009-08-22T03:32:19Z
[ "python" ]
What is this construct called in python: ( x, y )
1,313,805
<p>What is this called in python:</p> <pre><code>[('/', MainPage)] </code></pre> <p>Is that an array .. of ... erhm one dictionary? </p> <p>Is that</p> <pre><code>() </code></pre> <p>A tuple? ( or whatever they call it? ) </p>
5
2009-08-21T19:27:03Z
1,737,602
<p>It's a <em>list</em> of just one <em>tuple</em>. That tuple has two elements, a string and the object <code>MainPage</code> whatever it is.</p> <p>Both <em>lists</em> and <em>tuples</em> are ordered groups of object, it doesn't matter what kind of object, they can be heterogeneous in both cases.</p> <p>The main difference between lists and tuples is that <strong>tuples are <em>immutable</em></strong>, just like strings.</p> <p>For example we can define a list and a tuple:</p> <pre><code>&gt;&gt;&gt; L = ['a', 1, 5, 'b'] &gt;&gt;&gt; T = ('a', 1, 5, 'b') </code></pre> <p>we can modify elements of L simply by assigning them a new value</p> <pre><code>&gt;&gt;&gt; print L ['a', 1, 5, 'b'] &gt;&gt;&gt; L[1] = 'c' &gt;&gt;&gt; print L ['a', 'c', 5, 'b'] </code></pre> <p>This is not true for tuples</p> <pre><code>&gt;&gt;&gt; print T ('a', 1, 5, 'b') &gt;&gt;&gt; T[1] = 'c' Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'tuple' object does not support item assignment </code></pre> <p>This is because they are immutable. Tuples' elements may be mutable, and you can modify them, for example:</p> <pre><code>&gt;&gt;&gt; T = (3, ['a', 1, 2], 'lol') &gt;&gt;&gt; T[1] ['a', 1, 2] &gt;&gt;&gt; T[1][0] = 'b' &gt;&gt;&gt; T (3, ['b', 1, 2], 'lol') </code></pre> <p>but the list we edited is still the same object, we didn't replaced the tuple's element.</p>
0
2009-11-15T14:07:59Z
[ "python" ]
Raise exception vs. return None in Python functions
1,313,812
<p>What's better practice in a user-defined function in Python: raise an exception or return None? For example, I have a function that finds the most recent file in a folder.</p> <pre><code>def latestpdf(folder): # list the files and sort them try: latest = files[-1] except IndexError: # Folder is empty. return None # One possibility raise FileNotFoundError() # Alternative else: return somefunc(latest) # In my case, somefunc parses the filename </code></pre> <p>Another option is leave the exception and handle it in the caller code, but I figure it's more clear to deal with a FileNotFoundError than an IndexError. Or is it bad form to re-raise an exception with a different name?</p>
44
2009-08-21T19:28:19Z
1,313,837
<p>It's really a matter of semantics. What does <code>foo = latestpdf(d)</code> <em>mean</em>?</p> <p>Is it perfectly reasonable that there's no latest file? Then sure, just return None.</p> <p>Are you expecting to always find a latest file? Raise an exception. And yes, re-raising a more appropriate exception is fine.</p> <p>If this is just a general function that's supposed to apply to any directory, I'd do the former and return None. If the directory is, e.g., meant to be a specific data directory that contains an application's known set of files, I'd raise an exception.</p>
53
2009-08-21T19:34:06Z
[ "python", "exception-handling" ]
Raise exception vs. return None in Python functions
1,313,812
<p>What's better practice in a user-defined function in Python: raise an exception or return None? For example, I have a function that finds the most recent file in a folder.</p> <pre><code>def latestpdf(folder): # list the files and sort them try: latest = files[-1] except IndexError: # Folder is empty. return None # One possibility raise FileNotFoundError() # Alternative else: return somefunc(latest) # In my case, somefunc parses the filename </code></pre> <p>Another option is leave the exception and handle it in the caller code, but I figure it's more clear to deal with a FileNotFoundError than an IndexError. Or is it bad form to re-raise an exception with a different name?</p>
44
2009-08-21T19:28:19Z
1,313,838
<p>In general, I'd say an exception should be thrown if something catastrophic has occured that cannot be recovered from (i.e. your function deals with some internet resource that cannot be connected to), and you should return None if your function should really return something but nothing would be appropriate to return (i.e. "None" if your function tries to match a substring in a string for example).</p>
0
2009-08-21T19:34:15Z
[ "python", "exception-handling" ]
Raise exception vs. return None in Python functions
1,313,812
<p>What's better practice in a user-defined function in Python: raise an exception or return None? For example, I have a function that finds the most recent file in a folder.</p> <pre><code>def latestpdf(folder): # list the files and sort them try: latest = files[-1] except IndexError: # Folder is empty. return None # One possibility raise FileNotFoundError() # Alternative else: return somefunc(latest) # In my case, somefunc parses the filename </code></pre> <p>Another option is leave the exception and handle it in the caller code, but I figure it's more clear to deal with a FileNotFoundError than an IndexError. Or is it bad form to re-raise an exception with a different name?</p>
44
2009-08-21T19:28:19Z
1,313,956
<p>I usually prefer to handle exceptions internally (i.e. try/except inside the called function, possibly returning a None) because python is dynamically typed. In general, I consider it a judgment call one way or the other, but in a dynamically typed language, there are small factors that tip the scales in favor of not passing the exception to the caller:</p> <ol> <li>Anyone calling your function is not notified of the exceptions that can be thrown. It becomes a bit of an art form to know what kind of exception you are hunting for (and generic except blocks ought to be avoided).</li> <li><code>if val is None</code> is a little easier than <code>except ComplicatedCustomExceptionThatHadToBeImportedFromSomeNameSpace</code>. Seriously, I hate having to remember to type <code>from django.core.exceptions import ObjectDoesNotExist</code> at the top of all my django files just to handle a really common use case. In a statically typed world, let the editor do it for you.</li> </ol> <p>Honestly, though, it's always a judgment call, and the situation you're describing, where the called function receives an error it can't help, is an excellent reason to re-raise an exception that is meaningful. You have the exact right idea, but unless you're exception is going to provide more meaningful information in a stack trace than</p> <pre><code>AttributeError: 'NoneType' object has no attribute 'foo' </code></pre> <p>which, nine times out of ten, is what the caller will see if you return an unhandled None, don't bother.</p> <p>(All this kind of makes me wish that python exceptions had the <code>cause</code> attributes by default, as in java, which lets you pass exceptions into new exceptions so that you can rethrow all you want and never lose the original source of the problem.)</p>
2
2009-08-21T19:59:20Z
[ "python", "exception-handling" ]
Raise exception vs. return None in Python functions
1,313,812
<p>What's better practice in a user-defined function in Python: raise an exception or return None? For example, I have a function that finds the most recent file in a folder.</p> <pre><code>def latestpdf(folder): # list the files and sort them try: latest = files[-1] except IndexError: # Folder is empty. return None # One possibility raise FileNotFoundError() # Alternative else: return somefunc(latest) # In my case, somefunc parses the filename </code></pre> <p>Another option is leave the exception and handle it in the caller code, but I figure it's more clear to deal with a FileNotFoundError than an IndexError. Or is it bad form to re-raise an exception with a different name?</p>
44
2009-08-21T19:28:19Z
1,314,026
<p>I would make a couple suggestions before answering your question as it may answer the question for you.</p> <ul> <li>Always name your functions descriptive. <code>latestpdf</code> means very little to anyone but looking over your function <code>latestpdf()</code> gets the latest pdf. I would suggest that you name it <code>getLatestPdfFromFolder(folder)</code>.</li> </ul> <p>As soon as I did this it became clear what it should return.. If there isn't a pdf raise an exception. But wait there more..</p> <ul> <li>Keep the functions clearly defined. Since it's not apparent what somefuc is supposed to do and it's not (apparently) obvious how it relates to getting the latest pdf I would suggest you move it out. This makes the code much more readable.</li> </ul> <p><hr /></p> <pre><code>for folder in folders: try: latest = getLatestPdfFromFolder(folder) results = somefuc(latest) except IOError: pass </code></pre> <p>Hope this helps!</p>
4
2009-08-21T20:20:00Z
[ "python", "exception-handling" ]
If I have the contents of a zipfile in a Python string, can I decompress it without writing it to a file?
1,313,845
<p>I've written some Python code that fetches a zip file from the web and into a string:</p> <pre><code>In [1]: zip_contents[0:5] Out[1]: 'PK\x03\x04\x14' </code></pre> <p>I see there's a zipfile library, but I'm having trouble finding a function in it that I can just pass a bunch of raw zip data. It seems to want to read it from a file.</p> <p>Do I really need to dump this to a temp file, or is there a way around it?</p>
12
2009-08-21T19:35:05Z
1,313,867
<p>Wrap your string in a <a href="http://docs.python.org/library/stringio.html#module-cStringIO">cStringIO</a> object. It looks, acts, and quacks like a file object, but resides in memory.</p>
5
2009-08-21T19:37:29Z
[ "python" ]
If I have the contents of a zipfile in a Python string, can I decompress it without writing it to a file?
1,313,845
<p>I've written some Python code that fetches a zip file from the web and into a string:</p> <pre><code>In [1]: zip_contents[0:5] Out[1]: 'PK\x03\x04\x14' </code></pre> <p>I see there's a zipfile library, but I'm having trouble finding a function in it that I can just pass a bunch of raw zip data. It seems to want to read it from a file.</p> <p>Do I really need to dump this to a temp file, or is there a way around it?</p>
12
2009-08-21T19:35:05Z
1,313,868
<p><code>zipfile.ZipFile</code> accepts any file-like object, so you can use <code>StringIO</code> (2.x) or <code>BytesIO</code> (3.x):</p> <pre><code>try: from cStringIO import StringIO except: from StringIO import StringIO import zipfile fp = StringIO('PK\x03\x04\x14') zfp = zipfile.ZipFile(fp, "r") </code></pre>
23
2009-08-21T19:37:45Z
[ "python" ]
How can Django projects be deployed with minimal installation work?
1,313,989
<p>To deploy a site with Python/Django/MySQL I had to do these on the server (RedHat Linux):</p> <ul> <li>Install MySQLPython</li> <li>Install ModPython</li> <li>Install Django (using <em>python setup.py install</em>)</li> <li>Add some directives on httpd.conf file (or use .htaccess)</li> </ul> <p>But, when I deployed another site with PHP (using CodeIgniter) I had to do nothing. I faced some problems while deploying a Django project on a shared server. Now, my questions are:</p> <ul> <li>Can the deployment process of Django project be made easier?</li> <li>Am I doing too much?</li> <li>Can some of the steps be omitted?</li> <li>What is the best way to deploy django site on a shared server?</li> </ul>
3
2009-08-21T20:11:33Z
1,314,005
<p>You didn't have to do anything when deploying a PHP site because your hosting provider had already installed it. Web hosts which support Django typically install and configure it for you.</p>
1
2009-08-21T20:14:52Z
[ "python", "django" ]
How can Django projects be deployed with minimal installation work?
1,313,989
<p>To deploy a site with Python/Django/MySQL I had to do these on the server (RedHat Linux):</p> <ul> <li>Install MySQLPython</li> <li>Install ModPython</li> <li>Install Django (using <em>python setup.py install</em>)</li> <li>Add some directives on httpd.conf file (or use .htaccess)</li> </ul> <p>But, when I deployed another site with PHP (using CodeIgniter) I had to do nothing. I faced some problems while deploying a Django project on a shared server. Now, my questions are:</p> <ul> <li>Can the deployment process of Django project be made easier?</li> <li>Am I doing too much?</li> <li>Can some of the steps be omitted?</li> <li>What is the best way to deploy django site on a shared server?</li> </ul>
3
2009-08-21T20:11:33Z
1,314,019
<p><strong>Can the deployment process of django project be made easier?</strong></p> <p>No. You can script some of this, if you want. However, you're never going to install MySQL, MySQLPuthon, mod_wsgi (or mod_python), or Django again.</p> <p>You will, however, tweak your application all the time.</p> <p><strong>Am I doing too much?</strong></p> <p>No. Python (and Django) are not part of Apache. PHP is embedded in Apache. PHP is exactly like mod_python (or mod_wsgi). Just one piece of the pie. (Apparently, some hosts handle the PHP installation for you, but don't handle the mod_wsgi or mod_python installation.)</p> <p><strong>Can some of the steps be omitted?</strong></p> <p>No. However, you only do it once.</p> <p><strong>What is the best way to deploy django site on a shared server?</strong></p> <p>You're doing it correctly.</p> <p><strong>When I deployed another site with php (using CodeIgniter) I had to do nothing</strong></p> <p>Certainly an unfair comparison. Apparently, they already installed PHP and the database for you. Nice of them.</p> <p>Also, PHP is not Python. PHP is a plug-in to Apache. Python is "just" a programming language, that requires a separate plug-in to Apache (i.e., mod_python or mod_wsgi).</p> <p>See <a href="http://stackoverflow.com/questions/1311789/how-nicely-does-python-flow-with-html-as-compared-to-php/1311980#1311980">http://stackoverflow.com/questions/1311789/how-nicely-does-python-flow-with-html-as-compared-to-php/1311980#1311980</a></p>
3
2009-08-21T20:18:29Z
[ "python", "django" ]
How can Django projects be deployed with minimal installation work?
1,313,989
<p>To deploy a site with Python/Django/MySQL I had to do these on the server (RedHat Linux):</p> <ul> <li>Install MySQLPython</li> <li>Install ModPython</li> <li>Install Django (using <em>python setup.py install</em>)</li> <li>Add some directives on httpd.conf file (or use .htaccess)</li> </ul> <p>But, when I deployed another site with PHP (using CodeIgniter) I had to do nothing. I faced some problems while deploying a Django project on a shared server. Now, my questions are:</p> <ul> <li>Can the deployment process of Django project be made easier?</li> <li>Am I doing too much?</li> <li>Can some of the steps be omitted?</li> <li>What is the best way to deploy django site on a shared server?</li> </ul>
3
2009-08-21T20:11:33Z
1,314,039
<p>Django hosting support is not as widespread as for PHP, but there are some good options. I can recommend <a href="http://www.webfaction.com/" rel="nofollow">WebFaction</a> - they provide an easy-to-use control panel which offers various combinations of Django versions, Python versions, mod_python, mod_wsgi, MySQL, PostgreSQL etc. They're cost-effective, too. If you use their setup, you get SSH access but just about all of the setting up can be done via their control panel, apart from the actual uploading of your project folder.</p> <p>Disclaimer: apart from being a happy customer I have no other connection with them.</p>
2
2009-08-21T20:23:16Z
[ "python", "django" ]
How can Django projects be deployed with minimal installation work?
1,313,989
<p>To deploy a site with Python/Django/MySQL I had to do these on the server (RedHat Linux):</p> <ul> <li>Install MySQLPython</li> <li>Install ModPython</li> <li>Install Django (using <em>python setup.py install</em>)</li> <li>Add some directives on httpd.conf file (or use .htaccess)</li> </ul> <p>But, when I deployed another site with PHP (using CodeIgniter) I had to do nothing. I faced some problems while deploying a Django project on a shared server. Now, my questions are:</p> <ul> <li>Can the deployment process of Django project be made easier?</li> <li>Am I doing too much?</li> <li>Can some of the steps be omitted?</li> <li>What is the best way to deploy django site on a shared server?</li> </ul>
3
2009-08-21T20:11:33Z
1,314,127
<p>Most shared hosting sites run the LAMP (Linux, Apache, MySQL, PHP) stack so deployment is just a matter of copying some files over. If you were using one of the PHP frameworks like CakePHP or something the service hasn't installed (like an imaging library) you'd be going through extra deployment steps as well.</p> <p>With Django (or Rails, or any other complex framework) you have to set up the stack yourself that one time, then you're good to go.</p> <p>However, you'll also want to think about post-deployment updating. If it's something you're going to do often you may also want to look into <a href="http://www.nongnu.org/fab/" rel="nofollow">Fabric</a> or <a href="http://www.capify.org" rel="nofollow">Capistrano</a> to help automate that.</p> <p>P.S. I'll second that WebFaction recommendation. It's as close to one-button installation as I've seen. Pretty happy customer although I mostly use them for test-sites and prototyping.</p>
0
2009-08-21T20:45:30Z
[ "python", "django" ]
How can Django projects be deployed with minimal installation work?
1,313,989
<p>To deploy a site with Python/Django/MySQL I had to do these on the server (RedHat Linux):</p> <ul> <li>Install MySQLPython</li> <li>Install ModPython</li> <li>Install Django (using <em>python setup.py install</em>)</li> <li>Add some directives on httpd.conf file (or use .htaccess)</li> </ul> <p>But, when I deployed another site with PHP (using CodeIgniter) I had to do nothing. I faced some problems while deploying a Django project on a shared server. Now, my questions are:</p> <ul> <li>Can the deployment process of Django project be made easier?</li> <li>Am I doing too much?</li> <li>Can some of the steps be omitted?</li> <li>What is the best way to deploy django site on a shared server?</li> </ul>
3
2009-08-21T20:11:33Z
1,314,254
<p>You just install this already made <a href="http://www.turnkeylinux.org/appliances/django" rel="nofollow">solution</a> if your allowed to run an image on a virtual machine. I can imagine installations will be done this way in future as complicated security configuration can be done automatically.</p>
1
2009-08-21T21:12:38Z
[ "python", "django" ]
How can Django projects be deployed with minimal installation work?
1,313,989
<p>To deploy a site with Python/Django/MySQL I had to do these on the server (RedHat Linux):</p> <ul> <li>Install MySQLPython</li> <li>Install ModPython</li> <li>Install Django (using <em>python setup.py install</em>)</li> <li>Add some directives on httpd.conf file (or use .htaccess)</li> </ul> <p>But, when I deployed another site with PHP (using CodeIgniter) I had to do nothing. I faced some problems while deploying a Django project on a shared server. Now, my questions are:</p> <ul> <li>Can the deployment process of Django project be made easier?</li> <li>Am I doing too much?</li> <li>Can some of the steps be omitted?</li> <li>What is the best way to deploy django site on a shared server?</li> </ul>
3
2009-08-21T20:11:33Z
1,314,721
<p>You can use Python <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a> and <a href="http://pip.openplans.org/" rel="nofollow">pip</a> (see also "<a href="http://clemesha.org/blog/2009/jul/05/modern-python-hacker-tools-virtualenv-fabric-pip/" rel="nofollow">Tools of the Modern Python Hacker: Virtualenv, Fabric and Pip</a>"). I developed my Django project in the virtual environment. I copy the virtual environment file to the production machine when I deploy my application. I use <code>mod_wsgi</code>. You must write that in the <code>mod_wsig</code> file:</p> <pre><code>import site site.addsitedir('C:\PythonVirtualEnv\IntegralEnv\Lib\site-packages') </code></pre>
0
2009-08-22T00:02:10Z
[ "python", "django" ]
How can Django projects be deployed with minimal installation work?
1,313,989
<p>To deploy a site with Python/Django/MySQL I had to do these on the server (RedHat Linux):</p> <ul> <li>Install MySQLPython</li> <li>Install ModPython</li> <li>Install Django (using <em>python setup.py install</em>)</li> <li>Add some directives on httpd.conf file (or use .htaccess)</li> </ul> <p>But, when I deployed another site with PHP (using CodeIgniter) I had to do nothing. I faced some problems while deploying a Django project on a shared server. Now, my questions are:</p> <ul> <li>Can the deployment process of Django project be made easier?</li> <li>Am I doing too much?</li> <li>Can some of the steps be omitted?</li> <li>What is the best way to deploy django site on a shared server?</li> </ul>
3
2009-08-21T20:11:33Z
1,315,907
<p>To enable easy Django deployement I would to the following:</p> <p><strong>Fisrt-time server configuration</strong></p> <ul> <li>Install <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a> which allow you to run in <em>embedded</em> mode OR in <strong>daemon</strong> mode.</li> <li>Install python and <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a></li> </ul> <p><strong>In your development environment</strong></p> <ul> <li>Use virtualenv. Take a look at <a href="http://code.google.com/p/modwsgi/wiki/VirtualEnvironments" rel="nofollow">mod_wsgi and virtualenv configuration</a></li> <li>Install Django your django version (using python setup.py install)</li> <li>Install your python libs</li> <li>Develop your project</li> </ul> <p><strong>Every time you want to deploy</strong></p> <ul> <li>Copy your virtual environment to the production server</li> <li>Just add an Include directive in your httpd.conf file (or use .htaccess) to your project's apache configuration. As stated in <a href="http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango" rel="nofollow">mod_wsgi integration with django</a> documentation, one example of how Apache included file could be configured would be:</li> </ul> <p><code></p> <pre><code>Alias /media/ /usr/local/django/mysite/media/ &lt;Directory /usr/local/django/mysite/media&gt; Order deny,allow Allow from all &lt;/Directory&gt; WSGIScriptAlias / /usr/local/django/mysite/apache/django.wsgi &lt;Directory /usr/local/django/mysite/apache&gt; Order deny,allow Allow from all &lt;/Directory&gt; </code></pre> <p></code></p> <p><strong>Automating deployement</strong></p> <ul> <li>I would consider using <a href="http://www.nongnu.org/fab/" rel="nofollow">Fabric</a> to automate deployement</li> </ul>
4
2009-08-22T12:46:14Z
[ "python", "django" ]
Using PyUNO on Windows and CentOS
1,314,009
<p>Is there any way to use OpenOffice's <a href="http://wiki.services.openoffice.org/wiki/PyUNO_bridge" rel="nofollow">PyUNO</a> without using the version of Python that comes with OpenOffice? </p> <p>I mean, can I install a package (on Windows and CentOS) that uses the version of Python that's already on the server? </p> <p>I'm trying to use OpenOffice in headless mode so that I can do document conversion with a script (ultimately on a hosted server running CentOS) but my development work is being done on Windows and occassionally the Mac). I'm having nothing but trouble getting this to work.</p>
2
2009-08-21T20:16:34Z
1,316,731
<p>You can't use PyUNO with just any version of Python. You need to use the specific one that's integrated into your OpenOffice installation. However, the very latest OO (3.1 I believe) comes (on all platforms) with the very latest Python (2.6.2 I believe), so if you can upgrade your OpenOffice to the very latest released version on all platforms, you should be just fine.</p>
2
2009-08-22T18:56:42Z
[ "python", "openoffice.org", "uno" ]
How can I scrape this frame?
1,314,052
<p>If you visit <a href="http://cad.chp.ca.gov/iiqr.asp?Center=RDCC&amp;LogNumber=0197D0820&amp;t=Traffic%20Hazard&amp;l=3358%20MYRTLE&amp;b=" rel="nofollow">this link</a> right now, you will probably get a VBScript error.</p> <p>On the other hand, if you visit <a href="http://cad.chp.ca.gov/" rel="nofollow">this link first</a> and <em>then</em> the above link (in the same session), the page comes through.</p> <p>The way this application is set up, the first page is meant to serve as a frame in the second (main) page. If you click around a bit, you'll see how it works.</p> <p>My question: How do I scrape the first page with Python? I've tried everything I can think of -- urllib, urllib2, mechanize -- and all I get is 500 errors or timeouts. </p> <p>I suspect the answers lies with mechanize, but my mechanize-fu isn't good enough to crack this. Can anyone help?</p>
2
2009-08-21T20:28:36Z
1,314,095
<p>You might also try <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> in addition to Mechanize. I'm not positive, but you should be able to parse the DOM down into the framed page.</p> <p>I also find <a href="https://addons.mozilla.org/en-US/firefox/addon/966" rel="nofollow">Tamper Data</a> to be a rather useful plugin when I'm writing scrapers.</p>
1
2009-08-21T20:38:27Z
[ "python", "vbscript", "screen-scraping", "mechanize" ]
How can I scrape this frame?
1,314,052
<p>If you visit <a href="http://cad.chp.ca.gov/iiqr.asp?Center=RDCC&amp;LogNumber=0197D0820&amp;t=Traffic%20Hazard&amp;l=3358%20MYRTLE&amp;b=" rel="nofollow">this link</a> right now, you will probably get a VBScript error.</p> <p>On the other hand, if you visit <a href="http://cad.chp.ca.gov/" rel="nofollow">this link first</a> and <em>then</em> the above link (in the same session), the page comes through.</p> <p>The way this application is set up, the first page is meant to serve as a frame in the second (main) page. If you click around a bit, you'll see how it works.</p> <p>My question: How do I scrape the first page with Python? I've tried everything I can think of -- urllib, urllib2, mechanize -- and all I get is 500 errors or timeouts. </p> <p>I suspect the answers lies with mechanize, but my mechanize-fu isn't good enough to crack this. Can anyone help?</p>
2
2009-08-21T20:28:36Z
1,314,138
<p>It always comes down to the request/response model. You just have to craft a series of http requests such that you get the desired responses. In this case, you also need the server to treat each request as part of the same session. To do that, you need to figure out how the server is tracking sessions. It could be a number of things, from cookies to hidden inputs to form actions, post data, or query strings. If I had to guess I'd put my money on a cookie in this case (I haven't checked the links). If this holds true, you need to send the first request, save the cookie you get back, and then send that cookie along with the 2nd request.</p> <p>It could also be that the initial page will have buttons and links that get you to the second page. Those links will have something like <code>&lt;A href="http://cad.chp.ca.gov/iiqr.asp?Center=RDCC&amp;LogNumber=0197D0820&amp;t=Traffic%20Hazard&amp;l=3358%20MYRTLE&amp;b="&gt;</code> where a lot of the gobbedlygook is generated by the first page.</p> <p>The <code>"Center=RDCC&amp;LogNumber=0197D0820&amp;t=Traffic%20Hazard&amp;l=3358%20MYRTLE&amp;b="</code> part encodes some session information that you must get from the first page.</p> <p>And, of course, you might even need to do both.</p>
8
2009-08-21T20:46:55Z
[ "python", "vbscript", "screen-scraping", "mechanize" ]
Is there any way to get vim to auto wrap python strings at 79 chars?
1,314,174
<p>I found this <a href="http://stackoverflow.com/questions/1302364/python-pep8-printing-wrapped-strings-without-indent/1302381#1302381">answer</a> about wrapping strings using parens extremely useful, but is there a way in Vim to make this happen automatically? I want to be within a string, typing away, and have Vim just put parens around my string and wrap it as necessary. For me, this would be a <em>gigantic</em> time saver as I spend so much time just wrapping long strings manually. Thanks in advance.</p> <p>Example:</p> <ol> <li><p>I type the following text: <pre><code>mylongervarname = "my really long string here so please wrap and quote automatically" </pre></code></p></li> <li><p>Vim automatically does this when I hit column 80 with the string: <pre><code>mylongervarname = ("my really long string here so please wrap and " "quote automatically") </pre></code></p></li> </ol>
32
2009-08-21T20:54:01Z
1,315,419
<p>More a direction than a solution.</p> <p>Use <code>'formatexpr'</code> or <code>'formatprg'</code>. When a line exceeds <code>'textwidth'</code> and passes the criteria set by the <code>'formatoptions'</code> these are used (if set) to break the line. The only real difference is that <code>'formatexpr'</code> is a vimscript expression, while <code>'formatprg'</code> filters the line through an exterior program.</p> <p>So if you know of a formatter that can do this transformation to lines of python code, or are willing to write one, this will give you a hook to have it executed. And since vim supports python (see <code>:help python</code>) you can even write your python formatter in python.</p>
12
2009-08-22T07:46:39Z
[ "python", "vim", "string", "wrapping", "textwrapping" ]
How can I filter items from a list in Python?
1,314,314
<p>I have data naively collected from package dependency lists.</p> <p>Depends: foo bar baz >= 5.2</p> <p>I end up with </p> <pre><code> d = set(['foo','bar','baz','&gt;=','5.2']) </code></pre> <p>I don't want the numerics and the operands.</p> <p>In Perl I would</p> <pre><code>@new = grep {/^[a-z]+$/} @old </code></pre> <p>but I can't find a way to e.g. pass remove() a lambda, or something.</p> <p>The closest I've come is ugly: </p> <pre><code>[ item != None for item in [ re.search("^[a-zA-Z]+$",atom) for atom in d] ] </code></pre> <p>which gets me a map of which values out of the set I want...<em>if</em> the order of the set is repeatable? I know that's not the case in Perl hashes.</p> <p>I know how to iterate. :) I'm trying to do it the pythonesque Right Way</p>
7
2009-08-21T21:27:30Z
1,314,331
<p>How about </p> <pre><code>d = set([item for item in d if re.match("^[a-zA-Z]+$",item)]) </code></pre> <p>that gives you just the values you want, back in d (the order may be different, but that's the price you pay for using sets.</p>
1
2009-08-21T21:31:58Z
[ "python" ]
How can I filter items from a list in Python?
1,314,314
<p>I have data naively collected from package dependency lists.</p> <p>Depends: foo bar baz >= 5.2</p> <p>I end up with </p> <pre><code> d = set(['foo','bar','baz','&gt;=','5.2']) </code></pre> <p>I don't want the numerics and the operands.</p> <p>In Perl I would</p> <pre><code>@new = grep {/^[a-z]+$/} @old </code></pre> <p>but I can't find a way to e.g. pass remove() a lambda, or something.</p> <p>The closest I've come is ugly: </p> <pre><code>[ item != None for item in [ re.search("^[a-zA-Z]+$",atom) for atom in d] ] </code></pre> <p>which gets me a map of which values out of the set I want...<em>if</em> the order of the set is repeatable? I know that's not the case in Perl hashes.</p> <p>I know how to iterate. :) I'm trying to do it the pythonesque Right Way</p>
7
2009-08-21T21:27:30Z
1,314,352
<p>No need for regular expressions here. Use <a href="http://docs.python.org/library/stdtypes.html#str.isalpha"><code>str.isalpha</code></a>. With and without list comprehensions:</p> <pre><code>my_list = ['foo','bar','baz','&gt;=','5.2'] # With only_words = [token for token in my_list if token.isalpha()] # Without only_words = filter(str.isalpha, my_list) </code></pre> <p><em>Personally</em> I don't think you have to use a list comprehension for everything in Python, but I always get frowny-faced when I suggest <code>map</code> or <code>filter</code> answers.</p>
18
2009-08-21T21:40:28Z
[ "python" ]
How to get pyodbc.connect to prompt?
1,314,445
<p>In my C++ programs, I'm used to the connection process prompting for a missing password or letting you select your own connection. Whe I use pyodbc.connect(), an exception is generated instead.</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#41&gt;", line 1, in &lt;module&gt; c=pyodbc.connect('') Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnectW)') </code></pre> <p>The pyodbc documentation for <a href="http://code.google.com/p/pyodbc/wiki/ConnectionStrings" rel="nofollow">Connection Strings</a> states that pyodbc calls the C function <a href="http://msdn.microsoft.com/en-us/library/ms715433(VS.85).aspx" rel="nofollow">SQLDriverConnect</a>. The prompting behavior is controlled by the DriverCompletion parameter, and I can't see a way to set that parameter from Python.</p>
0
2009-08-21T22:14:53Z
1,314,517
<p>I'm not sure if you can, I just checked the source for this and it seems like it always sends SQL_DRIVER_NOPROMPT.</p> <p><a href="http://github.com/mkleehammer/pyodbc/blob/10ac782c60f8aa92c401963ca363d20f03de0a3e/src/connection.cpp#L88" rel="nofollow">See line 88 in connection.cpp</a></p>
2
2009-08-21T22:45:39Z
[ "python", "pyodbc" ]
Is there a LGPL/Apache/BSD Python library for rendering modern HTML and Flash with a transparent background on Windows,Mac,Linux?
1,314,596
<p>I'm looking for a Python library that's suitable, with DOM access too. I don't mind if the flash transparency doesn't carry over. PyQT's license isn't compatible with the project, and PySide isn't compiled cross-platform yet. Any thoughts?</p>
2
2009-08-21T23:19:04Z
1,314,609
<p>Actually, the <a href="http://www.pyside.org/" rel="nofollow">pyside</a> project now provides LGPL 2.1 python bindings for Qt.</p> <p>The first public release was on August 18th. It is being developed with support from Nokia.</p> <p>According to the <a href="http://www.pyside.org/2009/08/pyside-has-been-released/" rel="nofollow">release announcement</a> the bindings are initially focused on Linux/X11 but expect to support all Qt supported platforms eventually.</p>
2
2009-08-21T23:24:23Z
[ "python", "webkit", "widget", "alphablending", "gecko" ]
Python what does it mean "AttributeError: 'unicode' object has no attribute 'has_key' "
1,314,617
<p>I would like to ask what does it mean "AttributeError: 'unicode' object has no attribute 'has_key'" Here is the full stack trace:</p> <pre><code>Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\webapp\__init__.py", line 509, in __call__ handler.post(*groups) File "D:\Projects\workspace\foo\src\homepage.py", line 71, in post country=postedcountry File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 656, in __init__ prop.__set__(self, value) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2712, in __set__ value = self.validate(value) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2742, in validate if value is not None and not value.has_key(): AttributeError: 'unicode' object has no attribute 'has_key' </code></pre> <p>Let me describe a little bit more about the situation:</p> <ul> <li><p>First I created the models.py that has the db.Model for CMSRequest which has an attribute country that reference to the CMSCountry class</p> <pre><code>class CMSRequest(db.Model): country = db.ReferenceProperty(CMSCountry, required=True) class CMSCountry(db.Model): name = db.StringProperty(required=True) </code></pre></li> <li><p>Then, I created a bulkloader class to import the data into the CMSCountry</p></li> <li><p>In the form, user can select the country from the drop down list box, the results are posted back and save to the CMSRequest object</p> <pre><code>def post(self): postedcountry = self.request.get('country') cmsRequest = models.CMSRequest(postedcountry) </code></pre></li> </ul> <p>Maybe I have found the solution to my question, it is because I have not converted the posted key of CMSCountry back to save to the CMSRequest.</p> <p>Thank you everyone! </p>
5
2009-08-21T23:26:54Z
1,314,625
<p>In this line:</p> <pre><code>if value is not None and not value.has_key(): </code></pre> <p><code>value</code> is a unicode string. It looks like the code is expecting it to be a <code>db.Model</code>,</p> <p>(From what I can see, <code>has_key</code> is a method of <code>db.Model</code>, as well as a method of Python dictionaries, but this must be the <code>db.Model</code> one because it's being called with no arguments.)</p> <p>Are you passing a string to a GAE API that expects a <code>db.Model</code>?</p>
6
2009-08-21T23:30:48Z
[ "python", "google-app-engine" ]
Python what does it mean "AttributeError: 'unicode' object has no attribute 'has_key' "
1,314,617
<p>I would like to ask what does it mean "AttributeError: 'unicode' object has no attribute 'has_key'" Here is the full stack trace:</p> <pre><code>Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\webapp\__init__.py", line 509, in __call__ handler.post(*groups) File "D:\Projects\workspace\foo\src\homepage.py", line 71, in post country=postedcountry File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 656, in __init__ prop.__set__(self, value) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2712, in __set__ value = self.validate(value) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2742, in validate if value is not None and not value.has_key(): AttributeError: 'unicode' object has no attribute 'has_key' </code></pre> <p>Let me describe a little bit more about the situation:</p> <ul> <li><p>First I created the models.py that has the db.Model for CMSRequest which has an attribute country that reference to the CMSCountry class</p> <pre><code>class CMSRequest(db.Model): country = db.ReferenceProperty(CMSCountry, required=True) class CMSCountry(db.Model): name = db.StringProperty(required=True) </code></pre></li> <li><p>Then, I created a bulkloader class to import the data into the CMSCountry</p></li> <li><p>In the form, user can select the country from the drop down list box, the results are posted back and save to the CMSRequest object</p> <pre><code>def post(self): postedcountry = self.request.get('country') cmsRequest = models.CMSRequest(postedcountry) </code></pre></li> </ul> <p>Maybe I have found the solution to my question, it is because I have not converted the posted key of CMSCountry back to save to the CMSRequest.</p> <p>Thank you everyone! </p>
5
2009-08-21T23:26:54Z
1,314,634
<p>If you read the traceback, it'll tell you exactly what is going on:</p> <pre><code> if value is not None and not value.has_key(): AttributeError: 'unicode' object has no attribute 'has_key' </code></pre> <p>What this says is the the <code>value</code> variable which you're using doesn't have the <code>has_key</code> attribute. And, what it's telling you is that your <code>value</code> variable isn't a dictionary, as it looks like you're expecting...instead, it's a unicode object, which is basically a string.</p>
1
2009-08-21T23:34:03Z
[ "python", "google-app-engine" ]
Python what does it mean "AttributeError: 'unicode' object has no attribute 'has_key' "
1,314,617
<p>I would like to ask what does it mean "AttributeError: 'unicode' object has no attribute 'has_key'" Here is the full stack trace:</p> <pre><code>Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\webapp\__init__.py", line 509, in __call__ handler.post(*groups) File "D:\Projects\workspace\foo\src\homepage.py", line 71, in post country=postedcountry File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 656, in __init__ prop.__set__(self, value) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2712, in __set__ value = self.validate(value) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2742, in validate if value is not None and not value.has_key(): AttributeError: 'unicode' object has no attribute 'has_key' </code></pre> <p>Let me describe a little bit more about the situation:</p> <ul> <li><p>First I created the models.py that has the db.Model for CMSRequest which has an attribute country that reference to the CMSCountry class</p> <pre><code>class CMSRequest(db.Model): country = db.ReferenceProperty(CMSCountry, required=True) class CMSCountry(db.Model): name = db.StringProperty(required=True) </code></pre></li> <li><p>Then, I created a bulkloader class to import the data into the CMSCountry</p></li> <li><p>In the form, user can select the country from the drop down list box, the results are posted back and save to the CMSRequest object</p> <pre><code>def post(self): postedcountry = self.request.get('country') cmsRequest = models.CMSRequest(postedcountry) </code></pre></li> </ul> <p>Maybe I have found the solution to my question, it is because I have not converted the posted key of CMSCountry back to save to the CMSRequest.</p> <p>Thank you everyone! </p>
5
2009-08-21T23:26:54Z
1,315,050
<p>Note: normally "mapping" types in Python (dictionaries and dictionary like classes ... such as various types of dbm (indexed file) and some DBMS/ORM interfaces ... will implement a <code>has_key()</code> method.</p> <p>Somehow you have gotten a Unicode (string) object into this statement when you were expecting to have some sort of dictionary or other mapping object reference.</p> <p>In general <strong>AttributeError</strong> means that you have tangled up your object bindings (variable assignments). You've given a name to some object other than the type that you intended. (Or sometimes it means you have a typo like ".haskey()" instead of <code>has_key()</code> ... etc).</p> <p>BTW: the use of <code>has_key()</code> is somewhat dated. Normally it's better to test your containers with the Python <strong><code>in</code></strong> operator (which implicitly calls <code>__contains__()</code> --- and which works on lists, strings, and other sequences as well as mapping types).</p> <p>Also <code>value.has_key()</code> would raise an error even if <code>value</code> were a dictionary since the <code>.has_key()</code> method requires an argument.</p> <p>In your code I would either explicitly test for <code>if postedcountry is not None:</code> ... or I'd supply your <code>.get()</code> with an (optional) default for "postedcountry." </p> <p>How do you want to handle the situation where <code>request</code> had no <strong>postedcountry</strong>? Do you want to assume it's being posted from some particular default? Force a redirection to some page that requires the user to supply a value for that form element? Alert the Spanish Inquisition?</p>
2
2009-08-22T03:34:31Z
[ "python", "google-app-engine" ]
Python what does it mean "AttributeError: 'unicode' object has no attribute 'has_key' "
1,314,617
<p>I would like to ask what does it mean "AttributeError: 'unicode' object has no attribute 'has_key'" Here is the full stack trace:</p> <pre><code>Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\webapp\__init__.py", line 509, in __call__ handler.post(*groups) File "D:\Projects\workspace\foo\src\homepage.py", line 71, in post country=postedcountry File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 656, in __init__ prop.__set__(self, value) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2712, in __set__ value = self.validate(value) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2742, in validate if value is not None and not value.has_key(): AttributeError: 'unicode' object has no attribute 'has_key' </code></pre> <p>Let me describe a little bit more about the situation:</p> <ul> <li><p>First I created the models.py that has the db.Model for CMSRequest which has an attribute country that reference to the CMSCountry class</p> <pre><code>class CMSRequest(db.Model): country = db.ReferenceProperty(CMSCountry, required=True) class CMSCountry(db.Model): name = db.StringProperty(required=True) </code></pre></li> <li><p>Then, I created a bulkloader class to import the data into the CMSCountry</p></li> <li><p>In the form, user can select the country from the drop down list box, the results are posted back and save to the CMSRequest object</p> <pre><code>def post(self): postedcountry = self.request.get('country') cmsRequest = models.CMSRequest(postedcountry) </code></pre></li> </ul> <p>Maybe I have found the solution to my question, it is because I have not converted the posted key of CMSCountry back to save to the CMSRequest.</p> <p>Thank you everyone! </p>
5
2009-08-21T23:26:54Z
1,316,202
<p>You're attempting to set a string to a ReferenceProperty. The 'country' field of CMSCountry is a db.ReferenceProperty, which takes a db.Key or a CMSCountry object, but you're attempting to set it to a string.</p> <p>You should be doing something like this:</p> <pre><code>def post(self): postedcountry = self.request.get('country') country = models.CMSCountry.all().filter('name =', postedcountry) if not country: # Couldn't find the country else: cmsRequest = models.CMSRequest(country=country) </code></pre> <p>Please do <a href="http://code.google.com/p/googleappengine/issues/list" rel="nofollow">file a bug</a> about the rather unhelpful error message, though.</p>
1
2009-08-22T15:30:01Z
[ "python", "google-app-engine" ]
Python what does it mean "AttributeError: 'unicode' object has no attribute 'has_key' "
1,314,617
<p>I would like to ask what does it mean "AttributeError: 'unicode' object has no attribute 'has_key'" Here is the full stack trace:</p> <pre><code>Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\webapp\__init__.py", line 509, in __call__ handler.post(*groups) File "D:\Projects\workspace\foo\src\homepage.py", line 71, in post country=postedcountry File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 656, in __init__ prop.__set__(self, value) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2712, in __set__ value = self.validate(value) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2742, in validate if value is not None and not value.has_key(): AttributeError: 'unicode' object has no attribute 'has_key' </code></pre> <p>Let me describe a little bit more about the situation:</p> <ul> <li><p>First I created the models.py that has the db.Model for CMSRequest which has an attribute country that reference to the CMSCountry class</p> <pre><code>class CMSRequest(db.Model): country = db.ReferenceProperty(CMSCountry, required=True) class CMSCountry(db.Model): name = db.StringProperty(required=True) </code></pre></li> <li><p>Then, I created a bulkloader class to import the data into the CMSCountry</p></li> <li><p>In the form, user can select the country from the drop down list box, the results are posted back and save to the CMSRequest object</p> <pre><code>def post(self): postedcountry = self.request.get('country') cmsRequest = models.CMSRequest(postedcountry) </code></pre></li> </ul> <p>Maybe I have found the solution to my question, it is because I have not converted the posted key of CMSCountry back to save to the CMSRequest.</p> <p>Thank you everyone! </p>
5
2009-08-21T23:26:54Z
1,318,908
<p>Your problem is that postedcountry is a string and not a country object. Values retrieved from self.request.get are the string values of variables passed by the browser. </p> <p>You need to look up a country object using some GQL. Exactly how you do that will depend on what exactly the country field of your HTML form is returning , Object Key?, country name?</p> <pre><code>def post(self): postedcountry = self.request.get('country') # &lt;-------- Need to look up a country here !!!!! cmsRequest = models.CMSRequest(country=postedcountry) </code></pre>
3
2009-08-23T16:10:44Z
[ "python", "google-app-engine" ]
Python what does it mean "AttributeError: 'unicode' object has no attribute 'has_key' "
1,314,617
<p>I would like to ask what does it mean "AttributeError: 'unicode' object has no attribute 'has_key'" Here is the full stack trace:</p> <pre><code>Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\webapp\__init__.py", line 509, in __call__ handler.post(*groups) File "D:\Projects\workspace\foo\src\homepage.py", line 71, in post country=postedcountry File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 656, in __init__ prop.__set__(self, value) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2712, in __set__ value = self.validate(value) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\db\__init__.py", line 2742, in validate if value is not None and not value.has_key(): AttributeError: 'unicode' object has no attribute 'has_key' </code></pre> <p>Let me describe a little bit more about the situation:</p> <ul> <li><p>First I created the models.py that has the db.Model for CMSRequest which has an attribute country that reference to the CMSCountry class</p> <pre><code>class CMSRequest(db.Model): country = db.ReferenceProperty(CMSCountry, required=True) class CMSCountry(db.Model): name = db.StringProperty(required=True) </code></pre></li> <li><p>Then, I created a bulkloader class to import the data into the CMSCountry</p></li> <li><p>In the form, user can select the country from the drop down list box, the results are posted back and save to the CMSRequest object</p> <pre><code>def post(self): postedcountry = self.request.get('country') cmsRequest = models.CMSRequest(postedcountry) </code></pre></li> </ul> <p>Maybe I have found the solution to my question, it is because I have not converted the posted key of CMSCountry back to save to the CMSRequest.</p> <p>Thank you everyone! </p>
5
2009-08-21T23:26:54Z
3,891,621
<p>The dictionary object's has_key() method is deprecated in 3.0 - use the "in" expression instead. If you are using the old library in 3.x, you must make code changes to accommodate it.</p>
0
2010-10-08T14:36:55Z
[ "python", "google-app-engine" ]
Cannot connect to server externally using Twisted library in Python
1,315,087
<p>I am trying to get a simple TCP server running on my server. I am using echoserv.py and echoclient.py on the <a href="http://twistedmatrix.com/projects/core/documentation/examples/" rel="nofollow">Twisted examples page</a>. When I run echoserv.py on the server, I can connect fine using the following in echoclient.py:</p> <pre><code>reactor.connectTCP('localhost', 8000, factory) &lt;- for a localhost connection reactor.connectTCP('192.168.0.250', 8000, factory) &lt;- for a lan connection </code></pre> <p>but when I try to connect remotely via the Internet, I use the following line in echoclient.py:</p> <pre><code>reactor.connectTCP('mydomain.com', 8000, factory) </code></pre> <p>However when I try to run echoclient.py, there is a pause, and then I get:</p> <pre><code>connection failed: User timeout caused connection failure. </code></pre> <p>I know it is doing something with my domain, because when I do a random domain, I get:</p> <pre><code>connection failed: Connection was refused by other side: 111: Connection refused. </code></pre> <p>All my ports are configured correctly for port 8000, and I'm sure it's not my ISP blocking the ports (I can use random ports all the time with other applications). I've also tried using ports besides 8000, but no avail. Here is the port fowarding line in my router page if it helps:</p> <pre><code>[X] tcp_server 192.168.0.250 TCP 8000/8000 always edit delete </code></pre> <p>Any idea why this is happening?</p>
1
2009-08-22T04:00:24Z
1,315,106
<p>When you program your router to port-forward outcoming connections to your inbound server, it actually works only if the clients (those who try to connect) are really outside your network, really coming from the cloud. You, from inside your network, can't use it, it won't work for you. You will have the feeling that it is not working, but it is. At least for those outside.</p> <p>Search for <a href="http://www.google.com/search?q=port+forwarding+tester" rel="nofollow">Port Forwarding Tester at Google</a> to take a proof of that. This one (first result of Google) is working pretty fine: <a href="http://www.yougetsignal.com/tools/open-ports/" rel="nofollow">http://www.yougetsignal.com/tools/open-ports/</a></p>
4
2009-08-22T04:12:30Z
[ "python", "tcp", "twisted", "port" ]
Cannot connect to server externally using Twisted library in Python
1,315,087
<p>I am trying to get a simple TCP server running on my server. I am using echoserv.py and echoclient.py on the <a href="http://twistedmatrix.com/projects/core/documentation/examples/" rel="nofollow">Twisted examples page</a>. When I run echoserv.py on the server, I can connect fine using the following in echoclient.py:</p> <pre><code>reactor.connectTCP('localhost', 8000, factory) &lt;- for a localhost connection reactor.connectTCP('192.168.0.250', 8000, factory) &lt;- for a lan connection </code></pre> <p>but when I try to connect remotely via the Internet, I use the following line in echoclient.py:</p> <pre><code>reactor.connectTCP('mydomain.com', 8000, factory) </code></pre> <p>However when I try to run echoclient.py, there is a pause, and then I get:</p> <pre><code>connection failed: User timeout caused connection failure. </code></pre> <p>I know it is doing something with my domain, because when I do a random domain, I get:</p> <pre><code>connection failed: Connection was refused by other side: 111: Connection refused. </code></pre> <p>All my ports are configured correctly for port 8000, and I'm sure it's not my ISP blocking the ports (I can use random ports all the time with other applications). I've also tried using ports besides 8000, but no avail. Here is the port fowarding line in my router page if it helps:</p> <pre><code>[X] tcp_server 192.168.0.250 TCP 8000/8000 always edit delete </code></pre> <p>Any idea why this is happening?</p>
1
2009-08-22T04:00:24Z
1,315,119
<p>Have you tried the following?</p> <ol> <li>Do a port scan on the IP of the machine running the server to confirm that the port is open. A simple [google search][1] will give you plenty of options.</li> <li>If the port is shown to be open, try the remote connection via telnet instead of the twisted client script. Some system firewalls block the application level (such as Windows XP) and could be blocking your outgoing connection without you realizing it.</li> </ol>
1
2009-08-22T04:20:12Z
[ "python", "tcp", "twisted", "port" ]
Efficient way to verify that records are unique in Python/PyTables
1,315,129
<p>I have a table in PyTables with ~50 million records. The combination of two fields (specifically userID and date) should be unique (i.e. a user should have at most one record per day), but I need to verify that this is indeed the case.</p> <p>Illustratively, my table looks like this:</p> <pre><code>userID | date A | 1 A | 2 B | 1 B | 2 B | 2 &lt;- bad! Problem with the data! </code></pre> <p>Additional details:</p> <ul> <li>The table is currently 'mostly' sorted.</li> <li>I can just barely pull one column into memory as a numpy array, but I can't pull two into memory at the same time.</li> <li>Both userID and date are integers</li> </ul>
4
2009-08-22T04:25:39Z
1,316,043
<p>I don't know much about PyTables, but I would try this approach</p> <ol> <li>For each userID, get all <code>(userID, date)</code> pairs</li> <li><code>assert len(rows)==len(set(rows))</code> - this assertion holds true if all <code>(userID, date)</code> tuples contained in the <code>rows</code> list are unique</li> </ol>
0
2009-08-22T14:05:16Z
[ "python" ]
Efficient way to verify that records are unique in Python/PyTables
1,315,129
<p>I have a table in PyTables with ~50 million records. The combination of two fields (specifically userID and date) should be unique (i.e. a user should have at most one record per day), but I need to verify that this is indeed the case.</p> <p>Illustratively, my table looks like this:</p> <pre><code>userID | date A | 1 A | 2 B | 1 B | 2 B | 2 &lt;- bad! Problem with the data! </code></pre> <p>Additional details:</p> <ul> <li>The table is currently 'mostly' sorted.</li> <li>I can just barely pull one column into memory as a numpy array, but I can't pull two into memory at the same time.</li> <li>Both userID and date are integers</li> </ul>
4
2009-08-22T04:25:39Z
1,316,398
<p>It seems that indexes in PyTables are limited to single columns.</p> <p>I would suggest adding a hash column and putting an index on it. Your unique data is defined as the concatenation of other columns in the DB. Separators will ensure that there aren't two different rows that yield the same unique data. The hash column could just be this unique string, but if your data is long you will want to use a hash function. A fast hash function like md5 or sha1 is great for this application.</p> <p>Compute the hashed data and check if it's in the DB. If so, you know you hit some duplicate data. If not, you can safely add it.</p>
3
2009-08-22T16:36:40Z
[ "python" ]
Efficient way to verify that records are unique in Python/PyTables
1,315,129
<p>I have a table in PyTables with ~50 million records. The combination of two fields (specifically userID and date) should be unique (i.e. a user should have at most one record per day), but I need to verify that this is indeed the case.</p> <p>Illustratively, my table looks like this:</p> <pre><code>userID | date A | 1 A | 2 B | 1 B | 2 B | 2 &lt;- bad! Problem with the data! </code></pre> <p>Additional details:</p> <ul> <li>The table is currently 'mostly' sorted.</li> <li>I can just barely pull one column into memory as a numpy array, but I can't pull two into memory at the same time.</li> <li>Both userID and date are integers</li> </ul>
4
2009-08-22T04:25:39Z
11,302,850
<p>So years later I still have the same question, but with the power of indexing and querying this problem is only slightly painful, depending on the size of your table. With the use of readWhere, or getListWhere I think that the problem is approx O(n)</p> <p>Here is what I did... 1. I created a table that had two indicies..you <strong>can</strong> use multiple indicies in PyTables:</p> <p><a href="http://pytables.github.com/usersguide/optimization.html#indexed-searches" rel="nofollow">http://pytables.github.com/usersguide/optimization.html#indexed-searches</a></p> <p>Once your table is <a href="http://pytables.github.com/usersguide/optimization.html#indexed-searches" rel="nofollow">indexed</a>, I also use LZO compression you can do the following:</p> <pre><code>import tables h5f = tables.openFile('filename.h5') tbl = h5f.getNode('/data','data_table') # assumes group data and table data_table counter += 0 for row in tbl: ts = row['date'] # timestamp (ts) or date uid = row['userID'] query = '(date == %d) &amp; (userID == "%s")' % (ts, uid) result = tbl.readWhere(query) if len(result) &gt; 1: # Do something here pass counter += 1 if counter % 1000 == 0: print '%d rows processed' </code></pre> <p>Now the code that I've written here is actually kind of slow. I am sure that there is some PyTables guru out there who could give you a better answer. But here are my thoughts on performance:</p> <p>If you know that you are starting with clean data i.e. (No duplicates) then all you have to do is query the table once for the keys you are interested in finding, which means that you only have to do:</p> <pre><code>ts = row['date'] # timestamp (ts) or date uid = row['userID'] query = '(date == %d) &amp; (userID == "%s")' % (ts, uid) result = tbl.getListWhere(query) if len(result) == 0: # key pair is not in table # do what you were going to do pass elif len(result) &gt; 1: # Do something here, like get a handle to the row and update instead of append. pass </code></pre> <p>If you have lots of time to check for duplicates have create a background process that crawls over the directory with your files and searches for duplicates.</p> <p>I hope that this helps someone else.</p>
1
2012-07-03T00:07:29Z
[ "python" ]
app-engine-patch with pyamf = No module named encoding
1,315,368
<p>I'm trying to use app-engine-patch with pyamf by following this: <a href="http://pyamf.org/wiki/GoogleAppEngine" rel="nofollow">http://pyamf.org/wiki/GoogleAppEngine</a> because I want to migrate my Django &lt;-> pyamf application to app-engine-patch &lt;-> pyamf.</p> <p>What I have now is that I created my gateway.py with only one line of code: </p> <pre><code>import pyamf </code></pre> <p>just to test can I use pyamf and I get blank page when I point my browser to that url/file so that looks good (no import problems and pyamf is found) but in the command prompt where I started server with "manage.py runserver" I see bunch of errors like:</p> <pre><code>... File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2238, in Dispatch self._module_dict) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2156, in ExecuteCGI reset_modules = exec_script(handler_path, cgi_path, hook) File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2052, in ExecuteOrImportScript exec module_code in script_module.__dict__ File "C:\Users\[my app-engine-patch application path]\common\appenginepatch\main.py", line 16, in &lt;module&gt; patch_all() File "C:\Users\[my app-engine-patch application path]\common\appenginepatch\appenginepatcher\patch.py", line 29, in patch_all patch_app_engine() File "C:\Users\[my app-engine-patch application path]\common\appenginepatch\appenginepatcher\patch.py", line 193, in patch_app_engine from django.utils.encoding import force_unicode, smart_str ImportError: No module named encoding </code></pre> <p>Are there any pyamf &lt;-> app-engine-patch gurus out there which can give me a hint what am I doing wrong and how can I setup pyamf to work with app-engine-patch?</p>
0
2009-08-22T07:07:22Z
1,316,754
<p>Are you activating Django 1.0.2 in your app engine startup code? App Engine now comes with it, but also (for backwards compatibility) with 0.9.6, and (still for backwards compatibility) 0.9.6 is what it defaults to -- all it takes to fix this is, at startup, use:</p> <pre><code>from google.appengine.dist import use_library use_library('django', '1.0') </code></pre> <p>and then "Subsequent attempts to import the django package will use Django 1.0.2.". You do need to install 1.0.2 with the SDK separately. See all instructions <a href="http://code.google.com/appengine/docs/python/tools/libraries.html" rel="nofollow">here</a>.</p>
1
2009-08-22T19:04:17Z
[ "python", "google-app-engine", "pyamf", "app-engine-patch" ]
Python, find a file in the same directory
1,315,390
<p>Let's say I have the files a.py and b.txt in the same directory. I can't garuntee <strong>where</strong> that directory is, but I know b.txt will be in the same directory as a.py. a.py needs to access b.txt, how would I go about finding the path to b.txt? Something like "./b.txt" won't work if the user runs the program from a directory other than the one it's saved in.</p>
0
2009-08-22T07:31:50Z
1,315,401
<p>Use the <code>__file__</code> variable:</p> <pre><code>os.path.join(os.path.dirname(__file__), "b.txt") </code></pre>
4
2009-08-22T07:37:05Z
[ "python" ]
Python, find a file in the same directory
1,315,390
<p>Let's say I have the files a.py and b.txt in the same directory. I can't garuntee <strong>where</strong> that directory is, but I know b.txt will be in the same directory as a.py. a.py needs to access b.txt, how would I go about finding the path to b.txt? Something like "./b.txt" won't work if the user runs the program from a directory other than the one it's saved in.</p>
0
2009-08-22T07:31:50Z
1,315,403
<p>If you want the location of the main script, even from code that might be running in an imported module, you need to use <code>sys.argv[0]</code> rather than <code>__file__</code>. (<code>sys.argv[0]</code> is always the path to the main script; see <a href="http://docs.python.org/library/sys.html#sys.argv" rel="nofollow">http://docs.python.org/library/sys.html#sys.argv</a>)</p> <p>If you want the location of the current module, even if it's been imported by some other script, you should use <code>__file__</code> as Martin says.</p> <p>Here's a way to use <code>sys.argv[0]</code>:</p> <pre><code>import os, sys dirname, filename = os.path.split(os.path.abspath(sys.argv[0])) print os.path.join(dirname, "b.txt") </code></pre>
1
2009-08-22T07:38:22Z
[ "python" ]
dictionary of object
1,315,407
<p>I have a sorted dict </p> <p><code> { 1L: '&lt;'New_Config (type: 'String') (id: 1L) (value: 4L) (name: 'account_receivable')'>', 2L: '&lt;'New_Config (type: 'string') (id: 2L) (value: 5L) (name: 'account_payable')'>', 3L: '&lt;'New_Config (type: 'String') (id: 3L) (value: 8L) (name: 'account_cogs ')'>', 4L: '&lt;'New_Config (type: 'String') (id: 4L)(value: 9L)(name: 'account_retained_earning')'>', 5L: '&lt;'New_Config (type: 'String') (id: 5L) (value: 6L) (name: 'account_income')'>' } </code></p> <p>here new_config is object , i have to access object element</p> <p>how can i access the object properties???? suppose i want to access new_config.name</p>
0
2009-08-22T07:40:23Z
1,315,449
<p>Python dictionaries are not sorted. If you have some custom class which implements some mapping methods (like a dictionary) but over-rides some of them to give the appearance of maintaining some (sorted) ordering then the implementation details of that might also explain why your example doesn't look like valid Python.</p> <pre><code>{ 1L: New_Config(...)(...)(...)..., 2L: New_config(...)(...)(...)..., </code></pre> <p>... looks almost sorta like Python. 1L, 2L are representations of large integers (as keys if this were a dictionary). New_Config(...) looks kinda like a <code>repr</code> of something, and the (..) subsequent to that would be like a function call.</p> <p>So, my advice is don't try to post a question from memory or from some vague notion of what you thought you saw. Actually paste in some code.</p> <p>If you actually had objects there then you'd access their attributes using <code>new_config.attribute</code> or possibly (if someone coded up their class to be obnoxious) through some <code>new_config.accessor()</code> method calls (like <code>foo.getThis()</code> and <code>foo.getThat()</code> or something equally inane).</p>
1
2009-08-22T07:59:22Z
[ "python", "dictionary", "sorted" ]
dictionary of object
1,315,407
<p>I have a sorted dict </p> <p><code> { 1L: '&lt;'New_Config (type: 'String') (id: 1L) (value: 4L) (name: 'account_receivable')'>', 2L: '&lt;'New_Config (type: 'string') (id: 2L) (value: 5L) (name: 'account_payable')'>', 3L: '&lt;'New_Config (type: 'String') (id: 3L) (value: 8L) (name: 'account_cogs ')'>', 4L: '&lt;'New_Config (type: 'String') (id: 4L)(value: 9L)(name: 'account_retained_earning')'>', 5L: '&lt;'New_Config (type: 'String') (id: 5L) (value: 6L) (name: 'account_income')'>' } </code></p> <p>here new_config is object , i have to access object element</p> <p>how can i access the object properties???? suppose i want to access new_config.name</p>
0
2009-08-22T07:40:23Z
1,316,728
<pre><code>class Foo(object): def __init__(self,name,weight): self.name = name self.weight = weight &gt;&gt;&gt; D = {} &gt;&gt;&gt; D['1L'] = Foo("James",67) &gt;&gt;&gt; D['2L'] = Foo("Jack",83) &gt;&gt;&gt; D {'2L': &lt;__main__.Foo object at 0x013EB330&gt;, '1L': &lt;__main__.Foo object at 0x00C402D0&gt;} &gt;&gt;&gt; D['1L'].name 'James' </code></pre> <p>In general, </p> <p><strong>DictName[KEY]</strong> gives you <strong>VALUE</strong> for that <strong>KEY</strong>.</p> <p>so to access attribute where <strong>VALUE</strong> is an object you can use</p> <p><strong><code>DictName[KEY].attritbute</code></strong></p>
0
2009-08-22T18:55:48Z
[ "python", "dictionary", "sorted" ]
How can I specify that some command line arguments are mandatory in Python?
1,315,425
<p>I'm writing a program in Python that accepts command line arguments. I am parsing them with <code>getopt</code> (though my choice of <code>getopt</code> is no Catholic marriage. I'm more than willing to use any other library). Is there any way to specify that certain arguments <em>must</em> be given, or do I have to manually make sure that all the arguments were given?</p> <p><strong>Edit:</strong> I changed all instances of <em>option</em> to <em>argument</em> in response to public outcry. Let it not be said that I am not responsive to people who help me :-)</p>
5
2009-08-22T07:49:17Z
1,315,446
<p>The simplest approach would be to do it yourself. I.e.</p> <pre><code>found_f = False try: opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) except getopt.GetoptError, err: print str(err) usage() sys.exit(2) for o, a in opts: if o == '-f': process_f() found_f = True elif ... if not found_f: print "-f was not given" usage() sys.exit(2) </code></pre>
6
2009-08-22T07:57:48Z
[ "python", "command-line" ]
How can I specify that some command line arguments are mandatory in Python?
1,315,425
<p>I'm writing a program in Python that accepts command line arguments. I am parsing them with <code>getopt</code> (though my choice of <code>getopt</code> is no Catholic marriage. I'm more than willing to use any other library). Is there any way to specify that certain arguments <em>must</em> be given, or do I have to manually make sure that all the arguments were given?</p> <p><strong>Edit:</strong> I changed all instances of <em>option</em> to <em>argument</em> in response to public outcry. Let it not be said that I am not responsive to people who help me :-)</p>
5
2009-08-22T07:49:17Z
1,315,462
<p>As for me I prefer using <a href="http://docs.python.org/library/optparse.html">optparse module</a>, it is quite powerful, for exapmle it can automatically generate -h message by given options:</p> <pre><code>from optparse import OptionParser parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") (options, args) = parser.parse_args() </code></pre> <p>You should manually check if all arguments were given:</p> <pre><code>if len(args) != 1: parser.error("incorrect number of arguments") </code></pre> <p>Making options mandatory seems to be quite strange for me - they are called <strong>options</strong> not without any sense...</p>
10
2009-08-22T08:10:24Z
[ "python", "command-line" ]
What do you make of this Python error?
1,315,465
<p>Here's the error.</p> <pre><code>Traceback (most recent call last): File "_ctypes/callbacks.c", line 295, in 'calling callback function' File "USB2.py", line 454, in ff self.drv_locked = False SystemError: Objects/cellobject.c:24: bad argument to internal function </code></pre> <p>Here's the Python code involved.</p> <pre><code>def drv_send(self, data, size): if not self.Connected(): return def f(): self.drv_locked = True buffer = ''.join(chr(c) for c in data[:size]) out_buffer = cast(buffer, POINTER(c_uint8)) request_handle = (OPENUSB_REQUEST_HANDLE * 1)() request = (OPENUSB_INTR_REQUEST * 1)() request_handle[0].dev = self.usbhandle request_handle[0].interface = INTERFACE_ID request_handle[0].endpoint = LIBUSB_ENDPOINT_OUT + 1 request_handle[0].type = USB_TYPE_INTERRUPT request_handle[0].req.intr = request def f(req): print req[0].req.intr[0].result.status, req[0].req.intr[0].result.transferred_bytes self.drv_locked = False # Line 454 request_handle[0].cb = REQUEST_CALLBACK(f) request_handle[0].arg = None request[0].payload = out_buffer request[0].length = size request[0].timeout = 5000 request[0].flags = 0 request[0].next = None r = lib.openusb_xfer_aio(request_handle) print "result", r self.command_queue.put(f) </code></pre> <p>And here's the Python source involved.</p> <pre><code>PyObject * PyCell_Get(PyObject *op) { if (!PyCell_Check(op)) { PyErr_BadInternalCall(); // Line 24 return NULL; } Py_XINCREF(((PyCellObject*)op)-&gt;ob_ref); return PyCell_GET(op); } </code></pre>
2
2009-08-22T08:10:58Z
1,315,500
<p>The <code>PyCell_Check</code> function checks that its argument actually is a cell object (an internal type used to implement variables referenced by multiple scopes). If <code>op</code> is not a cell object, you would get this error.</p> <p>The code you posted does not give enough context/information to determine exactly how the bad parameter came to be passed.</p>
2
2009-08-22T08:32:41Z
[ "python", "ctypes" ]
What do you make of this Python error?
1,315,465
<p>Here's the error.</p> <pre><code>Traceback (most recent call last): File "_ctypes/callbacks.c", line 295, in 'calling callback function' File "USB2.py", line 454, in ff self.drv_locked = False SystemError: Objects/cellobject.c:24: bad argument to internal function </code></pre> <p>Here's the Python code involved.</p> <pre><code>def drv_send(self, data, size): if not self.Connected(): return def f(): self.drv_locked = True buffer = ''.join(chr(c) for c in data[:size]) out_buffer = cast(buffer, POINTER(c_uint8)) request_handle = (OPENUSB_REQUEST_HANDLE * 1)() request = (OPENUSB_INTR_REQUEST * 1)() request_handle[0].dev = self.usbhandle request_handle[0].interface = INTERFACE_ID request_handle[0].endpoint = LIBUSB_ENDPOINT_OUT + 1 request_handle[0].type = USB_TYPE_INTERRUPT request_handle[0].req.intr = request def f(req): print req[0].req.intr[0].result.status, req[0].req.intr[0].result.transferred_bytes self.drv_locked = False # Line 454 request_handle[0].cb = REQUEST_CALLBACK(f) request_handle[0].arg = None request[0].payload = out_buffer request[0].length = size request[0].timeout = 5000 request[0].flags = 0 request[0].next = None r = lib.openusb_xfer_aio(request_handle) print "result", r self.command_queue.put(f) </code></pre> <p>And here's the Python source involved.</p> <pre><code>PyObject * PyCell_Get(PyObject *op) { if (!PyCell_Check(op)) { PyErr_BadInternalCall(); // Line 24 return NULL; } Py_XINCREF(((PyCellObject*)op)-&gt;ob_ref); return PyCell_GET(op); } </code></pre>
2
2009-08-22T08:10:58Z
1,316,789
<p>An internal error is clearly a bug in Python itself, and if you're interested in further exploring this and offering a fix for the Python core, then simplifying your code down to where it still triggers the bug would be the right strategy.</p> <p>If you're more interested in having your code work, rather than in fixing the Python core, then I suggest you avoid some of the several anomalies in your code that might be contributing to confusing Python. For example, I don't know that anybody ever thought to test property for a nested function named <code>f</code> containing yet another further-nested function <strong>also</strong> named <code>f</code> -- it SHOULD work, but it's exactly the kind of thing that might not have been well tested just because nobody thought of it yet, and while deliberately provoking such anomalies is a very good strategy for strenghtening a suite of tests, it might be best avoided if you're not deliberately out to trigger bugs in Python's internals.</p> <p>So, first, I would make sure there's no homonimy around. If that still leaves the bug, I would next remove the use of cell objects by turning what currently are accesses to nonlocal variables into "prebound arguments", for example your "semi-outer" <code>f</code> could be changes to start with:</p> <p><code>def f(self=self):</code></p> <p>and your "fully-inner one" could become:</p> <p><code>def g(req, self=self):</code></p> <p>This would make accesses to <code>self</code> in either of those functions (currently nonlocal variable accesses) into local variable accesses. Yes, you should not have to do this (there should be no bugs in any software, that requires you to work around them), but alas perfection is not a characteristic of this sublunar world, so that learning bug-workaround strategies is an inevitable part of life;-).</p>
5
2009-08-22T19:16:18Z
[ "python", "ctypes" ]
How to migrate packages to a new Python installation?
1,315,511
<p>How can i quickly migrate/copy my python packages that i have installed over time to a new machine?</p> <p>This is my scenario;</p> <p>Am upgrading from an old laptop running python2.5 &amp; Django1.0, to a new laptop which i intend to install python 2.6.2 &amp; Django 1.1. In time i have downloaded and installed many python packages in my old machine(e.f pygame,pyro genshi,py2exe bla bla bla many...), is there an easier way i can copy my packages to the new laptop without running installation file for each individual package?</p> <p>Gath</p>
1
2009-08-22T08:38:39Z
1,315,529
<p>If they're pure Python, then in theory you could just copy them across from one <code>Lib\site-packages</code> directory to the other. However, this will not work for any packages which include C extensions (as these need to be recompiled anew for every Python version). You also need to consider e.g. <code>.pth</code> files which have been created by the installation packages, deleting pre-existing <code>.pyc</code> files etc.</p> <p>I'd advise just reinstalling the packages.</p>
2
2009-08-22T08:49:55Z
[ "python", "migration", "packages" ]
How to migrate packages to a new Python installation?
1,315,511
<p>How can i quickly migrate/copy my python packages that i have installed over time to a new machine?</p> <p>This is my scenario;</p> <p>Am upgrading from an old laptop running python2.5 &amp; Django1.0, to a new laptop which i intend to install python 2.6.2 &amp; Django 1.1. In time i have downloaded and installed many python packages in my old machine(e.f pygame,pyro genshi,py2exe bla bla bla many...), is there an easier way i can copy my packages to the new laptop without running installation file for each individual package?</p> <p>Gath</p>
1
2009-08-22T08:38:39Z
1,315,764
<p>As Vinay says, there are some parts of common installations that can't be just copied over. Also, keep in mind that setup.py scripts can perform arbitrary work, for example, they could test for the version of Python, and change how they install things, or they could write registry entries, or create .rc files, etc. </p> <p>I concur: re-install the packages. The time you save by trying to just copy everything over will be completely lost the first time something mysteriously doesn't work and you try to debug it.</p> <p>Also, another benefit to re-installation: if you only do it when you need the package, then you won't bother reinstalling the packages you no longer need.</p>
1
2009-08-22T11:10:53Z
[ "python", "migration", "packages" ]
How to migrate packages to a new Python installation?
1,315,511
<p>How can i quickly migrate/copy my python packages that i have installed over time to a new machine?</p> <p>This is my scenario;</p> <p>Am upgrading from an old laptop running python2.5 &amp; Django1.0, to a new laptop which i intend to install python 2.6.2 &amp; Django 1.1. In time i have downloaded and installed many python packages in my old machine(e.f pygame,pyro genshi,py2exe bla bla bla many...), is there an easier way i can copy my packages to the new laptop without running installation file for each individual package?</p> <p>Gath</p>
1
2009-08-22T08:38:39Z
1,315,834
<p>Use <a href="http://www.PortablePython.com" rel="nofollow">Portable Python</a> then you can have everything on your USB stick. Your entire development environment always in your pocket, just plug it in in ANY pc and start coding.</p> <p>You can even have multiple versions of Portable Python on same USB stick and run them side by side which helps if you e.g. are busy with transition to Python 3.* or just want to experiment.</p>
0
2009-08-22T11:59:50Z
[ "python", "migration", "packages" ]
How good is startswith?
1,315,559
<p>Is </p> <pre><code>text.startswith('a') </code></pre> <p>better than </p> <pre><code>text[0]=='a' </code></pre> <p>?</p> <p>Knowing text is not empty and we are only interested in the first character of it. </p>
11
2009-08-22T09:02:23Z
1,315,568
<p><code>text[0]</code> fails if <code>text</code> is an empty string:</p> <pre><code>IronPython 2.6 Alpha (2.6.0.1) on .NET 4.0.20506.1 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; text = "" &gt;&gt;&gt; print(text.startswith("a")) False &gt;&gt;&gt; print(text[0]=='a') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IndexError: index out of range: 0 </code></pre> <p>EDIT: You say you "know" that <code>text</code> is not empty... how confident are you of that, and what would you want to happen if it <em>is</em> empty in reality? If a failure is appropriate (e.g. it means a bug in your code) that would encourage the use of <code>text[0]=='a'</code>.</p> <p>Other questions:</p> <ul> <li><p>How concerned are you about the performance of this? If this is performance critical, then benchmark it <em>on your particular Python runtime</em>. I wouldn't be <em>entirely</em> surprised to find that (say) one form was faster on IronPython and a different one faster on CPython.</p></li> <li><p>Which do <em>you</em> (and your team) find more readable?</p></li> </ul>
25
2009-08-22T09:04:25Z
[ "python" ]
How good is startswith?
1,315,559
<p>Is </p> <pre><code>text.startswith('a') </code></pre> <p>better than </p> <pre><code>text[0]=='a' </code></pre> <p>?</p> <p>Knowing text is not empty and we are only interested in the first character of it. </p>
11
2009-08-22T09:02:23Z
1,315,570
<p>Personally I would say <code>startswith</code> is more readable.</p> <p>Also, from Python 2.5 <code>startwith</code> can take a tuple of prefixes to look for:</p> <pre><code>&gt;&gt;&gt; "hello world".startswith(("hello","goodbye")) True </code></pre>
9
2009-08-22T09:05:48Z
[ "python" ]
How good is startswith?
1,315,559
<p>Is </p> <pre><code>text.startswith('a') </code></pre> <p>better than </p> <pre><code>text[0]=='a' </code></pre> <p>?</p> <p>Knowing text is not empty and we are only interested in the first character of it. </p>
11
2009-08-22T09:02:23Z
1,315,577
<p>Yes: it’s easier to use and easier to read. When you are testing for more than one letter, when using slicing, you’ll have to know how long the target text is:</p> <pre><code>haystack = 'Hello, World!' needle = 'Hello' # The easy way result = haystack.startswith(needle) # The slightly harder way result = haystack[:len(needle)] == needle </code></pre> <p><strong>Edit:</strong> The question seems to have changed. It now says, “knowing text is not empty and we are only interested in the first character of it.” That turns it into a fairly meaningless hypothetical situation.</p> <p>I suspect the questioner is trying to “optimize” his/her code for execution speed. If that is the case, my answer is: don’t. Use whichever form is more <em>readable</em> and, therefore, more maintainable when you have to come back and work on it a year from now. Only optimize if profiling shows that line of code to be the bottleneck. This is not some O(n²) algorithm. It’s a string comparison.</p>
10
2009-08-22T09:07:49Z
[ "python" ]
How good is startswith?
1,315,559
<p>Is </p> <pre><code>text.startswith('a') </code></pre> <p>better than </p> <pre><code>text[0]=='a' </code></pre> <p>?</p> <p>Knowing text is not empty and we are only interested in the first character of it. </p>
11
2009-08-22T09:02:23Z
1,315,580
<p>The stock phrase for the questiom is: "Premature optimization is the root of all evil".</p>
7
2009-08-22T09:09:46Z
[ "python" ]
How good is startswith?
1,315,559
<p>Is </p> <pre><code>text.startswith('a') </code></pre> <p>better than </p> <pre><code>text[0]=='a' </code></pre> <p>?</p> <p>Knowing text is not empty and we are only interested in the first character of it. </p>
11
2009-08-22T09:02:23Z
1,315,591
<p>text[0]=='a' is good considering performance. Also you need to add validation when you use this.</p>
1
2009-08-22T09:20:26Z
[ "python" ]
How good is startswith?
1,315,559
<p>Is </p> <pre><code>text.startswith('a') </code></pre> <p>better than </p> <pre><code>text[0]=='a' </code></pre> <p>?</p> <p>Knowing text is not empty and we are only interested in the first character of it. </p>
11
2009-08-22T09:02:23Z
1,315,600
<p><code>text[0]</code> can fail but the equivalent <code>text[:1]</code> is safe if the string is empty.<br></p> <p>If you want to compare more than one characters, I believe <code>.startswith()</code> is better.</p>
4
2009-08-22T09:24:06Z
[ "python" ]
How good is startswith?
1,315,559
<p>Is </p> <pre><code>text.startswith('a') </code></pre> <p>better than </p> <pre><code>text[0]=='a' </code></pre> <p>?</p> <p>Knowing text is not empty and we are only interested in the first character of it. </p>
11
2009-08-22T09:02:23Z
1,316,245
<p>I'd agree with the others that startswith is more readable, and you should use that. That said, if performance is a big issue for such a special case, benchmark it:</p> <pre><code>$ python -m timeit -s 'text="foo"' 'text.startswith("a")' 1000000 loops, best of 3: 0.537 usec per loop $ python -m timeit -s 'text="foo"' 'text[0]=="a"' 1000000 loops, best of 3: 0.22 usec per loop </code></pre> <p>So <code>text[0]</code> is amost 2.5 times as fast - but it's a pretty quick operation; you'd save ~0.3 microseconds per compare depending on the system. Unless you're doing millions of comparisons in a time critical situation though, I'd still go with the more readable startswith.</p>
18
2009-08-22T15:44:09Z
[ "python" ]
How good is startswith?
1,315,559
<p>Is </p> <pre><code>text.startswith('a') </code></pre> <p>better than </p> <pre><code>text[0]=='a' </code></pre> <p>?</p> <p>Knowing text is not empty and we are only interested in the first character of it. </p>
11
2009-08-22T09:02:23Z
1,342,749
<p><a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> explicitly tells to use <code>startswith</code>, because of readability:</p> <blockquote> <pre><code>- Use ''.startswith() and ''.endswith() instead of string </code></pre> <p>slicing to check for prefixes or suffixes.</p> <pre><code> startswith() and endswith() are cleaner and less error prone. For example: Yes: if foo.startswith('bar'): No: if foo[:3] == 'bar': </code></pre> </blockquote>
5
2009-08-27T17:58:00Z
[ "python" ]
How good is startswith?
1,315,559
<p>Is </p> <pre><code>text.startswith('a') </code></pre> <p>better than </p> <pre><code>text[0]=='a' </code></pre> <p>?</p> <p>Knowing text is not empty and we are only interested in the first character of it. </p>
11
2009-08-22T09:02:23Z
18,870,135
<pre><code>def compo2(): n = "abba" for i in range(1000000): n[:1]=="_" </code></pre> <p>is faster than</p> <pre><code>def compo(): n = "abba" for i in range(1000000): n.startswith("_") </code></pre> <p>cProfile reports 0.061 for <code>compo2</code> compared to 0.954 for <code>compo</code> on my machine. This of interest in case you want to make a LOT of prefix checks for various "_mystring". If most strings don't start with underscores then using <code>string[:1]== char</code> before using <code>startswith</code> is an option to optimize your code. In a real application this method saved me about 15% of cpu time.</p>
2
2013-09-18T10:45:50Z
[ "python" ]
Amazon S3 Python Bulk File Transfer through Python
1,315,660
<p>I want to tranfer files in around 1000 directories to an Amazon S3 bucket using Pythons S3 package. How could I do it ?</p>
-2
2009-08-22T09:55:59Z
1,317,690
<p>I like boto,</p> <p><a href="http://code.google.com/p/boto/" rel="nofollow">http://code.google.com/p/boto/</a></p>
4
2009-08-23T03:31:30Z
[ "python", "amazon-s3" ]
Is there an way to programatically read a file from a TrueCrypt disk into memory?
1,315,677
<p>I need to load a file from an umounted TrueCrypt disk into memory. Is there any way to do this programatically? Does TrueCrypt offer an API?</p> <p>The way I believe is best for attempting this would be to mount the volume (prompting the user for a password, of course), open the file, and then unmount the volume. Is there a way to do this all automatically?</p> <p>I am on Windows Vista. I have C#, Python, and Perl readily available.</p>
10
2009-08-22T10:06:06Z
1,315,722
<p>Can you not use the <a href="http://www.truecrypt.org/docs/?s=command-line-usage">true crypt command line</a> from say System.Diagnostics.Process?</p> <pre><code>using System; using System.Diagnostics; namespace Test { class TrueCrypeStart { static void Main(string[] args) { string password = getPassword(...); Process tc= new Process(); tc.StartInfo.FileName = "TrueCrypt.exe"; tc.StartInfo.Arguments = string.Format("/v \"{0}\" /p \"{1}\" /q", ...mount info ..., password); // for quiet! tc.Start(); } } } </code></pre>
12
2009-08-22T10:38:11Z
[ "c#", "python", "perl", "readfile", "truecrypt" ]
Is there an way to programatically read a file from a TrueCrypt disk into memory?
1,315,677
<p>I need to load a file from an umounted TrueCrypt disk into memory. Is there any way to do this programatically? Does TrueCrypt offer an API?</p> <p>The way I believe is best for attempting this would be to mount the volume (prompting the user for a password, of course), open the file, and then unmount the volume. Is there a way to do this all automatically?</p> <p>I am on Windows Vista. I have C#, Python, and Perl readily available.</p>
10
2009-08-22T10:06:06Z
22,404,525
<p><a href="http://iknowu.dnsalias.com/files/public/TrueResize/TrueResize.htm" rel="nofollow">TrueResize</a> includes an open-source C# TrueCrypt library that will allow you to read the encrypted volume (without having to mount it), an additional library includes NTFS support.</p>
0
2014-03-14T12:06:12Z
[ "c#", "python", "perl", "readfile", "truecrypt" ]
when is it necessary to add an `else` clause to a try..except in Python?
1,316,002
<p>When I write code in Python with exception handling I can write code like:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() else: code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>How does this differ from:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>In both cases <code>code_that_needs_to_run_when_there_are_no_exceptions()</code> will execute when there are no exceptions. What's the difference?</p>
4
2009-08-22T13:41:42Z
1,316,008
<p>Actually, in the second snippet, the last line executes always.</p> <p>You probably meant</p> <pre><code>try: some_code_that_can_cause_an_exception() code_that_needs_to_run_when_there_are_no_exceptions() except: some_code_to_handle_exceptions() </code></pre> <p><strike>I believe you can use the <code>else</code> version if it makes the code more readable.</strike> You use the <code>else</code> variant if you don't want to catch exceptions from <code>code_that_needs_to_run_when_there_are_no_exceptions</code>.</p>
6
2009-08-22T13:44:32Z
[ "python", "exception" ]
when is it necessary to add an `else` clause to a try..except in Python?
1,316,002
<p>When I write code in Python with exception handling I can write code like:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() else: code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>How does this differ from:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>In both cases <code>code_that_needs_to_run_when_there_are_no_exceptions()</code> will execute when there are no exceptions. What's the difference?</p>
4
2009-08-22T13:41:42Z
1,316,011
<p>In the second example, <code>code_that_needs_to_run_when_there_are_no_exceptions()</code> will be ran when you <strong>do</strong> have an exception and then you handle it, continuing after the except.</p> <p>so ...</p> <p>In both cases code_that_needs_to_run_when_there_are_no_exceptions() will execute when there are no exceptions, but in the latter will execute when there are and are not exceptions.</p> <p>Try this on your CLI</p> <pre><code>#!/usr/bin/python def throws_ex( raise_it=True ): if raise_it: raise Exception("Handle me") def do_more(): print "doing more\n" if __name__ == "__main__": print "Example 1\n" try: throws_ex() except Exception, e: # Handle it print "Handling Exception\n" else: print "No Exceptions\n" do_more() print "example 2\n" try: throws_ex() except Exception, e: print "Handling Exception\n" do_more() print "example 3\n" try: throws_ex(False) except Exception, e: print "Handling Exception\n" else: do_more() print "example 4\n" try: throws_ex(False) except Exception, e: print "Handling Exception\n" do_more() </code></pre> <p>It will output</p> <blockquote> <p>Example 1</p> <p>Handling Exception</p> <p>example 2</p> <p>Handling Exception</p> <p>doing more</p> <p>example 3</p> <p>doing more</p> <p>example 4</p> <p>doing more</p> </blockquote> <p>You get the idea, <strong>play around</strong> with exceptions, bubbling and other things! Crack out the command-line and VIM!</p>
9
2009-08-22T13:46:00Z
[ "python", "exception" ]
when is it necessary to add an `else` clause to a try..except in Python?
1,316,002
<p>When I write code in Python with exception handling I can write code like:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() else: code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>How does this differ from:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>In both cases <code>code_that_needs_to_run_when_there_are_no_exceptions()</code> will execute when there are no exceptions. What's the difference?</p>
4
2009-08-22T13:41:42Z
1,316,037
<p>According to the <a href="http://docs.python.org/reference/compound%5Fstmts.html" rel="nofollow">docs</a>...</p> <p><em>"The optional else clause is executed if and when control flows off the end of the try clause.7.2 Exceptions in the else clause are not handled by the preceding except clauses."</em></p> <p>So look at this basic example as your answer</p> <pre><code>try: print("Try with Exception") print(sys.path) except NameError: print "Exception" else: print "Else" print("Out of try/except block") try: print("Try without Exception") except NameError: print "Exception" else: print "Else is now executed" print("Out of try/except finally") </code></pre> <p>See how the else got executed when the exception didn't occur. </p>
1
2009-08-22T13:58:26Z
[ "python", "exception" ]
when is it necessary to add an `else` clause to a try..except in Python?
1,316,002
<p>When I write code in Python with exception handling I can write code like:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() else: code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>How does this differ from:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>In both cases <code>code_that_needs_to_run_when_there_are_no_exceptions()</code> will execute when there are no exceptions. What's the difference?</p>
4
2009-08-22T13:41:42Z
1,316,041
<p>Example 1:</p> <pre><code>try: a() b() except: c() </code></pre> <p>Here, <code>b()</code> will only be run if <code>a()</code> didn't throw, but the except block will also catch any exceptions that may be <em>thrown by <code>b()</code></em>, which you might not want. A general rule is: only catch exceptions that you know might happen (and have a way of handling). Therefore, if you don't know whether <code>b()</code> will throw, or if you can't do anything useful by catching an exception thrown by <code>b()</code>, then <em>don't put <code>b()</code> in the <code>try:</code> block</em>.</p> <p>Example 2:</p> <pre><code>try: a() except: c() else: b() </code></pre> <p>Here, <code>b()</code> will only be run if <code>a()</code> didn't throw, but any exceptions that <code>b()</code> throws will not be caught here and will continue to propagate up the stack. This is very often what you want.</p> <p>Example 3:</p> <pre><code>try: a() except: c() b() </code></pre> <p>Here, <code>b()</code> is always run, even if <code>a()</code> didn't throw anything. This is also quite commonly useful, of course.</p>
5
2009-08-22T14:01:30Z
[ "python", "exception" ]
when is it necessary to add an `else` clause to a try..except in Python?
1,316,002
<p>When I write code in Python with exception handling I can write code like:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() else: code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>How does this differ from:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>In both cases <code>code_that_needs_to_run_when_there_are_no_exceptions()</code> will execute when there are no exceptions. What's the difference?</p>
4
2009-08-22T13:41:42Z
1,316,046
<p>You had the original code almost right. Here's the full treatment:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() else: code_that_needs_to_run_when_there_are_no_exceptions() code_that_runs_whether_there_was_an_exception_or_not() </code></pre>
4
2009-08-22T14:06:08Z
[ "python", "exception" ]
when is it necessary to add an `else` clause to a try..except in Python?
1,316,002
<p>When I write code in Python with exception handling I can write code like:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() else: code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>How does this differ from:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>In both cases <code>code_that_needs_to_run_when_there_are_no_exceptions()</code> will execute when there are no exceptions. What's the difference?</p>
4
2009-08-22T13:41:42Z
1,316,062
<p>I haven't been using Python for all that long, but I try to handle specific exceptions in a <code>try</code> block, and use <code>else</code> to handle the "other" exceptions I might not have expected, similar to a <code>default</code> block in C/C++ <code>switch</code> blocks. Is that an appropriate use for <code>else</code> as well?</p>
0
2009-08-22T14:14:45Z
[ "python", "exception" ]
when is it necessary to add an `else` clause to a try..except in Python?
1,316,002
<p>When I write code in Python with exception handling I can write code like:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() else: code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>How does this differ from:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>In both cases <code>code_that_needs_to_run_when_there_are_no_exceptions()</code> will execute when there are no exceptions. What's the difference?</p>
4
2009-08-22T13:41:42Z
1,319,426
<p>I use try:..except:..else: a lot!</p> <p>This is the pattern: try..except should span just one line of code where I anticipate an exception. Then except does the fallback/default handling, and else: does the thing I really wanted to do (no exceptions => go on to make what I wanted).</p> <p>A simple example:</p> <pre><code> # Exhibit 1 data_paths = [] try: from . import version_subst except ImportError: first_datadir = "./data" else: first_datadir = os.path.join(version_subst.DATADIR, PACKAGE_NAME) # Exhibit 2 for attr in attrs: try: obj = getattr(plugin, attr) except AttributeError, e: if warn: pretty.print_info(__name__, "Plugin %s: %s" % (plugin_name, e)) yield None else: yield obj </code></pre>
1
2009-08-23T20:08:10Z
[ "python", "exception" ]
when is it necessary to add an `else` clause to a try..except in Python?
1,316,002
<p>When I write code in Python with exception handling I can write code like:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() else: code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>How does this differ from:</p> <pre><code>try: some_code_that_can_cause_an_exception() except: some_code_to_handle_exceptions() code_that_needs_to_run_when_there_are_no_exceptions() </code></pre> <p>In both cases <code>code_that_needs_to_run_when_there_are_no_exceptions()</code> will execute when there are no exceptions. What's the difference?</p>
4
2009-08-22T13:41:42Z
22,579,805
<p>While Ned Batchelder's response is appropriate for the OP, I'd like to slightly build upon it. Also, I can't reply as a comment to Mk12's comment (since I "only" have 49 rep, not 50, go figure). So my mite of contribution:</p> <pre><code>try: code_that_can_cause_an_exception() except ParticularException: code_to_handle_the_particular_exception() except: code_to_handle_all_other_exceptions() else: code_to_run_when_there_are_no_exceptions_and_which_should_not_be_run_after_except_clauses() finally: code_to_run_whether_there_was_an_exception_or_not_even_if_the_program_will_exit_from_the_try_block() code_to_run_whether_there_was_an_exception_or_not_if_execution_reaches_here() </code></pre>
1
2014-03-22T15:47:22Z
[ "python", "exception" ]
Pythonic way of iterating over 3D array
1,316,068
<p>I have a 3D array in Python and I need to iterate over all the cubes in the array. That is, for all <code>(x,y,z)</code> in the array's dimensions I need to access the cube:</p> <pre><code>array[(x + 0, y + 0, z + 0)] array[(x + 1, y + 0, z + 0)] array[(x + 0, y + 1, z + 0)] array[(x + 1, y + 1, z + 0)] array[(x + 0, y + 0, z + 1)] array[(x + 1, y + 0, z + 1)] array[(x + 0, y + 1, z + 1)] array[(x + 1, y + 1, z + 1)] </code></pre> <p>The array is a Numpy array, though that's not really necessary. I just found it very easy to read the data in with a one-liner using <code>numpy.fromfile()</code>.</p> <p>Is there any more Pythonic way to iterate over these than the following? That simply looks like C using Python syntax.</p> <pre><code>for x in range(x_dimension): for y in range(y_dimension): for z in range(z_dimension): work_with_cube(array[(x + 0, y + 0, z + 0)], array[(x + 1, y + 0, z + 0)], array[(x + 0, y + 1, z + 0)], array[(x + 1, y + 1, z + 0)], array[(x + 0, y + 0, z + 1)], array[(x + 1, y + 0, z + 1)], array[(x + 0, y + 1, z + 1)], array[(x + 1, y + 1, z + 1)]) </code></pre>
5
2009-08-22T14:16:04Z
1,316,087
<pre><code>import itertools for x, y, z in itertools.product(xrange(x_size), xrange(y_size), xrange(z_size)): work_with_cube(array[x, y, z]) </code></pre>
7
2009-08-22T14:29:59Z
[ "python", "arrays", "loops" ]
Pythonic way of iterating over 3D array
1,316,068
<p>I have a 3D array in Python and I need to iterate over all the cubes in the array. That is, for all <code>(x,y,z)</code> in the array's dimensions I need to access the cube:</p> <pre><code>array[(x + 0, y + 0, z + 0)] array[(x + 1, y + 0, z + 0)] array[(x + 0, y + 1, z + 0)] array[(x + 1, y + 1, z + 0)] array[(x + 0, y + 0, z + 1)] array[(x + 1, y + 0, z + 1)] array[(x + 0, y + 1, z + 1)] array[(x + 1, y + 1, z + 1)] </code></pre> <p>The array is a Numpy array, though that's not really necessary. I just found it very easy to read the data in with a one-liner using <code>numpy.fromfile()</code>.</p> <p>Is there any more Pythonic way to iterate over these than the following? That simply looks like C using Python syntax.</p> <pre><code>for x in range(x_dimension): for y in range(y_dimension): for z in range(z_dimension): work_with_cube(array[(x + 0, y + 0, z + 0)], array[(x + 1, y + 0, z + 0)], array[(x + 0, y + 1, z + 0)], array[(x + 1, y + 1, z + 0)], array[(x + 0, y + 0, z + 1)], array[(x + 1, y + 0, z + 1)], array[(x + 0, y + 1, z + 1)], array[(x + 1, y + 1, z + 1)]) </code></pre>
5
2009-08-22T14:16:04Z
1,316,104
<p>Have a look at <a href="http://docs.python.org/library/itertools.html">itertools</a>, especially <a href="http://docs.python.org/library/itertools.html#itertools.product">itertools.product</a>. You can compress the three loops into one with </p> <pre><code>import itertools for x, y, z in itertools.product(*map(xrange, (x_dim, y_dim, z_dim)): ... </code></pre> <p>You can also create the cube this way:</p> <pre><code>cube = numpy.array(list(itertools.product((0,1), (0,1), (0,1)))) print cube array([[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]) </code></pre> <p>and add the offsets by a simple addition</p> <pre><code>print cube + (10,100,1000) array([[ 10, 100, 1000], [ 10, 100, 1001], [ 10, 101, 1000], [ 10, 101, 1001], [ 11, 100, 1000], [ 11, 100, 1001], [ 11, 101, 1000], [ 11, 101, 1001]]) </code></pre> <p>which would to translate to <code>cube + (x,y,z)</code> in your case. The very compact version of your code would be </p> <pre><code>import itertools, numpy cube = numpy.array(list(itertools.product((0,1), (0,1), (0,1)))) x_dim = y_dim = z_dim = 10 for offset in itertools.product(*map(xrange, (x_dim, y_dim, z_dim))): work_with_cube(cube+offset) </code></pre> <p><strong>Edit</strong>: <code>itertools.product</code> makes the product over the different arguments, i.e. <code>itertools.product(a,b,c)</code>, so I have to pass <code>map(xrange, ...)</code> with as <code>*map(...)</code></p>
13
2009-08-22T14:38:12Z
[ "python", "arrays", "loops" ]
Transforming nested list in Python
1,316,319
<p>Assuming I have a structure like this:</p> <pre><code>a = [ ('A', ['D', 'E', 'F', 'G']), ('B', ['H']), ('C', ['I']) ] </code></pre> <p>How can I transform it into:</p> <pre><code>a = [ ('A', 'D'), ('A', 'E'), ('A', 'F'), ('A', 'G'), ('B', 'H'), ('C', 'I'), ] </code></pre> <p>Thanks for your time!</p>
0
2009-08-22T16:14:36Z
1,316,335
<p>Here's a simple solution:</p> <pre><code>data = [ ('A', ['D', 'E', 'F', 'G']), ('B', ['H']), ('C', ['I']) ] result = [] for x in data: for y in x[1]: result.append((x[0], y)) </code></pre>
4
2009-08-22T16:19:09Z
[ "python" ]
Transforming nested list in Python
1,316,319
<p>Assuming I have a structure like this:</p> <pre><code>a = [ ('A', ['D', 'E', 'F', 'G']), ('B', ['H']), ('C', ['I']) ] </code></pre> <p>How can I transform it into:</p> <pre><code>a = [ ('A', 'D'), ('A', 'E'), ('A', 'F'), ('A', 'G'), ('B', 'H'), ('C', 'I'), ] </code></pre> <p>Thanks for your time!</p>
0
2009-08-22T16:14:36Z
1,316,339
<p>Try:</p> <pre><code>&gt;&gt;&gt; a = [('A', ['D', 'E', 'F', 'G']), ('B', ['H']), ('C', ['I'])] &gt;&gt;&gt; [(k,j) for k, more in a for j in more] [('A', 'D'), ('A', 'E'), ('A', 'F'), ('A', 'G'), ('B', 'H'), ('C', 'I')] </code></pre> <p>This handles only one level of nesting of course.</p>
10
2009-08-22T16:19:33Z
[ "python" ]
Transforming nested list in Python
1,316,319
<p>Assuming I have a structure like this:</p> <pre><code>a = [ ('A', ['D', 'E', 'F', 'G']), ('B', ['H']), ('C', ['I']) ] </code></pre> <p>How can I transform it into:</p> <pre><code>a = [ ('A', 'D'), ('A', 'E'), ('A', 'F'), ('A', 'G'), ('B', 'H'), ('C', 'I'), ] </code></pre> <p>Thanks for your time!</p>
0
2009-08-22T16:14:36Z
1,317,634
<p>(Side comment) Why on earth did you indent like that? Isn't the following more readable?</p> <pre><code>a = [ ('A', ['D', 'E', 'F', 'G']), ('B', ['H']), ('C', ['I']) ] </code></pre>
1
2009-08-23T02:49:09Z
[ "python" ]
pylint not recognizing some of the standard library
1,316,334
<p>I'm using pylint + pydev, with python 2.6. I have a module with just this line of code</p> <pre><code>from email import Message </code></pre> <p>Now when I try to run this module it runs fine. But pylint reports an error:</p> <pre><code>ID: E0611 No name 'Message' in module 'email' </code></pre> <p>Although it exists... Any idea why?</p>
9
2009-08-22T16:19:08Z
1,316,351
<p>The <code>email</code> module uses some horrible import hackery, which has bitten me in the past. You can do this:</p> <pre><code>&gt;&gt;&gt; from email import Message </code></pre> <p>but you can't do this:</p> <pre><code>&gt;&gt;&gt; import email &gt;&gt;&gt; email.Message Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? AttributeError: 'module' object has no attribute 'Message' </code></pre> <p>I realise that's not very helpful for making pylint work, but it might help to explain the problem.</p>
1
2009-08-22T16:23:25Z
[ "python", "email", "import", "pydev", "pylint" ]
pylint not recognizing some of the standard library
1,316,334
<p>I'm using pylint + pydev, with python 2.6. I have a module with just this line of code</p> <pre><code>from email import Message </code></pre> <p>Now when I try to run this module it runs fine. But pylint reports an error:</p> <pre><code>ID: E0611 No name 'Message' in module 'email' </code></pre> <p>Although it exists... Any idea why?</p>
9
2009-08-22T16:19:08Z
1,316,693
<p>I like pylint, but I do find I have to use a lot of <code># pylint: disable-msg=E0611</code> and the like to make it shut up in cases that are perfectly correct but confuse it (for example, like in this case, due to <code>email</code>'s playing with import tricks).</p>
9
2009-08-22T18:40:45Z
[ "python", "email", "import", "pydev", "pylint" ]