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 |
|---|---|---|---|---|---|---|---|---|---|
keyerror inside django model class __init__ | 866,399 | <p>Here's a Django model class I wrote. This class gets a keyerror when I call <code>get_object_or_404</code> from Django (I conceive that keyerror is raised due to no kwargs being passed to <code>__init__</code> by the get function, arguments are all positional). Interestingly, it does not get an error when I call <co... | 1 | 2009-05-14T23:35:13Z | 866,456 | <pre><code>self.user = kwargs['user'].pop()
self.event_type = kwargs['event_type'].pop()
</code></pre>
<p>You're trying to retrieve an entry from the dictionary, and then call its pop method. If you want to remove and return an object from a dictionary, call <code>dict.pop()</code>:</p>
<pre><code>self.user = kwargs.... | 7 | 2009-05-14T23:58:34Z | [
"python",
"django",
"django-models"
] |
keyerror inside django model class __init__ | 866,399 | <p>Here's a Django model class I wrote. This class gets a keyerror when I call <code>get_object_or_404</code> from Django (I conceive that keyerror is raised due to no kwargs being passed to <code>__init__</code> by the get function, arguments are all positional). Interestingly, it does not get an error when I call <co... | 1 | 2009-05-14T23:35:13Z | 866,662 | <p>There's no reason to write your own <code>__init__</code> for Django model classes. I think you'll be a lot happier without it. </p>
<p>Almost anything you think you want to do in <code>__init__</code> can be better done in <code>save</code>.</p>
| 2 | 2009-05-15T01:31:40Z | [
"python",
"django",
"django-models"
] |
keyerror inside django model class __init__ | 866,399 | <p>Here's a Django model class I wrote. This class gets a keyerror when I call <code>get_object_or_404</code> from Django (I conceive that keyerror is raised due to no kwargs being passed to <code>__init__</code> by the get function, arguments are all positional). Interestingly, it does not get an error when I call <co... | 1 | 2009-05-14T23:35:13Z | 866,665 | <blockquote>
<p>wonder why, and if the below code is the correct way (ie, using <code>__init__</code> to populate the link field) to construct this class.</p>
</blockquote>
<p>I once got some problems when I tried to overload <code>__init__</code>
In the maillist i got this answer</p>
<blockquote>
<p>It's best no... | 1 | 2009-05-15T01:35:20Z | [
"python",
"django",
"django-models"
] |
keyerror inside django model class __init__ | 866,399 | <p>Here's a Django model class I wrote. This class gets a keyerror when I call <code>get_object_or_404</code> from Django (I conceive that keyerror is raised due to no kwargs being passed to <code>__init__</code> by the get function, arguments are all positional). Interestingly, it does not get an error when I call <co... | 1 | 2009-05-14T23:35:13Z | 867,254 | <p>I don't think you need the <code>__init__</code> here at all. </p>
<p>You are always calculating the value of link when the class is instantiated. This means you ignore whatever is stored in the database. Since this is the case, why bother with a model field at all? You would be better making link a property, with ... | 2 | 2009-05-15T06:29:39Z | [
"python",
"django",
"django-models"
] |
In Django, how can you change the User class to work with a different db table? | 866,418 | <p>We're running django alongside - and sharing a database with - an existing application. And we want to use an existing "user" table (not Django's own) to store user information. </p>
<p>It looks like it's possible to change the name of the table that Django uses, in the Meta class of the User definition. </p>
<p>B... | 1 | 2009-05-14T23:41:46Z | 866,434 | <p>You might find it useful to set up your old table as an <a href="http://docs.djangoproject.com/en/dev/topics/auth/#other-authentication-sources" rel="nofollow">alternative authentication source</a> and sidestep all these issues. </p>
<p>Another option is to <a href="http://docs.djangoproject.com/en/dev/topics/auth/... | 6 | 2009-05-14T23:50:16Z | [
"python",
"django",
"django-models",
"monkeypatching"
] |
Creating a new terminal/shell window to simply display text | 866,737 | <p>I want to pipe [edit: real-time text] the output of several subprocesses (sometimes chained, sometimes parallel) to a single terminal/tty window that is not the active python shell (be it an IDE, command-line, or a running script using tkinter). IPython is not an option. I need something that comes with the standard... | 1 | 2009-05-15T02:16:21Z | 866,750 | <p>You say "pipe" so I assume you're dealing with text output from the subprocesses. A simple solution may be to just write output to files?</p>
<p>e.g. in the subprocess:</p>
<ol>
<li>Redirect output <code>%TEMP%\output.txt</code></li>
<li>On exit, copy <code>output.txt</code> to a directory your main process is wa... | 0 | 2009-05-15T02:27:00Z | [
"python",
"shell"
] |
Creating a new terminal/shell window to simply display text | 866,737 | <p>I want to pipe [edit: real-time text] the output of several subprocesses (sometimes chained, sometimes parallel) to a single terminal/tty window that is not the active python shell (be it an IDE, command-line, or a running script using tkinter). IPython is not an option. I need something that comes with the standard... | 1 | 2009-05-15T02:16:21Z | 866,805 | <p>A good solution in Unix would be named pipes. I know you asked about Windows, but there might be a similar approach in Windows, or this might be helpful for someone else.</p>
<p>on terminal 1:</p>
<pre><code>mkfifo /tmp/display_data
myapp >> /tmp/display_data
</code></pre>
<p>on terminal 2 (bash):</p>
<pr... | 2 | 2009-05-15T03:01:20Z | [
"python",
"shell"
] |
Creating a new terminal/shell window to simply display text | 866,737 | <p>I want to pipe [edit: real-time text] the output of several subprocesses (sometimes chained, sometimes parallel) to a single terminal/tty window that is not the active python shell (be it an IDE, command-line, or a running script using tkinter). IPython is not an option. I need something that comes with the standard... | 1 | 2009-05-15T02:16:21Z | 872,075 | <p>You could make a producer-customer system, where lines are inserted over a socket (nothing fancy here).
The customer would be a multithreaded socket server listening to connections and putting all lines into a <strong><a href="http://docs.python.org/library/queue.html" rel="nofollow">Queue</a></strong>. In the separ... | 0 | 2009-05-16T09:40:15Z | [
"python",
"shell"
] |
Can I segment a document in BeautifulSoup before converting it to text based on my analysis of the document? | 866,772 | <p>I have some html files that I want to convert to text. I have played around with BeautifulSoup and made some progress on understanding how to use the instructions and can submit html and get back text. </p>
<p>However, my files have a lot of text that is formatted using table structures. For example I might have... | 0 | 2009-05-15T02:40:42Z | 871,736 | <p>Man I love this stuff
Assuming in a naive case that I want to delete all of the tables that have any rows with a column length greater than 3 My answer is </p>
<pre><code>for table in soup.findAll('table'):
rows=[]
for row in table.findAll('tr'):
columns=0
for column in row.findAll('td'):
... | 0 | 2009-05-16T05:00:33Z | [
"python",
"beautifulsoup"
] |
python instance variables as optional arguments | 867,115 | <p>In python, is there a way I can use instance variables as optional arguments in a class method? ie:</p>
<pre><code>def function(self, arg1=val1, arg2=val2, arg3=self.instance_var):
# do stuff....
</code></pre>
<p>Any help would be appreciated.</p>
| 7 | 2009-05-15T05:40:57Z | 867,124 | <p>Try this:</p>
<pre><code>def foo(self, blah=None):
if blah is None: # faster than blah == None - thanks to kcwu
blah = self.instance_var
</code></pre>
| 14 | 2009-05-15T05:45:31Z | [
"python",
"function",
"class"
] |
python instance variables as optional arguments | 867,115 | <p>In python, is there a way I can use instance variables as optional arguments in a class method? ie:</p>
<pre><code>def function(self, arg1=val1, arg2=val2, arg3=self.instance_var):
# do stuff....
</code></pre>
<p>Any help would be appreciated.</p>
| 7 | 2009-05-15T05:40:57Z | 867,129 | <p>no, because the instance doesn't exist when class function definition time</p>
<p>You have to rewrite as following</p>
<pre><code>def function(self, arg1=val1, arg2=val2, arg3=None):
if arg3 is None:
arg3 = self.instance_var
</code></pre>
<p>This is slightly different to original one: you cannot pass ... | 2 | 2009-05-15T05:47:33Z | [
"python",
"function",
"class"
] |
python instance variables as optional arguments | 867,115 | <p>In python, is there a way I can use instance variables as optional arguments in a class method? ie:</p>
<pre><code>def function(self, arg1=val1, arg2=val2, arg3=self.instance_var):
# do stuff....
</code></pre>
<p>Any help would be appreciated.</p>
| 7 | 2009-05-15T05:40:57Z | 867,146 | <p>An alternative way of doing this would be:</p>
<pre><code>def foo(self, blah=None):
blah = blah or self.instance_var
</code></pre>
<p>This shorter version looks better, specially when there is more than one optional argument.</p>
<p><strong>Use with care. See the comments below...</strong></p>
| -1 | 2009-05-15T05:53:02Z | [
"python",
"function",
"class"
] |
python instance variables as optional arguments | 867,115 | <p>In python, is there a way I can use instance variables as optional arguments in a class method? ie:</p>
<pre><code>def function(self, arg1=val1, arg2=val2, arg3=self.instance_var):
# do stuff....
</code></pre>
<p>Any help would be appreciated.</p>
| 7 | 2009-05-15T05:40:57Z | 867,458 | <p>All the responses suggesting <code>None</code> are correct; if you want to make sure a caller can pass None as a regular argument, use a special <code>sentinel</code> and test with <code>is</code>:</p>
<pre><code>class Foo(object):
__default = object()
def foo(self, blah=Foo.__default):
if blah is Foo.__def... | 5 | 2009-05-15T07:51:18Z | [
"python",
"function",
"class"
] |
python instance variables as optional arguments | 867,115 | <p>In python, is there a way I can use instance variables as optional arguments in a class method? ie:</p>
<pre><code>def function(self, arg1=val1, arg2=val2, arg3=self.instance_var):
# do stuff....
</code></pre>
<p>Any help would be appreciated.</p>
| 7 | 2009-05-15T05:40:57Z | 2,142,400 | <pre><code>def foo(self, blah=None):
blah = blah if not blah is None else self.instance_var
</code></pre>
<p>This works with python 2.5 and forwards and handles the cases where blah is empty strings, lists and so on.</p>
| 0 | 2010-01-26T20:27:45Z | [
"python",
"function",
"class"
] |
db connection in python | 867,175 | <p>I am writing a code in python in which I established a connection with database.I have queries in a loop.While queries being executed in the loop ,If i unplug the network cable it should stop with an exception.But this not happens ,When i again plug yhe network cabe after 2 minutes it starts again from where it ende... | 0 | 2009-05-15T06:03:32Z | 867,202 | <p>Your database connection will almost certainly be based on a TCP socket. TCP sockets will hang around for a long time retrying before failing and (in python) raising an exception. Not to mention and retries/automatic reconnection attempts in the database layer.</p>
| 2 | 2009-05-15T06:11:53Z | [
"python",
"tcp",
"database-connection"
] |
db connection in python | 867,175 | <p>I am writing a code in python in which I established a connection with database.I have queries in a loop.While queries being executed in the loop ,If i unplug the network cable it should stop with an exception.But this not happens ,When i again plug yhe network cabe after 2 minutes it starts again from where it ende... | 0 | 2009-05-15T06:03:32Z | 867,222 | <p>As Douglas's answer said, it won't raise exception due to TCP.</p>
<p>You may try to use socket.setdefaulttimeout() to set a shorter timeout value.</p>
<blockquote>
<p>setdefaulttimeout(...)</p>
<pre><code> setdefaulttimeout(timeout)
Set the default timeout in floating seconds for new socket objects.
A... | 2 | 2009-05-15T06:18:49Z | [
"python",
"tcp",
"database-connection"
] |
db connection in python | 867,175 | <p>I am writing a code in python in which I established a connection with database.I have queries in a loop.While queries being executed in the loop ,If i unplug the network cable it should stop with an exception.But this not happens ,When i again plug yhe network cabe after 2 minutes it starts again from where it ende... | 0 | 2009-05-15T06:03:32Z | 867,433 | <p>If you want to implement timeouts that work no matter how the client library is connecting to the server, it's best to attempt the DB operations in a separate thread, or, better, a separate process, which a "monitor" thread/process can kill if needed; see the multiprocessing module in Python 2.6 standard library (th... | 1 | 2009-05-15T07:43:58Z | [
"python",
"tcp",
"database-connection"
] |
Python Class Members Initialization | 867,219 | <p>I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of questions...</p>
<p>The scenario: I ... | 33 | 2009-05-15T06:17:50Z | 867,226 | <p>What you keep referring to as a bug is the <a href="http://docs.python.org/tutorial/classes.html">documented</a>, standard behavior of Python classes.</p>
<p>Declaring a dict outside of <code>__init__</code> as you initially did is declaring a class-level variable. It is only created once at first, whenever you cre... | 47 | 2009-05-15T06:19:29Z | [
"python",
"class",
"initialization"
] |
Python Class Members Initialization | 867,219 | <p>I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of questions...</p>
<p>The scenario: I ... | 33 | 2009-05-15T06:17:50Z | 867,239 | <p>When you access attribute of instance, say, self.foo, python will first find 'foo' in <code>self.__dict__</code>. If not found, python will find 'foo' in <code>TheClass.__dict__</code></p>
<p>In your case, <code>dict1</code> is of class A, not instance. </p>
| 1 | 2009-05-15T06:23:12Z | [
"python",
"class",
"initialization"
] |
Python Class Members Initialization | 867,219 | <p>I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of questions...</p>
<p>The scenario: I ... | 33 | 2009-05-15T06:17:50Z | 867,248 | <p>Pythons class declarations are executed as a code block and any local variable definitions (of which function definitions are a special kind of) are stored in the constructed class instance. Due to the way attribute look up works in Python, if an attribute is not found on the instance the value on the class is used.... | 0 | 2009-05-15T06:27:39Z | [
"python",
"class",
"initialization"
] |
Python Class Members Initialization | 867,219 | <p>I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of questions...</p>
<p>The scenario: I ... | 33 | 2009-05-15T06:17:50Z | 867,348 | <p>If this is your code:</p>
<pre><code>class ClassA:
dict1 = {}
a = ClassA()
</code></pre>
<p>Then you probably expected this to happen inside Python:</p>
<pre><code>class ClassA:
__defaults__['dict1'] = {}
a = instance(ClassA)
# a bit of pseudo-code here:
for name, value in ClassA.__defaults__:
a.<... | 0 | 2009-05-15T07:06:18Z | [
"python",
"class",
"initialization"
] |
Python Class Members Initialization | 867,219 | <p>I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of questions...</p>
<p>The scenario: I ... | 33 | 2009-05-15T06:17:50Z | 1,542,534 | <p>@Matthew : Please review the difference between a class member and an object member in Object Oriented Programming. This problem happens because of the declaration of the original dict makes it a class member, and not an object member (as was the original poster's intent.) Consequently, it exists once for (is shar... | 2 | 2009-10-09T08:21:50Z | [
"python",
"class",
"initialization"
] |
Writing Digg like system in django/python | 867,251 | <p>I am tying to write a digg , hackernews , <a href="http://collectivesys.com/" rel="nofollow">http://collectivesys.com/</a> like application where users submit something and other users can vote up or down , mark items as favorite ect .
I was just wondering if there are some open source implementations django/pytho... | 2 | 2009-05-15T06:28:17Z | 867,259 | <p>Check out <a href="http://pinaxproject.com/" rel="nofollow">Pinax</a> and <a href="http://djangoplugables.com/" rel="nofollow">Django Pluggables</a> for some pre-made Django apps to help you out.</p>
| 6 | 2009-05-15T06:32:02Z | [
"python",
"django",
"digg"
] |
Writing Digg like system in django/python | 867,251 | <p>I am tying to write a digg , hackernews , <a href="http://collectivesys.com/" rel="nofollow">http://collectivesys.com/</a> like application where users submit something and other users can vote up or down , mark items as favorite ect .
I was just wondering if there are some open source implementations django/pytho... | 2 | 2009-05-15T06:28:17Z | 867,332 | <p><a href="http://reddit.com" rel="nofollow">reddit</a> is <a href="https://github.com/reddit/reddit" rel="nofollow">open source</a>, written mostly in python. Apart from the code, there might be some algorithms you may find helpful.</p>
| 5 | 2009-05-15T06:57:22Z | [
"python",
"django",
"digg"
] |
Writing Digg like system in django/python | 867,251 | <p>I am tying to write a digg , hackernews , <a href="http://collectivesys.com/" rel="nofollow">http://collectivesys.com/</a> like application where users submit something and other users can vote up or down , mark items as favorite ect .
I was just wondering if there are some open source implementations django/pytho... | 2 | 2009-05-15T06:28:17Z | 867,335 | <p>Though not written in django, <a href="http://reddit.com" rel="nofollow">reddit</a> is written in python and is open source. From <a href="http://code.reddit.com/" rel="nofollow">the code</a> you could get some ideas and see how they overcame certain hurdles etc. They've open sourced everything bar their antispam ... | 1 | 2009-05-15T06:58:51Z | [
"python",
"django",
"digg"
] |
Writing Digg like system in django/python | 867,251 | <p>I am tying to write a digg , hackernews , <a href="http://collectivesys.com/" rel="nofollow">http://collectivesys.com/</a> like application where users submit something and other users can vote up or down , mark items as favorite ect .
I was just wondering if there are some open source implementations django/pytho... | 2 | 2009-05-15T06:28:17Z | 869,039 | <p>I'd recommend taking a close look at the <a href="http://code.google.com/p/django-voting/wiki/RedditStyleVoting" rel="nofollow">django-voting project</a> on Google Code.</p>
<p>They claim to be an django implementation of "Reddit Style Voting"</p>
| 3 | 2009-05-15T14:31:08Z | [
"python",
"django",
"digg"
] |
How do languages such as Python overcome C's Integral data limits? | 867,393 | <p>While doing some random experimentation with a factorial program in C, Python and Scheme. I came across this fact:</p>
<p>In C, using 'unsigned long long' data type, the largest factorial I can print is of 65. which is '9223372036854775808' that is 19 digits as specified <a href="http://en.wikipedia.org/wiki/Integ... | 2 | 2009-05-15T07:26:49Z | 867,405 | <p>Python assigns to <code>long</code> integers (all <code>int</code>s in Python 3) just as much space as they need -- an array of "digits" (base being a power of 2) allocated as needed.</p>
| 1 | 2009-05-15T07:30:36Z | [
"python",
"c",
"types",
"integer"
] |
How do languages such as Python overcome C's Integral data limits? | 867,393 | <p>While doing some random experimentation with a factorial program in C, Python and Scheme. I came across this fact:</p>
<p>In C, using 'unsigned long long' data type, the largest factorial I can print is of 65. which is '9223372036854775808' that is 19 digits as specified <a href="http://en.wikipedia.org/wiki/Integ... | 2 | 2009-05-15T07:26:49Z | 867,408 | <p>Not octaword. It implemented <a href="http://en.wikipedia.org/wiki/Bignum" rel="nofollow">bignum</a> structure to store arbitary-precision numbers.</p>
| 3 | 2009-05-15T07:32:07Z | [
"python",
"c",
"types",
"integer"
] |
How do languages such as Python overcome C's Integral data limits? | 867,393 | <p>While doing some random experimentation with a factorial program in C, Python and Scheme. I came across this fact:</p>
<p>In C, using 'unsigned long long' data type, the largest factorial I can print is of 65. which is '9223372036854775808' that is 19 digits as specified <a href="http://en.wikipedia.org/wiki/Integ... | 2 | 2009-05-15T07:26:49Z | 867,411 | <p>It's called <em>Arbitrary Precision Arithmetic</em>. There's more here: <a href="http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic">http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic</a></p>
| 9 | 2009-05-15T07:33:02Z | [
"python",
"c",
"types",
"integer"
] |
How do languages such as Python overcome C's Integral data limits? | 867,393 | <p>While doing some random experimentation with a factorial program in C, Python and Scheme. I came across this fact:</p>
<p>In C, using 'unsigned long long' data type, the largest factorial I can print is of 65. which is '9223372036854775808' that is 19 digits as specified <a href="http://en.wikipedia.org/wiki/Integ... | 2 | 2009-05-15T07:26:49Z | 867,416 | <p>Data types such as <code>int</code> in C are directly mapped (more or less) to the data types supported by the processor. So the limits on C's <code>int</code> are essentially the limits imposed by the processor hardware.</p>
<p>But one can implement one's own <code>int</code> data type entirely in software. You ca... | 4 | 2009-05-15T07:34:43Z | [
"python",
"c",
"types",
"integer"
] |
How do languages such as Python overcome C's Integral data limits? | 867,393 | <p>While doing some random experimentation with a factorial program in C, Python and Scheme. I came across this fact:</p>
<p>In C, using 'unsigned long long' data type, the largest factorial I can print is of 65. which is '9223372036854775808' that is 19 digits as specified <a href="http://en.wikipedia.org/wiki/Integ... | 2 | 2009-05-15T07:26:49Z | 870,429 | <p>Looking at the Python source code, it seems the <code>long</code> type (at least in pre-Python 3 code) is defined in <a href="http://svn.python.org/view/python/trunk/Include/longintrepr.h?view=markup" rel="nofollow">longintrepr.h</a> like this -</p>
<pre><code>/* Long integer representation.
The absolute value o... | 6 | 2009-05-15T19:32:03Z | [
"python",
"c",
"types",
"integer"
] |
Numbers Comparison - Python Bug? | 867,436 | <p>Deep inside my code, in a nested if inside a nested for inside a class method, I'm comparing a certain index value to the length of a certain list, to validate I can access that index. The code looks something like that:</p>
<pre><code>if t.index_value < len(work_list):
... do stuff ...
else:
... print s... | 1 | 2009-05-15T07:45:07Z | 867,457 | <p>In my experience, what is the type of "t.index_value"? Maybe it is a string "3".</p>
<pre><code>>>> print '3' < 4
False
</code></pre>
| 8 | 2009-05-15T07:51:05Z | [
"python",
"numbers"
] |
Numbers Comparison - Python Bug? | 867,436 | <p>Deep inside my code, in a nested if inside a nested for inside a class method, I'm comparing a certain index value to the length of a certain list, to validate I can access that index. The code looks something like that:</p>
<pre><code>if t.index_value < len(work_list):
... do stuff ...
else:
... print s... | 1 | 2009-05-15T07:45:07Z | 867,508 | <p>To display values which might be of different types than you expect (e.g. a string rather than a number, as kcwu suggests), use <code>repr(x)</code> and the like.</p>
| 2 | 2009-05-15T08:07:11Z | [
"python",
"numbers"
] |
How to catch str exception? | 867,522 | <pre><code>import sys
try:
raise "xxx"
except str,e:
print "1",e
except:
print "2",sys.exc_type,sys.exc_value
</code></pre>
<p>In the above code a string exception is raised which though deprecated but still a 3rd party library I use uses it.
So how can I catch such exception without relying on catch all, ... | 2 | 2009-05-15T08:11:01Z | 867,553 | <pre><code>try:
raise "xxx"
except "xxx":
print "xxx caught"
</code></pre>
<p><code>except <class></code> only works with classes that are a subclass of <code>Exception</code> i think. Oh btw, use <code>basestring</code> when checking the type of strings, works with unicode strings too.</p>
| 2 | 2009-05-15T08:19:29Z | [
"python",
"exception",
"string"
] |
How to catch str exception? | 867,522 | <pre><code>import sys
try:
raise "xxx"
except str,e:
print "1",e
except:
print "2",sys.exc_type,sys.exc_value
</code></pre>
<p>In the above code a string exception is raised which though deprecated but still a 3rd party library I use uses it.
So how can I catch such exception without relying on catch all, ... | 2 | 2009-05-15T08:11:01Z | 867,559 | <p>The generic <code>except:</code> clause is the only way to catch all str exceptions.</p>
<p>str exceptions are a legacy Python feature. In new code you should use <code>raise Exception("xxx")</code> or raise your own Exception subclass, or <code>assert 0, "xxx"</code>.</p>
| 6 | 2009-05-15T08:22:14Z | [
"python",
"exception",
"string"
] |
How to catch str exception? | 867,522 | <pre><code>import sys
try:
raise "xxx"
except str,e:
print "1",e
except:
print "2",sys.exc_type,sys.exc_value
</code></pre>
<p>In the above code a string exception is raised which though deprecated but still a 3rd party library I use uses it.
So how can I catch such exception without relying on catch all, ... | 2 | 2009-05-15T08:11:01Z | 868,017 | <p>Raising raw strings is just wrong. It's a deprecated feature (and as such should have raised warnings). Catching the explicit string will work if you really need it, and so will catching everything. Since catching everything puts the ugliness in <em>your</em> code, I recommend catching the string explicitly, or even... | 2 | 2009-05-15T10:53:12Z | [
"python",
"exception",
"string"
] |
How to catch str exception? | 867,522 | <pre><code>import sys
try:
raise "xxx"
except str,e:
print "1",e
except:
print "2",sys.exc_type,sys.exc_value
</code></pre>
<p>In the above code a string exception is raised which though deprecated but still a 3rd party library I use uses it.
So how can I catch such exception without relying on catch all, ... | 2 | 2009-05-15T08:11:01Z | 868,244 | <p>Here is the solution from <a href="http://groups.google.com/group/comp.lang.python/browse_frm/thread/6f82aa367e86a54e/6891821d373b50a8#6891821d373b50a8" rel="nofollow">python mailing list</a>, not very elegant but will work if can't avoid the need for such hack</p>
<pre><code>import sys
try:
raise "a string ex... | 3 | 2009-05-15T11:54:47Z | [
"python",
"exception",
"string"
] |
Creating a wrapper for a C library in Python | 867,850 | <p>I'm trying to create a wrapper of my own for FLAC, so that I can use FLAC in my own Python code.</p>
<p>I tried using ctypes first, but it showed a really weird interface to the library, e.g. all the init functions for FLAC streams and files became one function with no real information on how to initialize it. Espe... | 5 | 2009-05-15T10:06:06Z | 867,861 | <p>Did you have a look at <a href="http://www.swig.org/">http://www.swig.org/</a>:</p>
<blockquote>
<p>SWIG is a software development tool
that connects programs written in C
and C++ with a variety of high-level
programming languages.</p>
</blockquote>
| 5 | 2009-05-15T10:12:24Z | [
"python",
"c"
] |
Creating a wrapper for a C library in Python | 867,850 | <p>I'm trying to create a wrapper of my own for FLAC, so that I can use FLAC in my own Python code.</p>
<p>I tried using ctypes first, but it showed a really weird interface to the library, e.g. all the init functions for FLAC streams and files became one function with no real information on how to initialize it. Espe... | 5 | 2009-05-15T10:06:06Z | 867,864 | <blockquote>
<p>Python has no way to store pointers, and thus I can't store the pointer to the stream decoder</p>
</blockquote>
<p><strong>ctypes</strong> has pointers, and ctypes can be used to wrap existing C libraries. Just a tip, you will need to wrap/rewrite all relavent C structures into ctypes.Structure.
Ta... | 10 | 2009-05-15T10:13:15Z | [
"python",
"c"
] |
Creating a wrapper for a C library in Python | 867,850 | <p>I'm trying to create a wrapper of my own for FLAC, so that I can use FLAC in my own Python code.</p>
<p>I tried using ctypes first, but it showed a really weird interface to the library, e.g. all the init functions for FLAC streams and files became one function with no real information on how to initialize it. Espe... | 5 | 2009-05-15T10:06:06Z | 868,007 | <p>Some people use <a href="http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/" rel="nofollow">pyrex</a> for this.</p>
| 0 | 2009-05-15T10:49:07Z | [
"python",
"c"
] |
Creating a wrapper for a C library in Python | 867,850 | <p>I'm trying to create a wrapper of my own for FLAC, so that I can use FLAC in my own Python code.</p>
<p>I tried using ctypes first, but it showed a really weird interface to the library, e.g. all the init functions for FLAC streams and files became one function with no real information on how to initialize it. Espe... | 5 | 2009-05-15T10:06:06Z | 870,957 | <blockquote>
<p>but Python has no way to store pointers ( BZZZT! )</p>
</blockquote>
<p>That is incorrect. You create a pointer like this:</p>
<pre><code>pInt = POINTER(c_int)()
</code></pre>
<p>and you access it like this</p>
<pre><code>pInt[0] # or p.contents
</code></pre>
| 4 | 2009-05-15T21:33:20Z | [
"python",
"c"
] |
Creating a wrapper for a C library in Python | 867,850 | <p>I'm trying to create a wrapper of my own for FLAC, so that I can use FLAC in my own Python code.</p>
<p>I tried using ctypes first, but it showed a really weird interface to the library, e.g. all the init functions for FLAC streams and files became one function with no real information on how to initialize it. Espe... | 5 | 2009-05-15T10:06:06Z | 22,825,713 | <p>This post is old, but there's an alternative to <code>ctypes</code>: <a href="http://cffi.readthedocs.org" rel="nofollow">CFFI</a>. It's lots easier, somewhat faster, and works better under PyPy. Plus, it supports pointers well. Here's an example:</p>
<pre><code>from cffi import FFI
ffi = cffi.FFI()
ffi.cdef('''
... | 1 | 2014-04-03T00:39:47Z | [
"python",
"c"
] |
Convert unicode codepoint to UTF8 hex in python | 867,866 | <p>I want to convert a number of unicode codepoints read from a file to their UTF8 encoding.</p>
<p>e.g I want to convert the string <code>'FD9B'</code> to the string <code>'EFB69B'</code>.</p>
<p>I can do this manually using string literals like this:</p>
<pre><code>u'\uFD9B'.encode('utf-8')
</code></pre>
<p>but I... | 11 | 2009-05-15T10:13:24Z | 867,880 | <p>Use the built-in function <code><a href="http://docs.python.org/library/functions.html#unichr">unichr()</a></code> to convert the number to character, then encode that:</p>
<pre><code>>>> unichr(int('fd9b', 16)).encode('utf-8')
'\xef\xb6\x9b'
</code></pre>
<p>This is the string itself. If you want the str... | 17 | 2009-05-15T10:18:55Z | [
"python",
"unicode"
] |
Convert unicode codepoint to UTF8 hex in python | 867,866 | <p>I want to convert a number of unicode codepoints read from a file to their UTF8 encoding.</p>
<p>e.g I want to convert the string <code>'FD9B'</code> to the string <code>'EFB69B'</code>.</p>
<p>I can do this manually using string literals like this:</p>
<pre><code>u'\uFD9B'.encode('utf-8')
</code></pre>
<p>but I... | 11 | 2009-05-15T10:13:24Z | 867,884 | <pre><code>Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> u'\uFD9B'.encode('utf-8')
'\xef\xb6\x9b'
>>> s = 'FD9B'
>>> i = int(s, 16)
>>> i
64923
>&... | 1 | 2009-05-15T10:20:48Z | [
"python",
"unicode"
] |
Convert unicode codepoint to UTF8 hex in python | 867,866 | <p>I want to convert a number of unicode codepoints read from a file to their UTF8 encoding.</p>
<p>e.g I want to convert the string <code>'FD9B'</code> to the string <code>'EFB69B'</code>.</p>
<p>I can do this manually using string literals like this:</p>
<pre><code>u'\uFD9B'.encode('utf-8')
</code></pre>
<p>but I... | 11 | 2009-05-15T10:13:24Z | 869,221 | <pre><code>data_from_file='\uFD9B'
unicode(data_from_file,"unicode_escape").encode("utf8")
</code></pre>
| 3 | 2009-05-15T15:05:03Z | [
"python",
"unicode"
] |
Convert unicode codepoint to UTF8 hex in python | 867,866 | <p>I want to convert a number of unicode codepoints read from a file to their UTF8 encoding.</p>
<p>e.g I want to convert the string <code>'FD9B'</code> to the string <code>'EFB69B'</code>.</p>
<p>I can do this manually using string literals like this:</p>
<pre><code>u'\uFD9B'.encode('utf-8')
</code></pre>
<p>but I... | 11 | 2009-05-15T10:13:24Z | 870,567 | <p>If the input string length is a multiple of 4 (i.e. your unicode code points are UCS-2 encoded), then try this:</p>
<pre><code>import struct
def unihex2utf8hex(arg):
count= len(arg)//4
uniarr= struct.unpack('!%dH' % count, arg.decode('hex'))
return u''.join(map(unichr, uniarr)).encode('utf-8').encode('... | 1 | 2009-05-15T19:54:55Z | [
"python",
"unicode"
] |
Convert unicode codepoint to UTF8 hex in python | 867,866 | <p>I want to convert a number of unicode codepoints read from a file to their UTF8 encoding.</p>
<p>e.g I want to convert the string <code>'FD9B'</code> to the string <code>'EFB69B'</code>.</p>
<p>I can do this manually using string literals like this:</p>
<pre><code>u'\uFD9B'.encode('utf-8')
</code></pre>
<p>but I... | 11 | 2009-05-15T10:13:24Z | 15,181,783 | <p>here's a complete solution:</p>
<pre><code>>>> ''.join(['{0:x}'.format(ord(x)) for x in unichr(int('FD9B', 16)).encode('utf-8')]).upper()
'EFB69B'
</code></pre>
| 2 | 2013-03-03T02:22:40Z | [
"python",
"unicode"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 867,983 | <p>I have no idea what you're trying to do with that code. But I'm 99% certain that whatever it is could probably be done in 2 lines. I also get the feeling that the '==' operator should be an 'is' operator, otherwise what is the compare() function doing? And what happens if the item returned from the second jump_iter.... | 0 | 2009-05-15T10:44:14Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 867,991 | <p>You could put the whole iteration into a single try structure, that way it would be clearer:</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
for item in items:
if jump_item is item:
jump_item = jump_iter.next()
# do lots of stuf... | 0 | 2009-05-15T10:46:34Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 867,994 | <p>So you want to compare pairs of items in the same list, the second item of the pair having to meet some condition. Normally, when you want to compare pairs in a list use <code>zip</code> (or <code>itertools.izip</code>):</p>
<pre><code>for item1, item2 in zip(items, items[1:]):
compare(item1, item2)
</code></pr... | 0 | 2009-05-15T10:46:37Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 868,000 | <p>I have no idea what <code>compare()</code> is doing, but 80% of the time, you can do this with a trivial dictionary or pair of dictionaries. Jumping around in a list is a kind of linear search. Linear Search -- to the extent possible -- should always be replaced with either a direct reference (i.e., a dict) or a tr... | 1 | 2009-05-15T10:47:45Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 868,152 | <p>Are you basically trying to compare every item in the iterator with every other item in the original list?</p>
<p>To my mind this should just be a case of using two loops, rather than trying to fit it into one.</p>
<pre>
<code>
filtered_items = (j for j in items if some_cond)
for filtered in filtered_items:
fo... | 0 | 2009-05-15T11:31:25Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 868,363 | <p>Here is one simple solution that might look a little cleaner: </p>
<pre><code>for i, item in enumerate(items):
for next_item in items[i+1:]:
if some_cond(next_item):
break
# do some stuff with both items
</code></pre>
<p>The disadvantage is that you check the condition for next_item mul... | 0 | 2009-05-15T12:19:15Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 868,396 | <p>How about this?</p>
<pre><code>paired_values = []
for elmt in reversed(items):
if <condition>:
current_val = elmt
try:
paired_values.append(current_val)
except NameError: # for the last elements of items that don't pass the condition
pass
paired_values.reverse()
for (item... | 1 | 2009-05-15T12:26:24Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 868,410 | <p>My first answer was wrong because I didn't quite understand what you were trying to achieve. So if I understand correctly (this time, I hope), you want the main <code>for item in items:</code> to "chase" after an iterator that filters out some items. Well, there's not much you can do, except maybe wrap this into a ... | 0 | 2009-05-15T12:29:29Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 868,458 | <p>The following iterator is time and memory-efficient:</p>
<pre><code>def jump_items(items):
number_to_be_returned = 0
for elmt in items:
if <condition(elmt)>:
for i in range(number_to_be_returned):
yield elmt
number_to_be_returned = 1
else:
... | 1 | 2009-05-15T12:40:49Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 868,497 | <pre><code>for i in range( 0, len( items ) ):
for j in range( i+1, len( items ) ):
if some_cond:
#do something
#items[i] = item, items[j] = jump_item
</code></pre>
| 0 | 2009-05-15T12:49:50Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 868,631 | <p>With just iterators</p>
<pre><code>def(lst, some_cond):
jump_item_iter = (j for j in lst if som_cond(j))
pairs = itertools.izip(lst, lst[1:])
for last in jump_item_iter:
for start, start_next in itertools.takewhile(lambda pair: pair[0] < last, pairs):
yield start, last
... | 0 | 2009-05-15T13:19:04Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 868,763 | <p>Even better using itertools.groupby:</p>
<pre><code>def h(lst, cond):
remain = lst
for last in (l for l in lst if cond(l)):
group = itertools.groupby(remain, key=lambda x: x < last)
for start in group.next()[1]:
yield start, last
remain = list(group.next()[1])
</code></pre>
<p>Usage:
lst =... | 0 | 2009-05-15T13:46:05Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 868,770 | <p>Maybe it is too late, but what about:</p>
<pre><code>l = [j for j in items if some_cond]
for item, jump_item in zip(l, l[1:]):
# do lots of stuff with item and jump_item
</code></pre>
<p>If l = [j for j in range(10) if j%2 ==0] then the iteration is over: [(0, 2),(2, 4),(4, 6),(6, 8)].</p>
| 0 | 2009-05-15T13:47:15Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 868,864 | <p>Write a generator function:</p>
<pre><code>def myIterator(someValue):
yield (someValue[0], someValue[1])
for element1, element2 in myIterator(array):
# do something with those elements.
</code></pre>
| 1 | 2009-05-15T14:03:58Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 869,468 | <p>As far as I can see any of the existing solutions work on a general one shot, possiboly infinite iter**ator**, all of them seem to require an iter**able**.</p>
<p>Heres a solution to that.</p>
<pre><code>def batch_by(condition, seq):
it = iter(seq)
batch = [it.next()]
for jump_item in it:
if co... | 4 | 2009-05-15T15:49:57Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 870,027 | <p>You could write your loop body as:</p>
<pre><code>import itertools, functools, operator
for item in items:
jump_item_iter = itertools.dropwhile(functools.partial(operator.is_, item),
jump_item_iter)
# do something with item and jump_item_iter
</code></pre>
<p>dro... | 0 | 2009-05-15T17:48:53Z | [
"python",
"iterator"
] |
Python: Elegant way of dual/multiple iteration over the same list | 867,936 | <p>I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration?</p>
<pre><code>jump_item_iter = (j for j in items if some_cond)
try:
jump_item = jump_item_iter.next()
except StopIteration:
return
for item... | 6 | 2009-05-15T10:35:14Z | 870,982 | <p>You could do something like:</p>
<pre><code>import itertools
def matcher(iterable, compare):
iterator= iter(iterable)
while True:
try: item= iterator.next()
except StopIteration: break
iterator, iterator2= itertools.tee(iterator)
for item2 in iterator2:
if compar... | 0 | 2009-05-15T21:41:22Z | [
"python",
"iterator"
] |
Loading files into variables in python | 868,112 | <p>I am trying to write a small function that gets a variable name, check if it exists, and if not loads it from a file (using pickle) to the global namespace.</p>
<p>I tried using this in a file:</p>
<pre><code>import cPickle
#
# Load if neccesary
#
def loadfile(variable, filename):
if variable not in globals()... | 2 | 2009-05-15T11:17:57Z | 868,172 | <p>You could alway avoid exec entirely:</p>
<pre>
<code>
import cPickle
#
# Load if neccesary
#
def loadfile(variable, filename):
g=globals()
if variable not in g:
g[variable]=cPickle.load(file(filename,'r'))
</code>
</pre>
<p>EDIT: of course that only loads the globals into the current module's glo... | 2 | 2009-05-15T11:37:16Z | [
"python",
"namespaces",
"pickle"
] |
Loading files into variables in python | 868,112 | <p>I am trying to write a small function that gets a variable name, check if it exists, and if not loads it from a file (using pickle) to the global namespace.</p>
<p>I tried using this in a file:</p>
<pre><code>import cPickle
#
# Load if neccesary
#
def loadfile(variable, filename):
if variable not in globals()... | 2 | 2009-05-15T11:17:57Z | 868,443 | <p>Using 'globals' has the problem that it only works for the current module. Rather than passing 'globals' around, a better way is to use the 'setattr' builtin directly on a namespace. This means you can then reuse the function on instances as well as modules.</p>
<pre><code>import cPickle
#
# Load if neccesary
#
de... | 2 | 2009-05-15T12:36:41Z | [
"python",
"namespaces",
"pickle"
] |
What host to use when making a UDP socket in python? | 868,173 | <p>I want ro receive some data that is sent as a UDP packet over VPN. So wrote (mostly copied) this program in python:</p>
<pre><code>import socket
import sys
HOST = ???????
PORT = 80
# SOCK_DGRAM is the socket type to use for UDP sockets
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((HOST,POR... | 4 | 2009-05-15T11:37:25Z | 868,191 | <p>The host argument is the host IP you want to bind to. Specify the IP of one of your interfaces (Eg, your public IP, or 127.0.0.1 for localhost), or use 0.0.0.0 to bind to all interfaces. If you bind to a specific interface, your service will only be available on that interface - for example, if you want to run somet... | 10 | 2009-05-15T11:40:10Z | [
"python",
"sockets",
"udp"
] |
What host to use when making a UDP socket in python? | 868,173 | <p>I want ro receive some data that is sent as a UDP packet over VPN. So wrote (mostly copied) this program in python:</p>
<pre><code>import socket
import sys
HOST = ???????
PORT = 80
# SOCK_DGRAM is the socket type to use for UDP sockets
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((HOST,POR... | 4 | 2009-05-15T11:37:25Z | 868,206 | <p>"0.0.0.0" will listen for all incoming hosts. For example,</p>
<pre><code>sock.bind(("0.0.0.0", 999))
data,addr = sock.recv(1024)
</code></pre>
| 3 | 2009-05-15T11:42:54Z | [
"python",
"sockets",
"udp"
] |
What host to use when making a UDP socket in python? | 868,173 | <p>I want ro receive some data that is sent as a UDP packet over VPN. So wrote (mostly copied) this program in python:</p>
<pre><code>import socket
import sys
HOST = ???????
PORT = 80
# SOCK_DGRAM is the socket type to use for UDP sockets
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((HOST,POR... | 4 | 2009-05-15T11:37:25Z | 868,230 | <p>Use:</p>
<pre><code>sock.bind(("", 999))
</code></pre>
| 3 | 2009-05-15T11:49:50Z | [
"python",
"sockets",
"udp"
] |
Python Newbie: Returning Multiple Int/String Results in Python | 868,325 | <p>I have a function that has several outputs, all of which "native", i.e. integers and strings. For example, let's say I have a function that analyzes a string, and finds both the number of words and the average length of a word. </p>
<p>In C/C++ I would use @ to pass 2 parameters to the function. In Python I'm not s... | 1 | 2009-05-15T12:12:31Z | 868,355 | <p>If you need to use method arguments in both directions, you can encapsulate the arguments to the class and pass object to the method and let the method use its properties.</p>
| 0 | 2009-05-15T12:17:44Z | [
"python",
"parameters",
"reference"
] |
Python Newbie: Returning Multiple Int/String Results in Python | 868,325 | <p>I have a function that has several outputs, all of which "native", i.e. integers and strings. For example, let's say I have a function that analyzes a string, and finds both the number of words and the average length of a word. </p>
<p>In C/C++ I would use @ to pass 2 parameters to the function. In Python I'm not s... | 1 | 2009-05-15T12:12:31Z | 868,356 | <p>python has a <code>return</code> statement, which allows you to do the follwing:</p>
<pre><code>def func(input):
# do calculation on input
return result
s = "hello goodbye"
res = func(s) # res now a result dictionary
</code></pre>
<p>but you don't need to have <code>result</code> at all, you can ret... | 17 | 2009-05-15T12:17:50Z | [
"python",
"parameters",
"reference"
] |
Python Newbie: Returning Multiple Int/String Results in Python | 868,325 | <p>I have a function that has several outputs, all of which "native", i.e. integers and strings. For example, let's say I have a function that analyzes a string, and finds both the number of words and the average length of a word. </p>
<p>In C/C++ I would use @ to pass 2 parameters to the function. In Python I'm not s... | 1 | 2009-05-15T12:12:31Z | 868,365 | <p>If you return the variables in your function like this:</p>
<pre><code>def analyze(s, num_words, avg_length):
# do something
return s, num_words, avg_length
</code></pre>
<p>Then you can call it like this to update the parameters that were passed:</p>
<pre><code>s, num_words, avg_length = analyze(s, num_w... | 3 | 2009-05-15T12:19:32Z | [
"python",
"parameters",
"reference"
] |
Python Newbie: Returning Multiple Int/String Results in Python | 868,325 | <p>I have a function that has several outputs, all of which "native", i.e. integers and strings. For example, let's say I have a function that analyzes a string, and finds both the number of words and the average length of a word. </p>
<p>In C/C++ I would use @ to pass 2 parameters to the function. In Python I'm not s... | 1 | 2009-05-15T12:12:31Z | 868,760 | <p>In python you don't modify parameters in the C/C++ way (passing them by reference or through a pointer and doing modifications <em>in situ</em>).There are some reasons such as that the string objects are inmutable in python. The right thing to do is to return the modified parameters in a tuple (as SilentGhost sugges... | 1 | 2009-05-15T13:45:26Z | [
"python",
"parameters",
"reference"
] |
Problem using py2app with the lxml package | 868,510 | <p>I am trying to use 'py2app' to generate a standalone application from some Python scripts. The Python uses the 'lxml' package, and I've found that I have to specify this explicitly in the setup.py file that 'py2app' uses. However, the resulting application program still won't run on machines that haven't had 'lxml' ... | 5 | 2009-05-15T12:52:37Z | 868,549 | <p><strong>------------- Edit--------------</strong><br>
<code>libxml2</code> is standard in the python.org version of Python. It is not standard in Apple's version of Python. Make sure py2app is using the right version of Python, or install <code>libxml2</code> and <code>libxslt</code> on your Mac.</p>
| 1 | 2009-05-15T13:01:48Z | [
"python",
"lxml",
"py2app"
] |
Problem using py2app with the lxml package | 868,510 | <p>I am trying to use 'py2app' to generate a standalone application from some Python scripts. The Python uses the 'lxml' package, and I've found that I have to specify this explicitly in the setup.py file that 'py2app' uses. However, the resulting application program still won't run on machines that haven't had 'lxml' ... | 5 | 2009-05-15T12:52:37Z | 874,923 | <p>I have no experience with the combination of lxml and py2app specifically, but I've had issues with py2app not picking up modules that were not explicitly imported. For example, I had to explicitly include modules that are imported via <code>__import__()</code>, like this:</p>
<pre><code>OPTIONS['includes'] = [file... | 1 | 2009-05-17T16:24:43Z | [
"python",
"lxml",
"py2app"
] |
Problem using py2app with the lxml package | 868,510 | <p>I am trying to use 'py2app' to generate a standalone application from some Python scripts. The Python uses the 'lxml' package, and I've found that I have to specify this explicitly in the setup.py file that 'py2app' uses. However, the resulting application program still won't run on machines that haven't had 'lxml' ... | 5 | 2009-05-15T12:52:37Z | 877,560 | <p>I just tried my app (uses py2app and lxml, with a similar setup) on another Mac without development libraries installed, and it works, so there must be something wrong in your system. My guess is that py2app picks the wrong version of libxml2 (I see it comes bundled with the iPhone SDK for example, which is probably... | 1 | 2009-05-18T12:46:32Z | [
"python",
"lxml",
"py2app"
] |
Problem using py2app with the lxml package | 868,510 | <p>I am trying to use 'py2app' to generate a standalone application from some Python scripts. The Python uses the 'lxml' package, and I've found that I have to specify this explicitly in the setup.py file that 'py2app' uses. However, the resulting application program still won't run on machines that haven't had 'lxml' ... | 5 | 2009-05-15T12:52:37Z | 888,551 | <p>Found it. py2app has a 'frameworks' option to let you specify frameworks, and also dylibs. My setup.py file now looks like this:</p>
<pre><code>from setuptools import setup
DATA_FILES = []
OPTIONS = {'argv_emulation': True,
'packages' : ['lxml'],
'frameworks' : ['/usr/local/libxml2-2.7.2/lib/... | 10 | 2009-05-20T15:15:54Z | [
"python",
"lxml",
"py2app"
] |
On GAE, how may I show a date according to right client TimeZone? | 868,708 | <p>On my Google App Engine application, i'm storing an auto-updated date/time in my model like that :</p>
<pre><code>class MyModel(db.Model):
date = db.DateTimeProperty(auto_now_add=True)
</code></pre>
<p>But, that date/time is the local time on server, according to it's time zone.</p>
<p>So, when I would like to... | 5 | 2009-05-15T13:34:23Z | 868,762 | <p>You can find out the server's timezone by asking for local and UTC time and seeing what the difference is. To find out the client timezone you need to have in your template a little bit of Javascript that will tell you e.g. in an AJAX exchange. To manipulate timezones once you've discovered the deltas I suggest py... | 1 | 2009-05-15T13:45:45Z | [
"python",
"django",
"google-app-engine",
"timezone"
] |
On GAE, how may I show a date according to right client TimeZone? | 868,708 | <p>On my Google App Engine application, i'm storing an auto-updated date/time in my model like that :</p>
<pre><code>class MyModel(db.Model):
date = db.DateTimeProperty(auto_now_add=True)
</code></pre>
<p>But, that date/time is the local time on server, according to it's time zone.</p>
<p>So, when I would like to... | 5 | 2009-05-15T13:34:23Z | 868,793 | <p>With respect to the second part of your question:</p>
<p>Python time() returns UTC regardless of what time zone the server is in. timezone() and tzname() will give you, respectively, the offset to local time on the server and the name of the timezone and the DST timezone as a tuple. GAE uses Python 2.5.x as of th... | 5 | 2009-05-15T13:50:08Z | [
"python",
"django",
"google-app-engine",
"timezone"
] |
On GAE, how may I show a date according to right client TimeZone? | 868,708 | <p>On my Google App Engine application, i'm storing an auto-updated date/time in my model like that :</p>
<pre><code>class MyModel(db.Model):
date = db.DateTimeProperty(auto_now_add=True)
</code></pre>
<p>But, that date/time is the local time on server, according to it's time zone.</p>
<p>So, when I would like to... | 5 | 2009-05-15T13:34:23Z | 868,885 | <p>Ok, so thanks to Thomas L Holaday, I have to sent that UTC date to the client, for example using JSON : </p>
<pre><code>json = '{"serverUTCDate":new Date("%s")}' % date.ctime()
</code></pre>
<p>And then, on the client side, add/remove the number of seconds according to the user time zone like that :</p>
<pre><cod... | 2 | 2009-05-15T14:07:55Z | [
"python",
"django",
"google-app-engine",
"timezone"
] |
HTML Newbie Question: Colored Background for Characters in Django HttpResponse | 868,871 | <p>I would like to generate an HttpResponse that contains a certain string. For each of the characters in the string I have a background color I want to use. </p>
<p>For simplification, let's assume I can only have shades of green in the background, and that the "background colors" data represents "level of brightness... | 1 | 2009-05-15T14:04:30Z | 869,024 | <p>It could be something like this:</p>
<pre><code>aString = 'abcd'
newString =''
colors= [0.0, 1.0, 0.5, 1.0]
for i in aString:
newString = newString + '<span style="background-color: rgb(0,%s,0)">%s</span>'%(colors.pop(0)*255,i)
response = HttpResponse(newString)
</code></pre>
<p>untested</p>
| 2 | 2009-05-15T14:28:52Z | [
"python",
"html",
"django",
"colors"
] |
HTML Newbie Question: Colored Background for Characters in Django HttpResponse | 868,871 | <p>I would like to generate an HttpResponse that contains a certain string. For each of the characters in the string I have a background color I want to use. </p>
<p>For simplification, let's assume I can only have shades of green in the background, and that the "background colors" data represents "level of brightness... | 1 | 2009-05-15T14:04:30Z | 869,031 | <p>you can use something like this to generate html in the django view itself
and return it as text/html</p>
<pre><code>data = "abcd"
greenShades = [0.0, 1.0, 0.5, 1.0]
out = "<html>"
for d, clrG in zip(data,greenShades):
out +=""" <div style="background-color:RGB(0,%s,0);color:white;">%s</div> ... | 2 | 2009-05-15T14:30:08Z | [
"python",
"html",
"django",
"colors"
] |
HTML Newbie Question: Colored Background for Characters in Django HttpResponse | 868,871 | <p>I would like to generate an HttpResponse that contains a certain string. For each of the characters in the string I have a background color I want to use. </p>
<p>For simplification, let's assume I can only have shades of green in the background, and that the "background colors" data represents "level of brightness... | 1 | 2009-05-15T14:04:30Z | 869,071 | <p>Your best bet here would be to use the <code>span</code> element, as well as a stylesheet. If you don't want to use a template, then you'd have to render this inline. An example: </p>
<pre><code>string_data = 'asdf'
color_data = [0.0, 1.0, 0.5, 1.0]
response = []
for char, color in zip(string_data, color_data):
... | 1 | 2009-05-15T14:35:16Z | [
"python",
"html",
"django",
"colors"
] |
cx_oracle and oracle 7? | 868,888 | <p>At work we have Oracle 7. I would like to use python to access the DB.
Has anyone done that or knows how to do it?
I have Windows XP, Python 2.6 and the cx_oracle version for python 2.6</p>
<p>However, when I try to import cx_oracle i get the following error:</p>
<pre><code>ImportError: DLL load failed the module ... | 4 | 2009-05-15T14:09:08Z | 896,416 | <p>cx_Oracle is currently only being provided with linkage to the 9i, 10g, and 11i clients. Install one of these clients and configure it to connect to the Oracle 7 database using the proper ORACLE_SID.</p>
| 2 | 2009-05-22T04:58:09Z | [
"python",
"cx-oracle"
] |
cx_oracle and oracle 7? | 868,888 | <p>At work we have Oracle 7. I would like to use python to access the DB.
Has anyone done that or knows how to do it?
I have Windows XP, Python 2.6 and the cx_oracle version for python 2.6</p>
<p>However, when I try to import cx_oracle i get the following error:</p>
<pre><code>ImportError: DLL load failed the module ... | 4 | 2009-05-15T14:09:08Z | 896,470 | <p>I was running into that same problem at work. I finally dropped trying to use cx_Oracle and went with <a href="http://adodbapi.sourceforge.net/" rel="nofollow">adodbapi</a>. It worked with Oracle 8.</p>
| 0 | 2009-05-22T05:20:45Z | [
"python",
"cx-oracle"
] |
cx_oracle and oracle 7? | 868,888 | <p>At work we have Oracle 7. I would like to use python to access the DB.
Has anyone done that or knows how to do it?
I have Windows XP, Python 2.6 and the cx_oracle version for python 2.6</p>
<p>However, when I try to import cx_oracle i get the following error:</p>
<pre><code>ImportError: DLL load failed the module ... | 4 | 2009-05-15T14:09:08Z | 906,577 | <p>If you have ODBC configured then you can use it. It is available with ActivePython or as win32 extensions. You will obtain connection with:</p>
<pre><code>connection = odbc.odbc('db_alias/user/passwd')
</code></pre>
<p>Optionally you can use Jython and thin JDBC client. Instalation of client is not required. With ... | 0 | 2009-05-25T12:39:19Z | [
"python",
"cx-oracle"
] |
cx_oracle and oracle 7? | 868,888 | <p>At work we have Oracle 7. I would like to use python to access the DB.
Has anyone done that or knows how to do it?
I have Windows XP, Python 2.6 and the cx_oracle version for python 2.6</p>
<p>However, when I try to import cx_oracle i get the following error:</p>
<pre><code>ImportError: DLL load failed the module ... | 4 | 2009-05-15T14:09:08Z | 9,177,179 | <p>Make sure you have the location of the oracle .dll (o files set in your PATH environment variable. The location containing oci.dll should suffice.</p>
| 2 | 2012-02-07T13:34:34Z | [
"python",
"cx-oracle"
] |
Why is looping over range() in Python faster than using a while loop? | 869,229 | <p>The other day I was doing some Python benchmarking and I came across something interesting. Below are two loops that do more or less the same thing. Loop 1 takes about twice as long as loop 2 to execute.</p>
<p>Loop 1:</p>
<pre><code>int i = 0
while i < 100000000:
i += 1
</code></pre>
<p>Loop 2:</p>
<pre>... | 49 | 2009-05-15T15:06:41Z | 869,274 | <p>Because you are running more often in code written in C in the interpretor. i.e. i+=1 is in Python, so slow (comparatively), whereas range(0,...) is one C call the for loop will execute mostly in C too.</p>
| 3 | 2009-05-15T15:15:04Z | [
"python",
"performance",
"benchmarking"
] |
Why is looping over range() in Python faster than using a while loop? | 869,229 | <p>The other day I was doing some Python benchmarking and I came across something interesting. Below are two loops that do more or less the same thing. Loop 1 takes about twice as long as loop 2 to execute.</p>
<p>Loop 1:</p>
<pre><code>int i = 0
while i < 100000000:
i += 1
</code></pre>
<p>Loop 2:</p>
<pre>... | 49 | 2009-05-15T15:06:41Z | 869,295 | <p><code>range()</code> is implemented in C, whereas <code>i += 1</code> is interpreted.</p>
<p>Using <code>xrange()</code> could make it even faster for large numbers. Starting with Python 3.0 <code>range()</code> is the same as previously <code>xrange()</code>.</p>
| 22 | 2009-05-15T15:18:02Z | [
"python",
"performance",
"benchmarking"
] |
Why is looping over range() in Python faster than using a while loop? | 869,229 | <p>The other day I was doing some Python benchmarking and I came across something interesting. Below are two loops that do more or less the same thing. Loop 1 takes about twice as long as loop 2 to execute.</p>
<p>Loop 1:</p>
<pre><code>int i = 0
while i < 100000000:
i += 1
</code></pre>
<p>Loop 2:</p>
<pre>... | 49 | 2009-05-15T15:06:41Z | 869,347 | <p>see the disassembly of python byte code, you may get a more concrete idea</p>
<p>use while loop:</p>
<pre><code>1 0 LOAD_CONST 0 (0)
3 STORE_NAME 0 (i)
2 6 SETUP_LOOP 28 (to 37)
>> 9 LOAD_NAME 0 (i) ... | 93 | 2009-05-15T15:27:07Z | [
"python",
"performance",
"benchmarking"
] |
Why is looping over range() in Python faster than using a while loop? | 869,229 | <p>The other day I was doing some Python benchmarking and I came across something interesting. Below are two loops that do more or less the same thing. Loop 1 takes about twice as long as loop 2 to execute.</p>
<p>Loop 1:</p>
<pre><code>int i = 0
while i < 100000000:
i += 1
</code></pre>
<p>Loop 2:</p>
<pre>... | 49 | 2009-05-15T15:06:41Z | 869,414 | <p>Most of Python's built in method calls are run as C code. Code that has to be interpreted is much slower. In terms of memory efficiency and execution speed the difference is gigantic. The python internals have been optimized to the extreme, and it's best to take advantage of those optimizations. </p>
| 1 | 2009-05-15T15:39:43Z | [
"python",
"performance",
"benchmarking"
] |
Why is looping over range() in Python faster than using a while loop? | 869,229 | <p>The other day I was doing some Python benchmarking and I came across something interesting. Below are two loops that do more or less the same thing. Loop 1 takes about twice as long as loop 2 to execute.</p>
<p>Loop 1:</p>
<pre><code>int i = 0
while i < 100000000:
i += 1
</code></pre>
<p>Loop 2:</p>
<pre>... | 49 | 2009-05-15T15:06:41Z | 16,072,743 | <p>It must be said that there is a lot of object creation and destruction going on with the while loop.</p>
<pre><code>i += 1
</code></pre>
<p>is the same as:</p>
<pre><code>i = i + 1
</code></pre>
<p>But because Python ints are immutable, it doesn't modify the existing object; rather it creates a brand new object ... | 3 | 2013-04-18T00:54:44Z | [
"python",
"performance",
"benchmarking"
] |
Running unittest.main() from a module? | 869,519 | <p>I wrote a little function that dynamically defines unittest.TestCase classes (trivial version below).</p>
<p>When I moved it out of the same source file into its own module, I can't figure out how to get unittest to discover the new classes. Calling unittest.main() from either file doesn't execute any tests.</p>
<... | 1 | 2009-05-15T15:57:58Z | 869,671 | <p>The general idea (what unittest.main does for you) is:</p>
<pre><code>suite = unittest.TestLoader().loadTestsFromTestCase(SomeTestCase)
unittest.TextTestRunner(verbosity=2).run(suite)
</code></pre>
<p>as per <a href="http://docs.python.org/library/unittest.html?highlight=unittest#module-unittest">http://docs.pytho... | 8 | 2009-05-15T16:31:53Z | [
"python",
"unit-testing"
] |
Running unittest.main() from a module? | 869,519 | <p>I wrote a little function that dynamically defines unittest.TestCase classes (trivial version below).</p>
<p>When I moved it out of the same source file into its own module, I can't figure out how to get unittest to discover the new classes. Calling unittest.main() from either file doesn't execute any tests.</p>
<... | 1 | 2009-05-15T15:57:58Z | 869,770 | <p>By default, unittest.main() looks for unit TestCase objects in the main module. The test_factory creates the TestCase objects in its own module. That's why moving it outside of the main module causes the behavior you see.</p>
<p>Try:</p>
<pre><code>def finish():
unittest.main(module=__name__)
</code></pre>
| 6 | 2009-05-15T16:55:28Z | [
"python",
"unit-testing"
] |
How do I disassemble a Python script? | 869,586 | <p>Earlier today, I <a href="http://stackoverflow.com/questions/869229/why-is-looping-over-range-in-python-faster-than-using-a-while-loop">asked a question</a> about the way Python handles certain kinds of loops. One of the answers contained disassembled versions of my examples.</p>
<p>I'd like to know more. How can... | 9 | 2009-05-15T16:12:02Z | 869,600 | <p>Look at the <a href="http://docs.python.org/library/dis.html">dis</a> module:</p>
<pre><code>def myfunc(alist):
return len(alist)
>>> dis.dis(myfunc)
2 0 LOAD_GLOBAL 0 (len)
3 LOAD_FAST 0 (alist)
6 CALL_FUNCTION 1
... | 12 | 2009-05-15T16:14:49Z | [
"python",
"debugging",
"reverse-engineering"
] |
How do I disassemble a Python script? | 869,586 | <p>Earlier today, I <a href="http://stackoverflow.com/questions/869229/why-is-looping-over-range-in-python-faster-than-using-a-while-loop">asked a question</a> about the way Python handles certain kinds of loops. One of the answers contained disassembled versions of my examples.</p>
<p>I'd like to know more. How can... | 9 | 2009-05-15T16:12:02Z | 869,640 | <p>Use the <code>dis</code> module from the Python standard library (<code>import dis</code> e.g. in an interactive interpreter, then <code>dis.dis</code> any function you care about!-).</p>
| 2 | 2009-05-15T16:24:53Z | [
"python",
"debugging",
"reverse-engineering"
] |
How do I disassemble a Python script? | 869,586 | <p>Earlier today, I <a href="http://stackoverflow.com/questions/869229/why-is-looping-over-range-in-python-faster-than-using-a-while-loop">asked a question</a> about the way Python handles certain kinds of loops. One of the answers contained disassembled versions of my examples.</p>
<p>I'd like to know more. How can... | 9 | 2009-05-15T16:12:02Z | 869,970 | <p>Besides using <code>dis</code> as module, you can also run it as command line tool</p>
<p>For example, on windows you can run:</p>
<pre><code>c:\Python25\Lib\dis.py test.py
</code></pre>
<p>And it will output the disassembed result to console.</p>
| 2 | 2009-05-15T17:38:30Z | [
"python",
"debugging",
"reverse-engineering"
] |
Downloading file using post method and python | 869,679 | <p>I need a little help getting a tar file to download from a website. The website is set up as a form where you pick the file you want and click submit and then the download windows opens up for you to pick the location.</p>
<p>I'm trying to do the same thing in code (so I don't have to manual pick each file). So far... | 2 | 2009-05-15T16:33:32Z | 869,703 | <p>Append this:</p>
<pre><code>myfile = open('myfile.tar', 'wb')
shutil.copyfileobj(response.fp, myfile)
myfile.close()
</code></pre>
<p><code>response.fp</code> is a file-like object that you can read from, just like an open file. <code>shutil.copyfileobj()</code> is a simple function that reads from one file-like ... | 2 | 2009-05-15T16:38:53Z | [
"python",
"urllib2"
] |
Populating a list/array by index in Python? | 869,778 | <p>Is this possible:</p>
<pre><code>myList = []
myList[12] = 'a'
myList[22] = 'b'
myList[32] = 'c'
myList[42] = 'd'
</code></pre>
<p>When I try, I get:</p>
<pre><code># IndexError: list assignment index out of range #
</code></pre>
| 20 | 2009-05-15T16:57:25Z | 869,805 | <p>For a "sparse list" you could use a <code>dict</code> instead:</p>
<pre><code>mylist = {}
mylist[12] = 'a'
</code></pre>
<p>etc. If you want an actual list (initialize it with <code>[]</code>, <em>not</em> <code>()</code>, of course!-) you need to fill the un-set slots to _some_thing, e.g. <code>None</code>, by a... | 22 | 2009-05-15T17:01:13Z | [
"python",
"list"
] |
Populating a list/array by index in Python? | 869,778 | <p>Is this possible:</p>
<pre><code>myList = []
myList[12] = 'a'
myList[22] = 'b'
myList[32] = 'c'
myList[42] = 'd'
</code></pre>
<p>When I try, I get:</p>
<pre><code># IndexError: list assignment index out of range #
</code></pre>
| 20 | 2009-05-15T16:57:25Z | 869,818 | <p>You'll have to pre-fill it with something (e.g. <code>0</code> or <code>None</code>) before you can index it:</p>
<pre><code>myList = [None] * 100 # Create list of 100 'None's
myList[12] = 'a' # etc.
</code></pre>
<p>Alternatively, use a dict instead of a list, as <a href="http://stackoverflow.com/questions/8697... | 37 | 2009-05-15T17:03:29Z | [
"python",
"list"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.