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 -- Regex -- How to find a string between two sets of strings
849,912
<p>Consider the following:</p> <pre><code>&lt;div id=hotlinklist&gt; &lt;a href="foo1.com"&gt;Foo1&lt;/a&gt; &lt;div id=hotlink&gt; &lt;a href="/"&gt;Home&lt;/a&gt; &lt;/div&gt; &lt;div id=hotlink&gt; &lt;a href="/extract"&gt;Extract&lt;/a&gt; &lt;/div&gt; &lt;div id=hotlink&gt; &lt;a href="/sitemap"&gt;Sitemap&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>How would you go about taking out the sitemap line with regex in <strong>python</strong>?</p> <pre><code>&lt;a href="/sitemap"&gt;Sitemap&lt;/a&gt; </code></pre> <p>The following can be used to pull out the anchor tags.</p> <pre><code>'/&lt;a(.*?)a&gt;/i' </code></pre> <p>However, there are multiple anchor tags. Also there are multiple hotlink(s) so we can't really use them either?</p>
5
2009-05-11T20:23:49Z
850,003
<p>Use <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> or <a href="http://www.codespeak.net/lxml/" rel="nofollow">lxml</a> if you need to parse HTML.</p> <p>Also, what is it that you really need to do? Find the last link? Find the third link? Find the link that points to /sitemap? It's unclear from you question. What do you need to <em>do</em> with the data?</p> <p>If you really have to use regular expressions, have a look at <code>findall</code>.</p>
1
2009-05-11T20:43:23Z
[ "python", "regex", "string", "tags" ]
Python -- Regex -- How to find a string between two sets of strings
849,912
<p>Consider the following:</p> <pre><code>&lt;div id=hotlinklist&gt; &lt;a href="foo1.com"&gt;Foo1&lt;/a&gt; &lt;div id=hotlink&gt; &lt;a href="/"&gt;Home&lt;/a&gt; &lt;/div&gt; &lt;div id=hotlink&gt; &lt;a href="/extract"&gt;Extract&lt;/a&gt; &lt;/div&gt; &lt;div id=hotlink&gt; &lt;a href="/sitemap"&gt;Sitemap&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>How would you go about taking out the sitemap line with regex in <strong>python</strong>?</p> <pre><code>&lt;a href="/sitemap"&gt;Sitemap&lt;/a&gt; </code></pre> <p>The following can be used to pull out the anchor tags.</p> <pre><code>'/&lt;a(.*?)a&gt;/i' </code></pre> <p>However, there are multiple anchor tags. Also there are multiple hotlink(s) so we can't really use them either?</p>
5
2009-05-11T20:23:49Z
851,592
<p>In order to extract the contents of the tagline:</p> <pre><code> &lt;a href="/sitemap"&gt;Sitemap&lt;/a&gt; </code></pre> <p>... I would use:</p> <pre><code> &gt;&gt;&gt; import re &gt;&gt;&gt; s = ''' &lt;div id=hotlinklist&gt; &lt;a href="foo1.com"&gt;Foo1&lt;/a&gt; &lt;div id=hotlink&gt; &lt;a href="/"&gt;Home&lt;/a&gt; &lt;/div&gt; &lt;div id=hotlink&gt; &lt;a href="/extract"&gt;Extract&lt;/a&gt; &lt;/div&gt; &lt;div id=hotlink&gt; &lt;a href="/sitemap"&gt;Sitemap&lt;/a&gt; &lt;/div&gt; &lt;/div&gt;''' &gt;&gt;&gt; m = re.compile(r'&lt;a href="/sitemap"&gt;(.*?)&lt;/a&gt;').search(s) &gt;&gt;&gt; m.group(1) 'Sitemap' </code></pre>
4
2009-05-12T07:37:33Z
[ "python", "regex", "string", "tags" ]
What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django)
850,117
<p>I have a database table with a unique string field and a couple of integer fields. The string field is usually 10-100 characters long.</p> <p>Once every minute or so I have the following scenario: I receive a list of 2-10 thousand tuples corresponding to the table's record structure, e.g. </p> <pre><code>[("hello", 3, 4), ("cat", 5, 3), ...] </code></pre> <p>I need to insert all these tuples to the table (assume I verified neither of these strings appear in the database). For clarification, I'm using InnoDB, and I have an auto-incremental primary key for this table, the string is not the PK. </p> <p>My code currently iterates through this list, for each tuple creates a Python module object with the appropriate values, and calls ".save()", something like so:</p> <pre><code>@transaction.commit_on_success def save_data_elements(input_list): for (s, i1, i2) in input_list: entry = DataElement(string=s, number1=i1, number2=i2) entry.save() </code></pre> <p>This code is currently one of the performance bottlenecks in my system, so I'm looking for ways to optimize it. </p> <p>For example, I could generate SQL codes each containing an INSERT command for 100 tuples ("hard-coded" into the SQL) and execute it, but I don't know if it will improve anything.</p> <p>Do you have any suggestion to optimize such a process?</p> <p>Thanks</p>
11
2009-05-11T21:13:26Z
850,125
<p>what format do you receive? if it is a file, you can do some sort of bulk load: <a href="http://www.classes.cs.uchicago.edu/archive/2005/fall/23500-1/mysql-load.html" rel="nofollow">http://www.classes.cs.uchicago.edu/archive/2005/fall/23500-1/mysql-load.html</a></p>
1
2009-05-11T21:16:10Z
[ "python", "sql", "mysql", "django", "insert" ]
What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django)
850,117
<p>I have a database table with a unique string field and a couple of integer fields. The string field is usually 10-100 characters long.</p> <p>Once every minute or so I have the following scenario: I receive a list of 2-10 thousand tuples corresponding to the table's record structure, e.g. </p> <pre><code>[("hello", 3, 4), ("cat", 5, 3), ...] </code></pre> <p>I need to insert all these tuples to the table (assume I verified neither of these strings appear in the database). For clarification, I'm using InnoDB, and I have an auto-incremental primary key for this table, the string is not the PK. </p> <p>My code currently iterates through this list, for each tuple creates a Python module object with the appropriate values, and calls ".save()", something like so:</p> <pre><code>@transaction.commit_on_success def save_data_elements(input_list): for (s, i1, i2) in input_list: entry = DataElement(string=s, number1=i1, number2=i2) entry.save() </code></pre> <p>This code is currently one of the performance bottlenecks in my system, so I'm looking for ways to optimize it. </p> <p>For example, I could generate SQL codes each containing an INSERT command for 100 tuples ("hard-coded" into the SQL) and execute it, but I don't know if it will improve anything.</p> <p>Do you have any suggestion to optimize such a process?</p> <p>Thanks</p>
11
2009-05-11T21:13:26Z
850,127
<p>For MySQL specifically, the fastest way to load data is using <a href="http://dev.mysql.com/doc/refman/5.1/en/load-data.html" rel="nofollow">LOAD DATA INFILE</a>, so if you could convert the data into the format that expects, it'll probably be the fastest way to get it into the table.</p>
11
2009-05-11T21:16:21Z
[ "python", "sql", "mysql", "django", "insert" ]
What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django)
850,117
<p>I have a database table with a unique string field and a couple of integer fields. The string field is usually 10-100 characters long.</p> <p>Once every minute or so I have the following scenario: I receive a list of 2-10 thousand tuples corresponding to the table's record structure, e.g. </p> <pre><code>[("hello", 3, 4), ("cat", 5, 3), ...] </code></pre> <p>I need to insert all these tuples to the table (assume I verified neither of these strings appear in the database). For clarification, I'm using InnoDB, and I have an auto-incremental primary key for this table, the string is not the PK. </p> <p>My code currently iterates through this list, for each tuple creates a Python module object with the appropriate values, and calls ".save()", something like so:</p> <pre><code>@transaction.commit_on_success def save_data_elements(input_list): for (s, i1, i2) in input_list: entry = DataElement(string=s, number1=i1, number2=i2) entry.save() </code></pre> <p>This code is currently one of the performance bottlenecks in my system, so I'm looking for ways to optimize it. </p> <p>For example, I could generate SQL codes each containing an INSERT command for 100 tuples ("hard-coded" into the SQL) and execute it, but I don't know if it will improve anything.</p> <p>Do you have any suggestion to optimize such a process?</p> <p>Thanks</p>
11
2009-05-11T21:13:26Z
850,129
<p>You can write the rows to a file in the format "field1", "field2", .. and then use LOAD DATA to load them</p> <pre><code>data = '\n'.join(','.join('"%s"' % field for field in row) for row in data) f= open('data.txt', 'w') f.write(data) f.close() </code></pre> <p>Then execute this:</p> <pre><code>LOAD DATA INFILE 'data.txt' INTO TABLE db2.my_table; </code></pre> <p><a href="http://dev.mysql.com/doc/refman/5.1/en/load-data.html">Reference</a></p>
10
2009-05-11T21:16:29Z
[ "python", "sql", "mysql", "django", "insert" ]
What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django)
850,117
<p>I have a database table with a unique string field and a couple of integer fields. The string field is usually 10-100 characters long.</p> <p>Once every minute or so I have the following scenario: I receive a list of 2-10 thousand tuples corresponding to the table's record structure, e.g. </p> <pre><code>[("hello", 3, 4), ("cat", 5, 3), ...] </code></pre> <p>I need to insert all these tuples to the table (assume I verified neither of these strings appear in the database). For clarification, I'm using InnoDB, and I have an auto-incremental primary key for this table, the string is not the PK. </p> <p>My code currently iterates through this list, for each tuple creates a Python module object with the appropriate values, and calls ".save()", something like so:</p> <pre><code>@transaction.commit_on_success def save_data_elements(input_list): for (s, i1, i2) in input_list: entry = DataElement(string=s, number1=i1, number2=i2) entry.save() </code></pre> <p>This code is currently one of the performance bottlenecks in my system, so I'm looking for ways to optimize it. </p> <p>For example, I could generate SQL codes each containing an INSERT command for 100 tuples ("hard-coded" into the SQL) and execute it, but I don't know if it will improve anything.</p> <p>Do you have any suggestion to optimize such a process?</p> <p>Thanks</p>
11
2009-05-11T21:13:26Z
850,273
<p>If you don't <code>LOAD DATA INFILE</code> as some of the other suggestions mention, two things you can do to speed up your inserts are :</p> <ol> <li>Use prepared statements - this cuts out the overhead of parsing the SQL for every insert</li> <li>Do all of your inserts in a single transaction - this would require using a DB engine that supports transactions (like InnoDB)</li> </ol>
4
2009-05-11T21:51:33Z
[ "python", "sql", "mysql", "django", "insert" ]
What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django)
850,117
<p>I have a database table with a unique string field and a couple of integer fields. The string field is usually 10-100 characters long.</p> <p>Once every minute or so I have the following scenario: I receive a list of 2-10 thousand tuples corresponding to the table's record structure, e.g. </p> <pre><code>[("hello", 3, 4), ("cat", 5, 3), ...] </code></pre> <p>I need to insert all these tuples to the table (assume I verified neither of these strings appear in the database). For clarification, I'm using InnoDB, and I have an auto-incremental primary key for this table, the string is not the PK. </p> <p>My code currently iterates through this list, for each tuple creates a Python module object with the appropriate values, and calls ".save()", something like so:</p> <pre><code>@transaction.commit_on_success def save_data_elements(input_list): for (s, i1, i2) in input_list: entry = DataElement(string=s, number1=i1, number2=i2) entry.save() </code></pre> <p>This code is currently one of the performance bottlenecks in my system, so I'm looking for ways to optimize it. </p> <p>For example, I could generate SQL codes each containing an INSERT command for 100 tuples ("hard-coded" into the SQL) and execute it, but I don't know if it will improve anything.</p> <p>Do you have any suggestion to optimize such a process?</p> <p>Thanks</p>
11
2009-05-11T21:13:26Z
850,723
<p>If you can do a hand-rolled <code>INSERT</code> statement, then that's the way I'd go. A single <code>INSERT</code> statement with multiple value clauses is much much faster than lots of individual <code>INSERT</code> statements.</p>
4
2009-05-12T01:08:52Z
[ "python", "sql", "mysql", "django", "insert" ]
What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django)
850,117
<p>I have a database table with a unique string field and a couple of integer fields. The string field is usually 10-100 characters long.</p> <p>Once every minute or so I have the following scenario: I receive a list of 2-10 thousand tuples corresponding to the table's record structure, e.g. </p> <pre><code>[("hello", 3, 4), ("cat", 5, 3), ...] </code></pre> <p>I need to insert all these tuples to the table (assume I verified neither of these strings appear in the database). For clarification, I'm using InnoDB, and I have an auto-incremental primary key for this table, the string is not the PK. </p> <p>My code currently iterates through this list, for each tuple creates a Python module object with the appropriate values, and calls ".save()", something like so:</p> <pre><code>@transaction.commit_on_success def save_data_elements(input_list): for (s, i1, i2) in input_list: entry = DataElement(string=s, number1=i1, number2=i2) entry.save() </code></pre> <p>This code is currently one of the performance bottlenecks in my system, so I'm looking for ways to optimize it. </p> <p>For example, I could generate SQL codes each containing an INSERT command for 100 tuples ("hard-coded" into the SQL) and execute it, but I don't know if it will improve anything.</p> <p>Do you have any suggestion to optimize such a process?</p> <p>Thanks</p>
11
2009-05-11T21:13:26Z
850,886
<p>This is unrelated to the actual load of data into the DB, but...</p> <p>If providing a "The data is loading... The load will be done shortly" type of message to the user is an option, then you can run the INSERTs or LOAD DATA asynchronously in a different thread.</p> <p>Just something else to consider.</p>
1
2009-05-12T02:23:39Z
[ "python", "sql", "mysql", "django", "insert" ]
What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django)
850,117
<p>I have a database table with a unique string field and a couple of integer fields. The string field is usually 10-100 characters long.</p> <p>Once every minute or so I have the following scenario: I receive a list of 2-10 thousand tuples corresponding to the table's record structure, e.g. </p> <pre><code>[("hello", 3, 4), ("cat", 5, 3), ...] </code></pre> <p>I need to insert all these tuples to the table (assume I verified neither of these strings appear in the database). For clarification, I'm using InnoDB, and I have an auto-incremental primary key for this table, the string is not the PK. </p> <p>My code currently iterates through this list, for each tuple creates a Python module object with the appropriate values, and calls ".save()", something like so:</p> <pre><code>@transaction.commit_on_success def save_data_elements(input_list): for (s, i1, i2) in input_list: entry = DataElement(string=s, number1=i1, number2=i2) entry.save() </code></pre> <p>This code is currently one of the performance bottlenecks in my system, so I'm looking for ways to optimize it. </p> <p>For example, I could generate SQL codes each containing an INSERT command for 100 tuples ("hard-coded" into the SQL) and execute it, but I don't know if it will improve anything.</p> <p>Do you have any suggestion to optimize such a process?</p> <p>Thanks</p>
11
2009-05-11T21:13:26Z
851,443
<p>Regardless of the insert method, you will want to use the InnoDB engine for maximum read/write concurrency. MyISAM will lock the entire table for the duration of the insert whereas InnoDB (under most circumstances) will only lock the affected rows, allowing SELECT statements to proceed.</p>
2
2009-05-12T06:38:43Z
[ "python", "sql", "mysql", "django", "insert" ]
What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django)
850,117
<p>I have a database table with a unique string field and a couple of integer fields. The string field is usually 10-100 characters long.</p> <p>Once every minute or so I have the following scenario: I receive a list of 2-10 thousand tuples corresponding to the table's record structure, e.g. </p> <pre><code>[("hello", 3, 4), ("cat", 5, 3), ...] </code></pre> <p>I need to insert all these tuples to the table (assume I verified neither of these strings appear in the database). For clarification, I'm using InnoDB, and I have an auto-incremental primary key for this table, the string is not the PK. </p> <p>My code currently iterates through this list, for each tuple creates a Python module object with the appropriate values, and calls ".save()", something like so:</p> <pre><code>@transaction.commit_on_success def save_data_elements(input_list): for (s, i1, i2) in input_list: entry = DataElement(string=s, number1=i1, number2=i2) entry.save() </code></pre> <p>This code is currently one of the performance bottlenecks in my system, so I'm looking for ways to optimize it. </p> <p>For example, I could generate SQL codes each containing an INSERT command for 100 tuples ("hard-coded" into the SQL) and execute it, but I don't know if it will improve anything.</p> <p>Do you have any suggestion to optimize such a process?</p> <p>Thanks</p>
11
2009-05-11T21:13:26Z
851,898
<p>I donot know the exact details, but u can use json style data representation and use it as fixtures or something. I saw something similar on Django Video Workshop by Douglas Napoleone. See the videos at <a href="http://www.linux-magazine.com/online/news/django%5Fvideo%5Fworkshop" rel="nofollow">http://www.linux-magazine.com/online/news/django_video_workshop</a>. and <a href="http://www.linux-magazine.com/online/features/django%5Freloaded%5Fworkshop%5Fpart%5F1" rel="nofollow">http://www.linux-magazine.com/online/features/django_reloaded_workshop_part_1</a>. Hope this one helps.</p> <p>Hope you can work it out. I just started learning django, so I can just point you to resources.</p>
1
2009-05-12T09:14:03Z
[ "python", "sql", "mysql", "django", "insert" ]
Python multiprocessing on Python 2.6 Win32 (xp)
850,424
<p>I tried to copy this example from this Multiprocessing lecture by jesse noller (as recommended in another SO post)[<a href="http://pycon.blip.tv/file/1947354?filename=Pycon-IntroductionToMultiprocessingInPython630.mp4" rel="nofollow">http://pycon.blip.tv/file/1947354?filename=Pycon-IntroductionToMultiprocessingInPython630.mp4</a>]</p> <p>But for some reason I'm getting an error, as though it's ignoring my function definitions: I'm on Windows XP (win32) <strong>which I know has restrictions with regards to the multiprocessing library in 2.6 that requires everything be pickleable</strong></p> <pre><code>from multiprocessing import Process import time def sleeper(wait): print 'Sleeping for %d seconds' % (wait,) time.sleep(wait) print 'Sleeping complete' def doIT(): p = Process(target=sleeper, args=(9,)) p.start() time.sleep(5) p.join() if __name__ == '__main__': doIT() </code></pre> <p>Output:</p> <pre><code>Evaluating mypikklez.py Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Python26\lib\multiprocessing\forking.py", line 342, in main self = load(from_parent) File "C:\Python26\lib\pickle.py", line 1370, in load return Unpickler(file).load() File "C:\Python26\lib\pickle.py", line 858, in load dispatch[key](self) File "C:\Python26\lib\pickle.py", line 1090, in load_global klass = self.find_class(module, name) File "C:\Python26\lib\pickle.py", line 1126, in find_class klass = getattr(mod, name) AttributeError: 'module' object has no attribute 'sleeper' </code></pre> <p>The error causing the issue is : AttributeError: 'module' object has no attribute 'sleeper'</p> <p>As simple of a function as it is I can't understand what would be the hold up.</p> <p>This is just for self-teaching purposes of basic concepts. I'm not trying to pre-optimize any real world issue.</p> <p>Thanks.</p>
2
2009-05-11T22:46:37Z
850,440
<p>Seems from the traceback that you are running the code directly into the python interpreter (REPL).</p> <p>Don't do that. Save the code in a file and run it from the file instead, with the command:</p> <pre><code>python myfile.py </code></pre> <p>That will solve your issue.</p> <p><hr /></p> <p>As an unrelated note, this line is wrong:</p> <pre><code>print 'Sleeping for ' + wait + ' seconds' </code></pre> <p>It should be:</p> <pre><code>print 'Sleeping for %d seconds' % (wait,) </code></pre> <p>Because you can't concatenate string and int objects (python is strongly typed)</p>
4
2009-05-11T22:50:49Z
[ "python", "winapi", "multiprocessing", "python-2.6" ]
Can a Python module use the imports from another file?
850,566
<p>I have something like this:</p> <pre><code> # a.py import os class A: ... # b.py import a class B(A): ... </code></pre> <p>In class B (b.py) I'd like to be able to use the modules imported in a.py (os in this case). Is it possible to achieve this behavior in Python or should I import the modules in both files?</p> <p>Edit: I'm not worried about the import times, my problem is the visual clutter that the block of imports puts on the files. I end up having stuff like this in every controller (RequestHandler):</p> <pre><code> from django.utils import simplejson from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext import db </code></pre> <p>That's what I'd like to avoid.</p>
3
2009-05-11T23:48:29Z
850,573
<p>You should import it separately. However, if you really need to forward some functionality, you can return a module from a function. Just:</p> <pre><code>import os def x: return os </code></pre> <p>But it seems like a plugin functionality - objects + inheritance would solve that case a bit better.</p>
0
2009-05-11T23:52:56Z
[ "python" ]
Can a Python module use the imports from another file?
850,566
<p>I have something like this:</p> <pre><code> # a.py import os class A: ... # b.py import a class B(A): ... </code></pre> <p>In class B (b.py) I'd like to be able to use the modules imported in a.py (os in this case). Is it possible to achieve this behavior in Python or should I import the modules in both files?</p> <p>Edit: I'm not worried about the import times, my problem is the visual clutter that the block of imports puts on the files. I end up having stuff like this in every controller (RequestHandler):</p> <pre><code> from django.utils import simplejson from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext import db </code></pre> <p>That's what I'd like to avoid.</p>
3
2009-05-11T23:48:29Z
850,583
<p>Sounds like you are wanting to use <a href="http://docs.python.org/tutorial/modules.html#packages" rel="nofollow">python packages</a>. Look into those.</p>
0
2009-05-11T23:56:47Z
[ "python" ]
Can a Python module use the imports from another file?
850,566
<p>I have something like this:</p> <pre><code> # a.py import os class A: ... # b.py import a class B(A): ... </code></pre> <p>In class B (b.py) I'd like to be able to use the modules imported in a.py (os in this case). Is it possible to achieve this behavior in Python or should I import the modules in both files?</p> <p>Edit: I'm not worried about the import times, my problem is the visual clutter that the block of imports puts on the files. I end up having stuff like this in every controller (RequestHandler):</p> <pre><code> from django.utils import simplejson from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext import db </code></pre> <p>That's what I'd like to avoid.</p>
3
2009-05-11T23:48:29Z
850,595
<p>Just import the modules again.</p> <p>Importing a module in python is a very lightweight operation. The first time you import a module, python will load the module and execute the code in it. On any subsequent imports, you will just get a reference to the already-imported module.</p> <p>You can verify this yourself, if you like:</p> <pre><code># module_a.py class A(object): pass print 'A imported' # module_b.py import module_a class B(object): pass print 'B imported' # at the interactive prompt &gt;&gt;&gt; import module_a A imported &gt;&gt;&gt; import module_a # notice nothing prints out this time &gt;&gt;&gt; import module_b # notice we get the print from B, but not from A B imported &gt;&gt;&gt; </code></pre>
1
2009-05-12T00:01:39Z
[ "python" ]
Can a Python module use the imports from another file?
850,566
<p>I have something like this:</p> <pre><code> # a.py import os class A: ... # b.py import a class B(A): ... </code></pre> <p>In class B (b.py) I'd like to be able to use the modules imported in a.py (os in this case). Is it possible to achieve this behavior in Python or should I import the modules in both files?</p> <p>Edit: I'm not worried about the import times, my problem is the visual clutter that the block of imports puts on the files. I end up having stuff like this in every controller (RequestHandler):</p> <pre><code> from django.utils import simplejson from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext import db </code></pre> <p>That's what I'd like to avoid.</p>
3
2009-05-11T23:48:29Z
850,601
<p>Yep. Once you import a module, that module becomes a property of the current module.</p> <pre><code># a.py class A(object): ... # b.py import a class B(a.A): ... </code></pre> <p>In Django, for example, many of the packages simply import the contents of other modules. Classes and functions are defined in separate files just for the separation:</p> <pre><code># django/db/models/fields/__init__.py class Field(object): ... class TextField(Field): ... # django/db/models/__init__.py from django.db.models.fields import * # mydjangoproject/myapp/models.py from django.db import models class MyModel(models.Model): myfield = models.TextField(...) .... </code></pre>
0
2009-05-12T00:05:07Z
[ "python" ]
Can a Python module use the imports from another file?
850,566
<p>I have something like this:</p> <pre><code> # a.py import os class A: ... # b.py import a class B(A): ... </code></pre> <p>In class B (b.py) I'd like to be able to use the modules imported in a.py (os in this case). Is it possible to achieve this behavior in Python or should I import the modules in both files?</p> <p>Edit: I'm not worried about the import times, my problem is the visual clutter that the block of imports puts on the files. I end up having stuff like this in every controller (RequestHandler):</p> <pre><code> from django.utils import simplejson from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext import db </code></pre> <p>That's what I'd like to avoid.</p>
3
2009-05-11T23:48:29Z
850,611
<p>Yes you can use the imports from the other file by going a.os.</p> <p>However, the pythonic way is to just import the exact modules you need without making a chain out of it (which can lead to circular references).</p> <p>When you import a module, the code is compiled and inserted into a dictionary of names -> module objects. The dictionary is located at sys.modules.</p> <pre><code>import sys sys.modules &gt;&gt;&gt; pprint.pprint(sys.modules) {'UserDict': &lt;module 'UserDict' from 'C:\python26\lib\UserDict.pyc'&gt;, '__builtin__': &lt;module '__builtin__' (built-in)&gt;, '__main__': &lt;module '__main__' (built-in)&gt;, '_abcoll': &lt;module '_abcoll' from 'C:\python26\lib\_abcoll.pyc'&gt;, # the rest omitted for brevity </code></pre> <p>When you try to import the module again, Python will check the dictionary to see if its already there. If it is, it will return the already compiled module object to you. Otherwise, it will compile the code, and insert it in sys.modules.</p> <p>Since dictionaries are implemented as hash tables, this lookup is very quick and takes up negligible time compared to the risk of creating circular references.</p> <blockquote> <p>Edit: I'm not worried about the import times, my problem is the visual clutter that the block of imports puts on the files.</p> </blockquote> <p>If you only have about 4 or 5 imports like that, its not too cluttery. Remember, "Explicit is better than implicit". However if it really bothers you that much, do this:</p> <pre><code>&lt;importheaders.py&gt; from django.utils import simplejson from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext import db &lt;mycontroller.py&gt; from importheaders import * </code></pre>
13
2009-05-12T00:11:58Z
[ "python" ]
Can a Python module use the imports from another file?
850,566
<p>I have something like this:</p> <pre><code> # a.py import os class A: ... # b.py import a class B(A): ... </code></pre> <p>In class B (b.py) I'd like to be able to use the modules imported in a.py (os in this case). Is it possible to achieve this behavior in Python or should I import the modules in both files?</p> <p>Edit: I'm not worried about the import times, my problem is the visual clutter that the block of imports puts on the files. I end up having stuff like this in every controller (RequestHandler):</p> <pre><code> from django.utils import simplejson from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext import db </code></pre> <p>That's what I'd like to avoid.</p>
3
2009-05-11T23:48:29Z
850,680
<p>First you can shorten it to:</p> <pre><code>from django.utils import simplejson from google.appengine.ext import webapp, db from webapp import template </code></pre> <p>Secondly suppose you have those ^ imports in my_module.py</p> <p>In my_module2.py you can do:</p> <p>from my_module2.py import webapp, db, tempate</p> <p>example:</p> <pre><code>In [5]: from my_module2 import MyMath2, MyMath In [6]: m2 = MyMath2() In [7]: m2.my_cos(3) Out[7]: 0.94398413915231416 In [8]: m = MyMath() In [9]: m.my_sin(3) Out[9]: 0.32999082567378202 </code></pre> <p>where my_module2 is:</p> <pre><code>from my_module import math, MyMath class MyMath2(object): the_meaning_of_life = 42 def my_cos(self, number): return math.cos(number * 42) </code></pre> <p>and my_module1 is:</p> <pre><code>import math class MyMath(object): some_number = 42 def my_sin(self, num): return math.sin(num * self.some_number) </code></pre> <p>Cheers, Hope it helps AleP</p>
0
2009-05-12T00:45:11Z
[ "python" ]
Python *.py, *.pyo, *.pyc: Which can be eliminated for an Embedded System?
850,630
<p>To squeeze into the limited amount of filesystem storage available in an embedded system I'm currently playing with, I would like to eliminate any files that could reasonably be removed without significantly impacting functionality or performance. The *.py, *.pyo, and *.pyc files in the Python library account for a sizable amount of space, I'm wondering which of these options would be most reasonable for a Python 2.6 installation in a small embedded system:</p> <ol> <li>Keep *.py, eliminate *.pyc and *.pyo (Maintain ability to debug, performance suffers?)</li> <li>Keep *.py and *.pyc, eliminate *.pyo (Does optimization really buy anything?)</li> <li>Keep *.pyc, eliminate *.pyo and *.py (Will this work?)</li> <li>Keep *.py, *.pyc, and *.pyo (All are needed?)</li> </ol>
10
2009-05-12T00:18:59Z
850,642
<p>Number 3 should and will work. You do not need the .pyo or .py files in order to use the compiled python code.</p>
3
2009-05-12T00:25:38Z
[ "python", "embedded" ]
Python *.py, *.pyo, *.pyc: Which can be eliminated for an Embedded System?
850,630
<p>To squeeze into the limited amount of filesystem storage available in an embedded system I'm currently playing with, I would like to eliminate any files that could reasonably be removed without significantly impacting functionality or performance. The *.py, *.pyo, and *.pyc files in the Python library account for a sizable amount of space, I'm wondering which of these options would be most reasonable for a Python 2.6 installation in a small embedded system:</p> <ol> <li>Keep *.py, eliminate *.pyc and *.pyo (Maintain ability to debug, performance suffers?)</li> <li>Keep *.py and *.pyc, eliminate *.pyo (Does optimization really buy anything?)</li> <li>Keep *.pyc, eliminate *.pyo and *.py (Will this work?)</li> <li>Keep *.py, *.pyc, and *.pyo (All are needed?)</li> </ol>
10
2009-05-12T00:18:59Z
850,646
<p><a href="http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html">http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html</a></p> <blockquote> <p>When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements.</p> <p>Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only <strong>doc</strong> strings are removed from the bytecode, resulting in more compact ‘.pyo’ files.</p> </blockquote> <p>My suggestion to you? </p> <p>Use -OO to compile only <strong>.pyo</strong> files if you don't need assert statements and __doc__ strings.</p> <p>Otherwise, go with <strong>.pyc</strong> only.</p> <p><strong>Edit</strong></p> <p>I noticed that you only mentioned the Python library. Much of the python library can be removed if you only need part of the functionality. </p> <p>I also suggest that you take a look at <a href="http://www.tinypy.org/">tinypy</a> which is large subset of Python in about 64kb.</p>
13
2009-05-12T00:27:43Z
[ "python", "embedded" ]
Python *.py, *.pyo, *.pyc: Which can be eliminated for an Embedded System?
850,630
<p>To squeeze into the limited amount of filesystem storage available in an embedded system I'm currently playing with, I would like to eliminate any files that could reasonably be removed without significantly impacting functionality or performance. The *.py, *.pyo, and *.pyc files in the Python library account for a sizable amount of space, I'm wondering which of these options would be most reasonable for a Python 2.6 installation in a small embedded system:</p> <ol> <li>Keep *.py, eliminate *.pyc and *.pyo (Maintain ability to debug, performance suffers?)</li> <li>Keep *.py and *.pyc, eliminate *.pyo (Does optimization really buy anything?)</li> <li>Keep *.pyc, eliminate *.pyo and *.py (Will this work?)</li> <li>Keep *.py, *.pyc, and *.pyo (All are needed?)</li> </ol>
10
2009-05-12T00:18:59Z
850,690
<p>What it ultimately boils down to is that you really only need one of the three options, but your best bet is to go with .pys and either .pyos or .pycs.</p> <p>Here's how I see each of your options:</p> <ol> <li>If you put the .pys in a zip file, you won't see pycs or pyos built. It should also be pointed out that the performance difference is only in startup time, and even then isn't too great in my experience (your milage may vary though). Also note that there is a way to prevent the interpreter from outputting .pycs as <a href="http://stackoverflow.com/questions/850630/python-py-pyo-pyc-which-can-be-eliminated-for-an-embedded-system/851194#851194">Algorias</a> points out.</li> <li>I think that this is an ideal option (either that or .pys and .pyos) because you get the best mix of performance, debuggability and reliability. You don't necessarily <em>need</em> a source file and compiled file though.</li> <li>If you're really strapped for space and need performance, this will work. I'd advise you to keep the .pys if at all possible though. Compiled binaries (.pycs or .pyos) don't always transfer to different versions of python.</li> <li>It's doubtful that you'll need all three unless you plan on running in optimized mode sometimes and non-optimized mode sometimes.</li> </ol> <p>In terms of space it's been my (very anecdotal) experience that .py files compress the best compared to .pycs and .pyos if you put them in a zipfile. If you plan on compressing the files, .pyos don't tend to gain a lot in terms of sheer space because docstrings tend to compress fairly well and asserts just don't take up that much space.</p>
1
2009-05-12T00:50:04Z
[ "python", "embedded" ]
Python *.py, *.pyo, *.pyc: Which can be eliminated for an Embedded System?
850,630
<p>To squeeze into the limited amount of filesystem storage available in an embedded system I'm currently playing with, I would like to eliminate any files that could reasonably be removed without significantly impacting functionality or performance. The *.py, *.pyo, and *.pyc files in the Python library account for a sizable amount of space, I'm wondering which of these options would be most reasonable for a Python 2.6 installation in a small embedded system:</p> <ol> <li>Keep *.py, eliminate *.pyc and *.pyo (Maintain ability to debug, performance suffers?)</li> <li>Keep *.py and *.pyc, eliminate *.pyo (Does optimization really buy anything?)</li> <li>Keep *.pyc, eliminate *.pyo and *.py (Will this work?)</li> <li>Keep *.py, *.pyc, and *.pyo (All are needed?)</li> </ol>
10
2009-05-12T00:18:59Z
851,194
<p>I would recommend keeping only .py files. The difference in startup time isn't that great, and having the source around is a plus, as it will run under different python versions without any issues.</p> <p>As of python 2.6, setting sys.dont_write_bytecode to True will suppress compilation of .pyc and .pyo files altogether, so you may want to use that option if you have 2.6 available.</p>
2
2009-05-12T04:54:30Z
[ "python", "embedded" ]
Python *.py, *.pyo, *.pyc: Which can be eliminated for an Embedded System?
850,630
<p>To squeeze into the limited amount of filesystem storage available in an embedded system I'm currently playing with, I would like to eliminate any files that could reasonably be removed without significantly impacting functionality or performance. The *.py, *.pyo, and *.pyc files in the Python library account for a sizable amount of space, I'm wondering which of these options would be most reasonable for a Python 2.6 installation in a small embedded system:</p> <ol> <li>Keep *.py, eliminate *.pyc and *.pyo (Maintain ability to debug, performance suffers?)</li> <li>Keep *.py and *.pyc, eliminate *.pyo (Does optimization really buy anything?)</li> <li>Keep *.pyc, eliminate *.pyo and *.py (Will this work?)</li> <li>Keep *.py, *.pyc, and *.pyo (All are needed?)</li> </ol>
10
2009-05-12T00:18:59Z
25,644,162
<p>Here's how I minimize disk requirements for mainline Python 2.7 at the day job:</p> <p>1) Remove packages from the standard library which you won't need. The following is a conservative list:</p> <pre><code>bsddb/test ctypes/test distutils/tests email/test idlelib lib-tk lib2to3 pydoc.py tabnanny.py test unittest </code></pre> <p>Note that some Python code may have surprising dependencies; e.g. <code>setuptools</code> needs <code>unittest</code> to run.</p> <p>2) Pre-compile all Python code, using -OO to strip asserts and docstrings.</p> <pre><code>find -name '*.py' | python -OO -m py_compile - </code></pre> <p>Note that Python by default does not look at <code>.pyo</code> files; you have to explicitly ask for optimization at runtime as well, using an option or an environment variable. Run scripts in one of the following ways:</p> <pre><code>python -OO -m mylib.myscript PYTHONOPTIMIZE=2 python -m mylib.myscript </code></pre> <p>3) Remove <code>.py</code> source code files (unless you need to run them as scripts) and <code>.pyc</code> unoptimized files.</p> <pre><code>find '(' -name '*.py' -or -name '*.pyc' ')' -and -not -executable -execdir rm '{}' ';' </code></pre> <p>4) Compress the Python library files. Python can load modules from a zip file. The paths in the zip-file must match the package hierarchy; thus you should merge <code>site-packages</code> and <code>.egg</code> directories into the main library directory before zipping. (Or you can add multiple zip files to the Python path.)</p> <p>On Linux, Python's default path includes <code>/usr/lib/python27.zip</code> already, so just drop the zip file there and you're ready to go.</p> <p>Leave <code>os.pyo</code> as an ordinary (non-zipped) file, since Python looks for this as a sanity check. If you move it to the zip file, you'll get a warning on every Python invocation (though everything will still work). Or you can just leave an empty <code>os.py</code> file there, and put the real one in the zip file.</p> <p>Final notes:</p> <ul> <li>In this manner, Python fits in 7 MB of disk space. There's a lot more that can be done to reduce size, but 7 MB was small enough for my purposes. :)</li> <li>Python bytecode is not compatible across versions, but who cares when it's you who do the compilation and you who controls the Python version?</li> <li><code>.pyo</code> files in a zip file should be a performance win in all cases, unless the disk is extremely fast and the processor/RAM is extremely slow. Either way, Python executes from memory, not the on-disk format, so it only affects performance on load. Although the stripping of docstrings can save quite a bit of memory.</li> <li>Do note that <code>.pyo</code> files do not contain <code>assert</code> statements.</li> <li><code>.pyo</code> files preserve function names and line numbers, so debugability is not decreased: You still get nice tracebacks, you just have to manually go look up the line number in the source, which you'd have to do anyway.</li> <li>If you want to "hack" a file at runtime, just put it in the current working directory. It take precedence over the library zip file.</li> </ul>
1
2014-09-03T12:20:01Z
[ "python", "embedded" ]
Scope of Python Recursive Generators
850,725
<p>Hey all, I was working on a recursive generator to create the fixed integer partitions of a number and I was confused by a scoping issue.</p> <p>The code is similar to this snippet.</p> <pre><code>def testGen(a,n): if n &lt;= 1: print('yield', a) yield a else: for i in range(2): a[i] += n for j in testGen(a,n-i-1): yield j </code></pre> <p>My confusion is illustrated below.</p> <pre><code>&gt;&gt;&gt; list(testGen([1,2],4)) yield [10, 2] yield [10, 4] yield [10, 7] yield [12, 11] yield [12, 13] [[12, 13], [12, 13], [12, 13], [12, 13], [12, 13]] </code></pre> <p>I can get the right answer simply by using a copy of the array (e.g. passing in <code>a[:]</code> to the recursive call) but I still don't understand the above behavior. Why are the print statements and yield values different?</p>
2
2009-05-12T01:09:32Z
850,729
<p>I would guess you are mutating the array, so when you print it has a particular value, then the next time you print it has actually updated the value, and so on. At the end, you have 5 references to the same array, so of course you have the same value 5 times.</p>
2
2009-05-12T01:13:36Z
[ "python", "recursion", "scope", "generator" ]
Scope of Python Recursive Generators
850,725
<p>Hey all, I was working on a recursive generator to create the fixed integer partitions of a number and I was confused by a scoping issue.</p> <p>The code is similar to this snippet.</p> <pre><code>def testGen(a,n): if n &lt;= 1: print('yield', a) yield a else: for i in range(2): a[i] += n for j in testGen(a,n-i-1): yield j </code></pre> <p>My confusion is illustrated below.</p> <pre><code>&gt;&gt;&gt; list(testGen([1,2],4)) yield [10, 2] yield [10, 4] yield [10, 7] yield [12, 11] yield [12, 13] [[12, 13], [12, 13], [12, 13], [12, 13], [12, 13]] </code></pre> <p>I can get the right answer simply by using a copy of the array (e.g. passing in <code>a[:]</code> to the recursive call) but I still don't understand the above behavior. Why are the print statements and yield values different?</p>
2
2009-05-12T01:09:32Z
850,733
<p>The print statement displays the list at that particular point in time. Your code changes the list as you run it, so by the time you examine the list at the end, you see its value then.</p> <p>You can observe this by stepping through:</p> <pre><code>&gt;&gt;&gt; g = testGen([1,2],4) &gt;&gt;&gt; g.next() ('yield', [10, 2]) # note brackets in print statement because I'm on python 2.5 [10, 2] &gt;&gt;&gt; g.next() ('yield', [10, 4]) [10, 4] &gt;&gt;&gt; g.next() ('yield', [10, 7]) [10, 7] &gt;&gt;&gt; g.next() ('yield', [12, 11]) [12, 11] &gt;&gt;&gt; g.next() ('yield', [12, 13]) [12, 13] </code></pre>
2
2009-05-12T01:17:26Z
[ "python", "recursion", "scope", "generator" ]
Scope of Python Recursive Generators
850,725
<p>Hey all, I was working on a recursive generator to create the fixed integer partitions of a number and I was confused by a scoping issue.</p> <p>The code is similar to this snippet.</p> <pre><code>def testGen(a,n): if n &lt;= 1: print('yield', a) yield a else: for i in range(2): a[i] += n for j in testGen(a,n-i-1): yield j </code></pre> <p>My confusion is illustrated below.</p> <pre><code>&gt;&gt;&gt; list(testGen([1,2],4)) yield [10, 2] yield [10, 4] yield [10, 7] yield [12, 11] yield [12, 13] [[12, 13], [12, 13], [12, 13], [12, 13], [12, 13]] </code></pre> <p>I can get the right answer simply by using a copy of the array (e.g. passing in <code>a[:]</code> to the recursive call) but I still don't understand the above behavior. Why are the print statements and yield values different?</p>
2
2009-05-12T01:09:32Z
850,739
<p>The print and yield statements are different because you only have one print statement while you have 2 yields. Try this:</p> <pre><code>def testGen(a,n): if n &lt;= 1: print('yield', a) yield a else: for i in range(2): a[i] += n for j in testGen(a,n-i-1): print('yield', j) yield j &gt;&gt;&gt; list(testGen([1,2],4)) ('yield', [10, 2]) ('yield', [10, 2]) ('yield', [10, 2]) ('yield', [10, 2]) ('yield', [10, 4]) ('yield', [10, 4]) ('yield', [10, 4]) ('yield', [10, 4]) ('yield', [10, 7]) ('yield', [10, 7]) ('yield', [10, 7]) ('yield', [12, 11]) ('yield', [12, 11]) ('yield', [12, 11]) ('yield', [12, 13]) ('yield', [12, 13]) ('yield', [12, 13]) [[12, 13], [12, 13], [12, 13], [12, 13], [12, 13]] </code></pre> <p>You will see that the last yields are your answers because you've been passing around the same list instead of making a copy.</p>
0
2009-05-12T01:19:19Z
[ "python", "recursion", "scope", "generator" ]
Scope of Python Recursive Generators
850,725
<p>Hey all, I was working on a recursive generator to create the fixed integer partitions of a number and I was confused by a scoping issue.</p> <p>The code is similar to this snippet.</p> <pre><code>def testGen(a,n): if n &lt;= 1: print('yield', a) yield a else: for i in range(2): a[i] += n for j in testGen(a,n-i-1): yield j </code></pre> <p>My confusion is illustrated below.</p> <pre><code>&gt;&gt;&gt; list(testGen([1,2],4)) yield [10, 2] yield [10, 4] yield [10, 7] yield [12, 11] yield [12, 13] [[12, 13], [12, 13], [12, 13], [12, 13], [12, 13]] </code></pre> <p>I can get the right answer simply by using a copy of the array (e.g. passing in <code>a[:]</code> to the recursive call) but I still don't understand the above behavior. Why are the print statements and yield values different?</p>
2
2009-05-12T01:09:32Z
850,742
<p>Lists are mutable objects, if you pass in a list, and the generator performs in-place operations on that list, then finally all references to the list will point to the same list.</p>
2
2009-05-12T01:20:26Z
[ "python", "recursion", "scope", "generator" ]
Check whether a path exists on a remote host using paramiko
850,749
<p>Paramiko's <a href="http://www.metasnark.com/paramiko/docs/paramiko.SFTP-class.html">SFTPClient</a> apparently does not have an <code>exists</code> method. This is my current implementation:</p> <pre><code>def rexists(sftp, path): """os.path.exists for paramiko's SCP object """ try: sftp.stat(path) except IOError, e: if 'No such file' in str(e): return False raise else: return True </code></pre> <p>Is there a better way to do this? Checking for substring in Exception messages is pretty ugly and can be unreliable.</p>
9
2009-05-12T01:24:59Z
850,865
<p>There is no "exists" method defined for SFTP (not just paramiko), so your method is fine.</p> <p>I think checking the errno is a little cleaner:</p> <pre><code>def rexists(sftp, path): """os.path.exists for paramiko's SCP object """ try: sftp.stat(path) except IOError, e: if e[0] == 2: return False raise else: return True </code></pre>
5
2009-05-12T02:16:12Z
[ "python", "ssh", "scp", "paramiko" ]
Check whether a path exists on a remote host using paramiko
850,749
<p>Paramiko's <a href="http://www.metasnark.com/paramiko/docs/paramiko.SFTP-class.html">SFTPClient</a> apparently does not have an <code>exists</code> method. This is my current implementation:</p> <pre><code>def rexists(sftp, path): """os.path.exists for paramiko's SCP object """ try: sftp.stat(path) except IOError, e: if 'No such file' in str(e): return False raise else: return True </code></pre> <p>Is there a better way to do this? Checking for substring in Exception messages is pretty ugly and can be unreliable.</p>
9
2009-05-12T01:24:59Z
1,391,409
<p>See the <a href="http://docs.python.org/library/errno.html#errno.ENOENT"><code>errno</code> module</a> for constants defining all those error codes. Also, it's a bit clearer to use the <code>errno</code> attribute of the exception than the expansion of the <code>__init__</code> args, so I'd do this:</p> <pre><code>except IOError, e: # or "as" if you're using Python 3.0 if e.errno == errno.ENOENT: ... </code></pre>
15
2009-09-08T00:29:06Z
[ "python", "ssh", "scp", "paramiko" ]
Clearing Python lists
850,795
<p>Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python:</p> <pre><code>old_list = [] old_list = list() </code></pre> <p>The reason I ask is that I just saw this in some running code:</p> <pre><code>del old_list[ 0:len(old_list) ] </code></pre>
119
2009-05-12T01:46:55Z
850,831
<p>Clearing a list in place will affect all other references of the same list.</p> <p>For example, this method doesn't affect other references:</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; b = a &gt;&gt;&gt; a = [] &gt;&gt;&gt; print(a) [] &gt;&gt;&gt; print(b) [1, 2, 3] </code></pre> <p>But this one does:</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; b = a &gt;&gt;&gt; del a[:] # equivalent to del a[0:len(a)] &gt;&gt;&gt; print(a) [] &gt;&gt;&gt; print(b) [] &gt;&gt;&gt; a is b True </code></pre> <p>You could also do:</p> <pre><code>&gt;&gt;&gt; a[:] = [] </code></pre>
229
2009-05-12T02:03:16Z
[ "python" ]
Clearing Python lists
850,795
<p>Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python:</p> <pre><code>old_list = [] old_list = list() </code></pre> <p>The reason I ask is that I just saw this in some running code:</p> <pre><code>del old_list[ 0:len(old_list) ] </code></pre>
119
2009-05-12T01:46:55Z
850,832
<p><del>It appears to me that del will give you the memory back, while assigning a new list will make the old one be deleted only when the gc runs.matter.</p> <p>This may be useful for large lists, but for small list it should be negligible.</del></p> <p><strong>Edit</strong>: As Algorias, it doesn't matter.</p> <p>Note that </p> <pre><code>del old_list[ 0:len(old_list) ] </code></pre> <p>is equivalent to</p> <pre><code>del old_list[:] </code></pre>
10
2009-05-12T02:03:32Z
[ "python" ]
Clearing Python lists
850,795
<p>Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python:</p> <pre><code>old_list = [] old_list = list() </code></pre> <p>The reason I ask is that I just saw this in some running code:</p> <pre><code>del old_list[ 0:len(old_list) ] </code></pre>
119
2009-05-12T01:46:55Z
851,533
<p>There are two cases in which you might want to clear a list:</p> <ol> <li>You want to use the name <code>old_list</code> further in your code;</li> <li>You want the old list to be garbage collected as soon as possible to free some memory;</li> </ol> <p>In case 1 you just go on with the assigment:</p> <pre><code> old_list = [] # or whatever you want it to be equal to </code></pre> <p>In case 2 the <code>del</code> statement would reduce the reference count to the list object the name <code>old list</code> points at. If the list object is only pointed by the name <code>old_list</code> at, the reference count would be 0, and the object would be freed for garbage collection.</p> <pre><code> del old_list </code></pre>
4
2009-05-12T07:13:48Z
[ "python" ]
Clearing Python lists
850,795
<p>Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python:</p> <pre><code>old_list = [] old_list = list() </code></pre> <p>The reason I ask is that I just saw this in some running code:</p> <pre><code>del old_list[ 0:len(old_list) ] </code></pre>
119
2009-05-12T01:46:55Z
12,970,184
<p>There is a very simple way to delete a python list. Use <strong>del list_name[:]</strong>.</p> <p>For example: <pre><code><code>a = [1, 2, 3]</code> b = a del a[:] print b </pre></code></p>
22
2012-10-19T08:23:54Z
[ "python" ]
Clearing Python lists
850,795
<p>Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python:</p> <pre><code>old_list = [] old_list = list() </code></pre> <p>The reason I ask is that I just saw this in some running code:</p> <pre><code>del old_list[ 0:len(old_list) ] </code></pre>
119
2009-05-12T01:46:55Z
30,431,696
<pre><code>del list[:] </code></pre> <p>Will delete the values of that list variable </p> <pre><code>del list </code></pre> <p>Will delete the variable itself from memory </p>
2
2015-05-25T05:22:54Z
[ "python" ]
Clearing Python lists
850,795
<p>Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python:</p> <pre><code>old_list = [] old_list = list() </code></pre> <p>The reason I ask is that I just saw this in some running code:</p> <pre><code>del old_list[ 0:len(old_list) ] </code></pre>
119
2009-05-12T01:46:55Z
31,270,256
<p>If you're clearing the list, you, obviously, don't need the list anymore. If so, you can just delete the entire list by simple del method.</p> <pre><code>a = [1, 3, 5, 6] del a # This will entirely delete a(the list). </code></pre> <p>But in case, you need it again, you can reinitialize it. Or just simply clear its elements by </p> <pre><code>del a[:] </code></pre>
1
2015-07-07T13:41:34Z
[ "python" ]
Clearing Python lists
850,795
<p>Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python:</p> <pre><code>old_list = [] old_list = list() </code></pre> <p>The reason I ask is that I just saw this in some running code:</p> <pre><code>del old_list[ 0:len(old_list) ] </code></pre>
119
2009-05-12T01:46:55Z
35,139,695
<p>another solution that works fine is to create empty list as a reference empty list.</p> <pre><code>empt_list = [] </code></pre> <p>for example you have a list as <code>a_list = [1,2,3]</code>. To clear it just make the following:</p> <pre><code>a_list = list(empt_list) </code></pre> <p>this will make <code>a_list</code> an empty list just like the <code>empt_list</code>.</p>
-1
2016-02-01T20:28:09Z
[ "python" ]
How to filter a file using pattern to another file using Python?
850,799
<p>I have a dictionary. I want to take only the words containing a simple word pattern (i.e. "cow") and write them to another file. Each line starts with a word and then the definition. I'm still extremely new at python so I don't have a good grasp of the syntax, but the pseudocode in my head looks something like:</p> <pre><code>infile = open('C:/infile.txt') outfile = open('C:/outfile.txt') pattern = re.compile('cow') for line in infile: linelist = line.split(None, 2) if (pattern.search(linelist[1]) outfile.write(listlist[1]) outfile.close() infile.close() </code></pre> <p>I'm running into a lot of errors, any help will be appreciated!</p>
0
2009-05-12T01:49:08Z
850,829
<pre><code>import re infile = open('C:/infile.txt') outfile = open('C:/outfile.txt', 'w') pattern = re.compile('^(cow\w*)') for line in infile: found = pattern.match(line) if found: text = "%s\n" % (found.group(0)) outfile.write(text) outfile.close() infile.close() </code></pre>
2
2009-05-12T02:03:02Z
[ "python", "file-io" ]
Faster way to sum a list of numbers than with a for-loop?
850,877
<p>Is there a way to sum up a list of numbers faster than with a for-loop, perhaps in the Python library? Or is that something really only multi-threading / vector processing can do efficiently?</p> <p>Edit: Just to clarify, it could be a list of any numbers, unsorted, just input from the user.</p>
8
2009-05-12T02:20:32Z
850,882
<p>You can use sum() to sum the values of an array.</p> <pre><code>a = [1,9,12] print sum(a) </code></pre>
32
2009-05-12T02:22:50Z
[ "python", "algorithm", "for-loop" ]
Faster way to sum a list of numbers than with a for-loop?
850,877
<p>Is there a way to sum up a list of numbers faster than with a for-loop, perhaps in the Python library? Or is that something really only multi-threading / vector processing can do efficiently?</p> <p>Edit: Just to clarify, it could be a list of any numbers, unsorted, just input from the user.</p>
8
2009-05-12T02:20:32Z
850,890
<p>If each term in the list simply increments by 1, or if you can find a pattern in the series, you could find a formula for summing n terms. For example, the sum of the series {1,2,3,...,n} = n(n+1)/2</p> <p>Read more <a href="http://en.wikipedia.org/wiki/Summation" rel="nofollow">here</a></p>
0
2009-05-12T02:24:49Z
[ "python", "algorithm", "for-loop" ]
Faster way to sum a list of numbers than with a for-loop?
850,877
<p>Is there a way to sum up a list of numbers faster than with a for-loop, perhaps in the Python library? Or is that something really only multi-threading / vector processing can do efficiently?</p> <p>Edit: Just to clarify, it could be a list of any numbers, unsorted, just input from the user.</p>
8
2009-05-12T02:20:32Z
850,898
<p>Well, I don't know if it is faster but you could try a little calculus to make it one operation. (N*(N+1))/2 gives you the sum of every number from 1 to N, and there are other formulas for solving more complex sums.</p>
0
2009-05-12T02:26:32Z
[ "python", "algorithm", "for-loop" ]
Faster way to sum a list of numbers than with a for-loop?
850,877
<p>Is there a way to sum up a list of numbers faster than with a for-loop, perhaps in the Python library? Or is that something really only multi-threading / vector processing can do efficiently?</p> <p>Edit: Just to clarify, it could be a list of any numbers, unsorted, just input from the user.</p>
8
2009-05-12T02:20:32Z
850,910
<p>For a general list, you have to at least go over every member at least once to get the sum, which is exactly what a for loop does. Using library APIs (like sum) is more convenient, but I doubt it would actually be faster.</p>
0
2009-05-12T02:31:29Z
[ "python", "algorithm", "for-loop" ]
Faster way to sum a list of numbers than with a for-loop?
850,877
<p>Is there a way to sum up a list of numbers faster than with a for-loop, perhaps in the Python library? Or is that something really only multi-threading / vector processing can do efficiently?</p> <p>Edit: Just to clarify, it could be a list of any numbers, unsorted, just input from the user.</p>
8
2009-05-12T02:20:32Z
851,489
<p>Yet another way to sum up a list with the loop time:</p> <pre><code> s = reduce(lambda x, y: x + y, l) </code></pre>
4
2009-05-12T06:56:34Z
[ "python", "algorithm", "for-loop" ]
Editing Photoshop PSD text layers programmatically
850,899
<p>I have a multi-layered PSD, with one specific layer being non-rasterized text. I'm trying to figure out a way I can, from a bash/perl/python/whatever-else program:</p> <ol> <li>load the PSD</li> <li>edit the text in said layer</li> <li>flatten all layers in the image</li> <li>save as a web-friendly format like PNG or JPG</li> </ol> <p>I immediately thought of <a href="http://www.imagemagick.org/">ImageMagick</a>, but I don't think I can edit the text layer through IM. If I can accomplish the first two steps some other programmatic way, I can always use ImageMagick to perform the last two steps.</p> <p>After a couple of hours of googling and searching CPAN and PyPI, I still have found nothing promising. Does anyone have advice or ideas on the subject?</p>
7
2009-05-12T02:27:02Z
850,987
<p>If you're going to automate Photoshop, you pretty much have to use Photoshop's own scripting systems. I don't think there's a way around that.</p> <p>Looking at the problem a different way, can you export from Photoshop to some other format which supports layers, like PNG, which is editable by ImageMagick?</p>
1
2009-05-12T03:01:50Z
[ "python", "perl", "image", "photoshop", "psd" ]
Editing Photoshop PSD text layers programmatically
850,899
<p>I have a multi-layered PSD, with one specific layer being non-rasterized text. I'm trying to figure out a way I can, from a bash/perl/python/whatever-else program:</p> <ol> <li>load the PSD</li> <li>edit the text in said layer</li> <li>flatten all layers in the image</li> <li>save as a web-friendly format like PNG or JPG</li> </ol> <p>I immediately thought of <a href="http://www.imagemagick.org/">ImageMagick</a>, but I don't think I can edit the text layer through IM. If I can accomplish the first two steps some other programmatic way, I can always use ImageMagick to perform the last two steps.</p> <p>After a couple of hours of googling and searching CPAN and PyPI, I still have found nothing promising. Does anyone have advice or ideas on the subject?</p>
7
2009-05-12T02:27:02Z
851,244
<p>The only way I can think of to automate the changing of text inside of a PSD would be to use a regex based substitution. </p> <ol> <li>Create a very simple picture in Photoshop, perhaps a white background and a text layer, with the text being a known length.</li> <li>Search the file for your text, and with a hex editor, search nearby for the length of the text (which may or may not be part of the file format).</li> <li>Try changing the text, first to a string of the same length, then to something shorter/longer.</li> <li>Open in Photoshop after each change to see if the file is corrupt.</li> </ol> <p>This method, if viable, will only work if the layer in question contains a known string, which can be substituted for your other value. Note that I have no idea whether this will work, as I don't have Photoshop on this computer to try this method out. Perhaps you can make it work?</p> <p>As for converting to png, I am at a loss. If the replacing script is in Python, you may be able to do it with the Python Imaging Library (PIL, <a href="http://effbot.org/imagingbook/format-psd.htm" rel="nofollow">which seems to support it</a>), but otherwise you may just have to open Photoshop to do the conversion. Which means that it probably wouldn't be worth it to change the text pragmatically in the first place.</p>
3
2009-05-12T05:18:51Z
[ "python", "perl", "image", "photoshop", "psd" ]
Editing Photoshop PSD text layers programmatically
850,899
<p>I have a multi-layered PSD, with one specific layer being non-rasterized text. I'm trying to figure out a way I can, from a bash/perl/python/whatever-else program:</p> <ol> <li>load the PSD</li> <li>edit the text in said layer</li> <li>flatten all layers in the image</li> <li>save as a web-friendly format like PNG or JPG</li> </ol> <p>I immediately thought of <a href="http://www.imagemagick.org/">ImageMagick</a>, but I don't think I can edit the text layer through IM. If I can accomplish the first two steps some other programmatic way, I can always use ImageMagick to perform the last two steps.</p> <p>After a couple of hours of googling and searching CPAN and PyPI, I still have found nothing promising. Does anyone have advice or ideas on the subject?</p>
7
2009-05-12T02:27:02Z
851,513
<p>If you don't like to use the officially supported AppleScript, JavaScript, or VBScript, then there is also the possibility to do it in Python. This is explained in the article <a href="http://techarttiki.blogspot.com/2008/08/photoshop-scripting-with-python.html">Photoshop scripting with Python</a>, which relies on Photoshop's COM interface.</p> <p>I have not tried it, so in case it does not work for you: If your text is preserved after <a href="http://www.google.de/search?hl=de&amp;q=photoshop%2Bsvg%2Bplugin&amp;revid=1305924600&amp;ei=4h4JSqDpJsPj-Ab308jmCw&amp;sa=X&amp;oi=revisions%5Finline&amp;resnum=0&amp;ct=broad-revision&amp;cd=3">conversion to SVG</a> then you can simply replace it by whatever tool you like. Afterwards, convert it to PNG (eg. by <code>inkscape --export-png=...</code>).</p>
5
2009-05-12T07:07:47Z
[ "python", "perl", "image", "photoshop", "psd" ]
Editing Photoshop PSD text layers programmatically
850,899
<p>I have a multi-layered PSD, with one specific layer being non-rasterized text. I'm trying to figure out a way I can, from a bash/perl/python/whatever-else program:</p> <ol> <li>load the PSD</li> <li>edit the text in said layer</li> <li>flatten all layers in the image</li> <li>save as a web-friendly format like PNG or JPG</li> </ol> <p>I immediately thought of <a href="http://www.imagemagick.org/">ImageMagick</a>, but I don't think I can edit the text layer through IM. If I can accomplish the first two steps some other programmatic way, I can always use ImageMagick to perform the last two steps.</p> <p>After a couple of hours of googling and searching CPAN and PyPI, I still have found nothing promising. Does anyone have advice or ideas on the subject?</p>
7
2009-05-12T02:27:02Z
851,685
<p>Have you considered opening and editing the image in The GIMP? It has very good PSD support, and can be scripted in several languages.</p> <p>Which one you use depends in part on your platform, the Perl interface didn't work on Windows the last I knew. I believe Scheme is supported in all ports.</p>
3
2009-05-12T08:12:17Z
[ "python", "perl", "image", "photoshop", "psd" ]
Editing Photoshop PSD text layers programmatically
850,899
<p>I have a multi-layered PSD, with one specific layer being non-rasterized text. I'm trying to figure out a way I can, from a bash/perl/python/whatever-else program:</p> <ol> <li>load the PSD</li> <li>edit the text in said layer</li> <li>flatten all layers in the image</li> <li>save as a web-friendly format like PNG or JPG</li> </ol> <p>I immediately thought of <a href="http://www.imagemagick.org/">ImageMagick</a>, but I don't think I can edit the text layer through IM. If I can accomplish the first two steps some other programmatic way, I can always use ImageMagick to perform the last two steps.</p> <p>After a couple of hours of googling and searching CPAN and PyPI, I still have found nothing promising. Does anyone have advice or ideas on the subject?</p>
7
2009-05-12T02:27:02Z
852,143
<p>You can use Photoshop itself to do this with OLE. You will need to install Photoshop, of course. Win32::OLE in Perl or similar module in Python. See <a href="http://www.adobe.com/devnet/photoshop/pdfs/PhotoshopScriptingGuide.pdf" rel="nofollow">http://www.adobe.com/devnet/photoshop/pdfs/PhotoshopScriptingGuide.pdf</a> </p>
2
2009-05-12T10:35:01Z
[ "python", "perl", "image", "photoshop", "psd" ]
Editing Photoshop PSD text layers programmatically
850,899
<p>I have a multi-layered PSD, with one specific layer being non-rasterized text. I'm trying to figure out a way I can, from a bash/perl/python/whatever-else program:</p> <ol> <li>load the PSD</li> <li>edit the text in said layer</li> <li>flatten all layers in the image</li> <li>save as a web-friendly format like PNG or JPG</li> </ol> <p>I immediately thought of <a href="http://www.imagemagick.org/">ImageMagick</a>, but I don't think I can edit the text layer through IM. If I can accomplish the first two steps some other programmatic way, I can always use ImageMagick to perform the last two steps.</p> <p>After a couple of hours of googling and searching CPAN and PyPI, I still have found nothing promising. Does anyone have advice or ideas on the subject?</p>
7
2009-05-12T02:27:02Z
35,058,547
<p>You can also try this using Node.js. I made a <a href="https://www.npmjs.com/package/psd-cli" rel="nofollow">PSD command-line tool</a></p> <p>One-line command install (needs NodeJS/NPM installed)</p> <p><code>npm install -g psd-cli</code></p> <p>You can then use it by typing in your terminal</p> <p><code>psd myfile.psd -t</code></p> <p>You can check out the code to use it from another node script or use it through your shell is from another Bash/Perl/whatever script.</p>
1
2016-01-28T10:14:20Z
[ "python", "perl", "image", "photoshop", "psd" ]
Can you pass a class (not an object) as a parameter to a method in python?
850,921
<p>I want to do something like the following</p> <pre><code>class A: def static_method_A(): print "hello" def main(param=A): param.static_method_A() </code></pre> <p>I want this to be equivalent to <code>A.static_method()</code>. Is this possible?</p>
5
2009-05-12T02:35:23Z
850,929
<p>Sure. Classes are first-class objects in Python.</p> <p>Although, in your example, you should use the <code>@classmethod</code> (class object as initial argument) or <code>@staticmethod</code> (no initial argument) decorator for your method.</p>
7
2009-05-12T02:37:44Z
[ "python", "static", "parameters" ]
Can you pass a class (not an object) as a parameter to a method in python?
850,921
<p>I want to do something like the following</p> <pre><code>class A: def static_method_A(): print "hello" def main(param=A): param.static_method_A() </code></pre> <p>I want this to be equivalent to <code>A.static_method()</code>. Is this possible?</p>
5
2009-05-12T02:35:23Z
850,932
<p>Sure why not? Don't forget to add @staticmethod to static methods.</p> <pre><code>class A: @staticmethod def static_method_A(): print "hello" def main(param=A): param.static_method_A() </code></pre>
0
2009-05-12T02:38:29Z
[ "python", "static", "parameters" ]
Can you pass a class (not an object) as a parameter to a method in python?
850,921
<p>I want to do something like the following</p> <pre><code>class A: def static_method_A(): print "hello" def main(param=A): param.static_method_A() </code></pre> <p>I want this to be equivalent to <code>A.static_method()</code>. Is this possible?</p>
5
2009-05-12T02:35:23Z
850,937
<p>You should be able to do the following (note the <code>@staticmethod</code> decorator):</p> <pre><code>class A: @staticmethod def static_method_A(): print "hello" def main(param=A): param.static_method_A() </code></pre>
5
2009-05-12T02:39:51Z
[ "python", "static", "parameters" ]
How do I check if a disk is in a drive using python?
851,010
<p>Say I want to manipulate some files on a floppy drive or a USB card reader. How do I check to see if the drive in question is ready? (That is, has a disk physically inserted.)</p> <p>The drive letter <em>exists</em>, so os.exists() will always return True in this case. Also, at this point in the process I don't yet know any file names, so checking to see if a given file exists also won't work.</p> <p>Some clarification: the issue here is exception handling. Most of the win32 API calls in question just throw an exception when you try to access a drive that isn't ready. Normally, this would work fine - look for something like the free space, and then catch the raised exception and assume that means there isn't a disk present. However, even when I catch any and all exceptions, I still get an angry exception dialog box from Windows telling me the floppy / card reader isn't ready. So, I guess the real question is - how do I suppress the windows error box?</p>
4
2009-05-12T03:20:00Z
851,038
<p>Not sure about your platform, but <a href="http://pysnmp.sourceforge.net/" rel="nofollow">SNMP</a> might be the answer for you.</p>
0
2009-05-12T03:36:26Z
[ "python", "windows" ]
How do I check if a disk is in a drive using python?
851,010
<p>Say I want to manipulate some files on a floppy drive or a USB card reader. How do I check to see if the drive in question is ready? (That is, has a disk physically inserted.)</p> <p>The drive letter <em>exists</em>, so os.exists() will always return True in this case. Also, at this point in the process I don't yet know any file names, so checking to see if a given file exists also won't work.</p> <p>Some clarification: the issue here is exception handling. Most of the win32 API calls in question just throw an exception when you try to access a drive that isn't ready. Normally, this would work fine - look for something like the free space, and then catch the raised exception and assume that means there isn't a disk present. However, even when I catch any and all exceptions, I still get an angry exception dialog box from Windows telling me the floppy / card reader isn't ready. So, I guess the real question is - how do I suppress the windows error box?</p>
4
2009-05-12T03:20:00Z
851,039
<p>You can compare <code>len(os.listdir("path"))</code> to zero to see if there are any files in the directory.</p>
4
2009-05-12T03:37:44Z
[ "python", "windows" ]
How do I check if a disk is in a drive using python?
851,010
<p>Say I want to manipulate some files on a floppy drive or a USB card reader. How do I check to see if the drive in question is ready? (That is, has a disk physically inserted.)</p> <p>The drive letter <em>exists</em>, so os.exists() will always return True in this case. Also, at this point in the process I don't yet know any file names, so checking to see if a given file exists also won't work.</p> <p>Some clarification: the issue here is exception handling. Most of the win32 API calls in question just throw an exception when you try to access a drive that isn't ready. Normally, this would work fine - look for something like the free space, and then catch the raised exception and assume that means there isn't a disk present. However, even when I catch any and all exceptions, I still get an angry exception dialog box from Windows telling me the floppy / card reader isn't ready. So, I guess the real question is - how do I suppress the windows error box?</p>
4
2009-05-12T03:20:00Z
851,043
<p>If you have pythonwin, does any of the information in <a href="http://www.microsoft.com/technet/scriptcenter/scripts/python/storage/disks/drives/stdvpy05.mspx?mfr=true" rel="nofollow">this recipe</a> help?</p> <p>At a guess, "Availability" and "Status" may be worth looking at. Or you could test volume name, which I guess will be either 'X:' or '' if there is nothing in the drive. Or, heck, look for free space or total number of blocks.</p>
1
2009-05-12T03:40:20Z
[ "python", "windows" ]
How do I check if a disk is in a drive using python?
851,010
<p>Say I want to manipulate some files on a floppy drive or a USB card reader. How do I check to see if the drive in question is ready? (That is, has a disk physically inserted.)</p> <p>The drive letter <em>exists</em>, so os.exists() will always return True in this case. Also, at this point in the process I don't yet know any file names, so checking to see if a given file exists also won't work.</p> <p>Some clarification: the issue here is exception handling. Most of the win32 API calls in question just throw an exception when you try to access a drive that isn't ready. Normally, this would work fine - look for something like the free space, and then catch the raised exception and assume that means there isn't a disk present. However, even when I catch any and all exceptions, I still get an angry exception dialog box from Windows telling me the floppy / card reader isn't ready. So, I guess the real question is - how do I suppress the windows error box?</p>
4
2009-05-12T03:20:00Z
852,348
<p>You can use win32 functions via the excellent pywin32 (<a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">http://sourceforge.net/projects/pywin32/</a>) for this purpose. </p> <p>I suggest looking at the <code>GetDiskFreeSpace</code> function. You can check the free space on the target drive and continue based on that information.</p> <p>As an alternative you can watch the changes of a directory or file with the <code>ReadDirectoryChangesW</code> function. You'll get notifications about file changes etc. But you have to check whether this works for you or not. You can look at this example foryourself: <a href="http://timgolden.me.uk/python/downloads/watch%5Fdirectory.py" rel="nofollow">http://timgolden.me.uk/python/downloads/watch_directory.py</a></p>
1
2009-05-12T11:51:42Z
[ "python", "windows" ]
How do I check if a disk is in a drive using python?
851,010
<p>Say I want to manipulate some files on a floppy drive or a USB card reader. How do I check to see if the drive in question is ready? (That is, has a disk physically inserted.)</p> <p>The drive letter <em>exists</em>, so os.exists() will always return True in this case. Also, at this point in the process I don't yet know any file names, so checking to see if a given file exists also won't work.</p> <p>Some clarification: the issue here is exception handling. Most of the win32 API calls in question just throw an exception when you try to access a drive that isn't ready. Normally, this would work fine - look for something like the free space, and then catch the raised exception and assume that means there isn't a disk present. However, even when I catch any and all exceptions, I still get an angry exception dialog box from Windows telling me the floppy / card reader isn't ready. So, I guess the real question is - how do I suppress the windows error box?</p>
4
2009-05-12T03:20:00Z
1,020,363
<p>And the answer, as with so many things, turns out to be in <a href="http://bcbjournal.org/articles/vol2/9806/Detecting%5Fdisk%5Ferrors.htm">an article about C++/Win32 programming from a decade ago</a>.</p> <p>The issue, in a nutshell, is that Windows handles floppy disk errors slightly differently than other kinds of drive errors. By default, no matter what you program does, or <strong>thinks</strong> it's doing, Windows will intercept any errors thrown by the device and present a dialog box to the user rather than letting the program handle it - the exact issue I was having.</p> <p>But, as it turns out, there's a Win32 API call to solve this issue, primarily <code>SetErrorMode()</code></p> <p>In a nutshell (and I'm handwaving a way a lot of the details here), we can use <code>SetErrorMode()</code> to get Windows to stop being quite so paranoid, do our thing and let the program handle the situation, and then reset the Windows error mode back to what it was before as if we had never been there. (There's probably a Keyser Soze joke here, but I've had the wrong amount of caffeine today to be able to find it.)</p> <p>Adapting the C++ sample code from the linked article, that looks about like this:</p> <pre><code>int OldMode; //a place to store the old error mode //save the old error mode and set the new mode to let us do the work: OldMode = SetErrorMode(SEM_FAILCRITICALERRORS); // Do whatever we need to do that might cause an error SetErrorMode(OldMode); //put things back the way they were </code></pre> <p>Under C++, detecting errors the right way needs the `GetLastError()' function, which we fortunately don't need to worry about here, since this is a Python question. In our case, Python's exception handling works fine. This, then, is the function I knocked together to check a drive letter for "readiness", all ready for copy-pasting if anyone else needs it:</p> <pre><code>import win32api def testDrive( currentLetter ): """ Tests a given drive letter to see if the drive is question is ready for access. This is to handle things like floppy drives and USB card readers which have to have physical media inserted in order to be accessed. Returns true if the drive is ready, false if not. """ returnValue = False #This prevents Windows from showing an error to the user, and allows python #to handle the exception on its own. oldError = win32api.SetErrorMode( 1 ) #note that SEM_FAILCRITICALERRORS = 1 try: freeSpace = win32file.GetDiskFreeSpaceEx( letter ) except: returnValue = False else: returnValue = True #restore the Windows error handling state to whatever it was before we #started messing with it: win32api.SetErrorMode( oldError ) return returnValue </code></pre> <p>I've been using this quite a bit the last few days, and it's been working beautifully for both floppies and USB card readers.</p> <p>A few notes: pretty much any function needing disk access will work in the try block - all we're looking for in an exception due to the media not being present.</p> <p>Also, while the python <code>win32api</code> package exposes all the functions we need, it dones't seem to have any of the flag constants. After a trip to the ancient bowels of MSDN, it turns out that SEM_FAILCRITICALERRORS is equal to 1, which makes our life awfully easy.</p> <p>I hope this helps someone else with a similar problem!</p>
6
2009-06-19T22:47:36Z
[ "python", "windows" ]
how are exceptions compared in an except clause
851,012
<p>In the following code segment:</p> <pre><code>try: raise Bob() except Fred: print "blah" </code></pre> <p>How is the comparison of Bob and Fred implemented?</p> <p>From playing around it seems to be calling isinstance underneath, is this correct?</p> <p>I'm asking because I am attempting to subvert the process, specifically I want to be able to construct a Bob such that it gets caught by execpt Fred even though it isn't actually an instance of Fred or any of its subclasses.</p> <p>A couple of people have asked why I'm trying to do this...</p> <p>We have a RMI system, that is built around the philosophy of making it as seamless as possible, here's a quick example of it in use, note that there is no socket specific code in the RMI system, sockets just provided a convenient example.</p> <pre><code>import remobj socket = remobj.RemObj("remote_server_name").getImport("socket") s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(("", 0)) print "listening on port:", s.getsockname()[1] s.settimeout(10) try: print "received:", s.recv(2048) except socket.timeout: print "timeout" </code></pre> <p>Now in this particular example the except doesn't work as expected because the raised object is not an instance of socket.timeout, it's an instance of one of our proxy helper classes.</p>
-2
2009-05-12T03:20:08Z
851,027
<blockquote> <p>I want to be able to construct a Bob such that it gets caught by execpt Fred even though it isn't actually an instance of Fred or any of its subclasses.</p> </blockquote> <p>Well, you can just catch 'Exception' - but this is not very pythonic. You should attempt to catch the correct exception and then fall back on the general Exception (which all exceptions are subclassed from) as a last resort. If this does not work for you then something has gone terribly wrong in your design phase.</p> <p><a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#eafp-try-except-example" rel="nofollow">See this note from Code Like A Pythonista</a></p> <blockquote> <p>Note: Always specify the exceptions to catch. Never use bare except clauses. Bare except clauses will catch unexpected exceptions, making your code exceedingly difficult to debug.</p> </blockquote> <p>However, one of the idioms in the Zen of Python is</p> <blockquote> <p>Special cases aren't special enough to break the rules. Although practicality beats purity.</p> </blockquote>
1
2009-05-12T03:28:51Z
[ "python", "exception" ]
how are exceptions compared in an except clause
851,012
<p>In the following code segment:</p> <pre><code>try: raise Bob() except Fred: print "blah" </code></pre> <p>How is the comparison of Bob and Fred implemented?</p> <p>From playing around it seems to be calling isinstance underneath, is this correct?</p> <p>I'm asking because I am attempting to subvert the process, specifically I want to be able to construct a Bob such that it gets caught by execpt Fred even though it isn't actually an instance of Fred or any of its subclasses.</p> <p>A couple of people have asked why I'm trying to do this...</p> <p>We have a RMI system, that is built around the philosophy of making it as seamless as possible, here's a quick example of it in use, note that there is no socket specific code in the RMI system, sockets just provided a convenient example.</p> <pre><code>import remobj socket = remobj.RemObj("remote_server_name").getImport("socket") s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(("", 0)) print "listening on port:", s.getsockname()[1] s.settimeout(10) try: print "received:", s.recv(2048) except socket.timeout: print "timeout" </code></pre> <p>Now in this particular example the except doesn't work as expected because the raised object is not an instance of socket.timeout, it's an instance of one of our proxy helper classes.</p>
-2
2009-05-12T03:20:08Z
851,037
<p>I believe that your guess is correct in how the comparison works, and the only way to intercept that is to add Fred as a base class to Bob. For example:</p> <pre><code># Assume both Bob and Fred are derived from Exception &gt;&gt;&gt; class Bob(Bob, Fred): ... pass ... &gt;&gt;&gt; try: ... raise Bob() ... except Fred: ... print 'blah' blah </code></pre> <p>As far as I know, this is the only way to make it work as you wrote it. However, if you simply rewrote the except: line as</p> <pre><code>... except (Bob, Fred): </code></pre> <p>It would catch both Bob and Fred, without requiring the modification of the definition of Bob.</p>
6
2009-05-12T03:35:50Z
[ "python", "exception" ]
how are exceptions compared in an except clause
851,012
<p>In the following code segment:</p> <pre><code>try: raise Bob() except Fred: print "blah" </code></pre> <p>How is the comparison of Bob and Fred implemented?</p> <p>From playing around it seems to be calling isinstance underneath, is this correct?</p> <p>I'm asking because I am attempting to subvert the process, specifically I want to be able to construct a Bob such that it gets caught by execpt Fred even though it isn't actually an instance of Fred or any of its subclasses.</p> <p>A couple of people have asked why I'm trying to do this...</p> <p>We have a RMI system, that is built around the philosophy of making it as seamless as possible, here's a quick example of it in use, note that there is no socket specific code in the RMI system, sockets just provided a convenient example.</p> <pre><code>import remobj socket = remobj.RemObj("remote_server_name").getImport("socket") s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(("", 0)) print "listening on port:", s.getsockname()[1] s.settimeout(10) try: print "received:", s.recv(2048) except socket.timeout: print "timeout" </code></pre> <p>Now in this particular example the except doesn't work as expected because the raised object is not an instance of socket.timeout, it's an instance of one of our proxy helper classes.</p>
-2
2009-05-12T03:20:08Z
851,482
<pre><code>&gt;&gt;&gt; class Fred(Exception): pass &gt;&gt;&gt; class Bob(Fred): pass &gt;&gt;&gt; issubclass(Bob, Fred) True &gt;&gt;&gt; issubclass(Fred, Bob) False &gt;&gt;&gt; try: raise Bob() except Fred: print("blah") blah </code></pre> <p>So basically the exception is caught because, Bob is subclass of Fred, I am assuming, either they must have implemented a logic similar to <code>issubclass(Bob, Fred)</code></p> <p>See, is this how you want to implement, watever you want. Ofcourse not in the <strong>init</strong>, but some other method.</p> <pre><code>&gt;&gt;&gt; class Bob(Exception): def __init__(self): raise Fred &gt;&gt;&gt; try: b = Bob() except Fred: print('blah') blah </code></pre>
1
2009-05-12T06:53:52Z
[ "python", "exception" ]
how are exceptions compared in an except clause
851,012
<p>In the following code segment:</p> <pre><code>try: raise Bob() except Fred: print "blah" </code></pre> <p>How is the comparison of Bob and Fred implemented?</p> <p>From playing around it seems to be calling isinstance underneath, is this correct?</p> <p>I'm asking because I am attempting to subvert the process, specifically I want to be able to construct a Bob such that it gets caught by execpt Fred even though it isn't actually an instance of Fred or any of its subclasses.</p> <p>A couple of people have asked why I'm trying to do this...</p> <p>We have a RMI system, that is built around the philosophy of making it as seamless as possible, here's a quick example of it in use, note that there is no socket specific code in the RMI system, sockets just provided a convenient example.</p> <pre><code>import remobj socket = remobj.RemObj("remote_server_name").getImport("socket") s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(("", 0)) print "listening on port:", s.getsockname()[1] s.settimeout(10) try: print "received:", s.recv(2048) except socket.timeout: print "timeout" </code></pre> <p>Now in this particular example the except doesn't work as expected because the raised object is not an instance of socket.timeout, it's an instance of one of our proxy helper classes.</p>
-2
2009-05-12T03:20:08Z
855,053
<p>In CPython at least, it looks like there's a COMPARE_OP operation with type 10 (exception match). There's unlikely anything you can do to hack around that calculation.</p> <pre> >>> import dis >>> def foo(): ... try: ... raise OSError() ... except Exception, e: ... pass ... >>> dis.dis(foo) 2 0 SETUP_EXCEPT 13 (to 16) 3 3 LOAD_GLOBAL 0 (OSError) 6 CALL_FUNCTION 0 9 RAISE_VARARGS 1 12 POP_BLOCK 13 JUMP_FORWARD 21 (to 37) 4 >> 16 DUP_TOP 17 LOAD_GLOBAL 1 (Exception) 20 COMPARE_OP 10 (exception match) 23 JUMP_IF_FALSE 9 (to 35) 26 POP_TOP 27 POP_TOP 28 STORE_FAST 0 (e) 31 POP_TOP 5 32 JUMP_FORWARD 2 (to 37) >> 35 POP_TOP 36 END_FINALLY >> 37 LOAD_CONST 0 (None) 40 RETURN_VALUE </pre>
0
2009-05-12T21:50:50Z
[ "python", "exception" ]
how are exceptions compared in an except clause
851,012
<p>In the following code segment:</p> <pre><code>try: raise Bob() except Fred: print "blah" </code></pre> <p>How is the comparison of Bob and Fred implemented?</p> <p>From playing around it seems to be calling isinstance underneath, is this correct?</p> <p>I'm asking because I am attempting to subvert the process, specifically I want to be able to construct a Bob such that it gets caught by execpt Fred even though it isn't actually an instance of Fred or any of its subclasses.</p> <p>A couple of people have asked why I'm trying to do this...</p> <p>We have a RMI system, that is built around the philosophy of making it as seamless as possible, here's a quick example of it in use, note that there is no socket specific code in the RMI system, sockets just provided a convenient example.</p> <pre><code>import remobj socket = remobj.RemObj("remote_server_name").getImport("socket") s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(("", 0)) print "listening on port:", s.getsockname()[1] s.settimeout(10) try: print "received:", s.recv(2048) except socket.timeout: print "timeout" </code></pre> <p>Now in this particular example the except doesn't work as expected because the raised object is not an instance of socket.timeout, it's an instance of one of our proxy helper classes.</p>
-2
2009-05-12T03:20:08Z
856,409
<p>I'm not clear how hiding your exception in socket.timeout adhears to the "seamless" philosophy? What's wrong with catching the expected exception as it's defined?</p> <pre><code>try: print "received:", s.recv(2048) except socket.timeout: print "timeout" except our_proxy_helper_class: print 'crap!' </code></pre> <p>Or, if you really want to catch it as socket.timeout, why not just raise socket.timeout in our_proxy_helper_class?</p> <pre><code>raise socket.timeout('Method x timeout') </code></pre> <p>So when you raise socket.timeout in our_proxy_helper_class it should be caught by 'except socket.timeout'.</p>
1
2009-05-13T06:37:42Z
[ "python", "exception" ]
How does Python import modules from .egg files?
851,420
<p>How can I open <code>__init__.pyc</code> here?</p> <pre><code> &gt;&gt;&gt; import stompservice &lt;module 'stompservice' from 'C:\Python25\lib\site-packages\stompservice-0.1.0-py2.5.egg\stompservice\__init__.pyc'&gt; </code></pre> <p>All I see in <code>C:\Python25\lib\site-packages\</code> is the .egg file, but where are the internal files of the package?</p>
12
2009-05-12T06:31:41Z
851,430
<p><a href="http://peak.telecommunity.com/DevCenter/PythonEggs">http://peak.telecommunity.com/DevCenter/PythonEggs</a></p> <p>.egg files are simply renamed zip files.</p> <p>Open the egg with your zip program, or just rename the extension to .zip, and extract.</p>
18
2009-05-12T06:35:16Z
[ "python", "module", "packages" ]
How does Python import modules from .egg files?
851,420
<p>How can I open <code>__init__.pyc</code> here?</p> <pre><code> &gt;&gt;&gt; import stompservice &lt;module 'stompservice' from 'C:\Python25\lib\site-packages\stompservice-0.1.0-py2.5.egg\stompservice\__init__.pyc'&gt; </code></pre> <p>All I see in <code>C:\Python25\lib\site-packages\</code> is the .egg file, but where are the internal files of the package?</p>
12
2009-05-12T06:31:41Z
15,497,487
<p>For example, if you want to import the suds module which is available as .egg file:</p> <p>In your python script:</p> <pre><code>egg_path='/home/shahid/suds_2.4.egg' sys.path.append(egg_path) import suds #... rest of code </code></pre>
10
2013-03-19T10:54:35Z
[ "python", "module", "packages" ]
Using ctypes.c_void_p as an input to glTexImage2D?
851,587
<p>I'm using a 3rd party DLL to load in some raw image data, and I want to use this raw image data as a texture in openGL. However, the c function returns a void*, and I need to somehow convert this so it will work as the "pixels" parameter to glTexImage2D. Right now my code looks like something this:</p> <pre><code>data = c_void_p(vdll.vlImageGetData()) glTexImage2D(GL_TEXTURE_2D, 1, GL_RGB8, 1024, 1024, 0, GL_RGB, GL_UNSIGNED_BYTE, data ) </code></pre> <p>However, I get a TypeError complaining that data 'cannot be converted to pointer'. Does anyone know how to get this to work?</p> <p>Edit: Figured it out. Basically what I do is this:</p> <pre><code>data = create_string_buffer( BUFFER_SIZE ) data = dll.vlImageGetData() glTexImage2D(GL_TEXTURE_2D, 1, GL_RGB8, 1024, 1024, 0, GL_RGB, GL_UNSIGNED_BYTE, data ) </code></pre>
1
2009-05-12T07:35:45Z
851,659
<p>An <a href="http://stackoverflow.com/questions/318067/python-converting-strings-for-use-with-ctypes-cvoidp/318140#318140">answer</a> to a <a href="http://stackoverflow.com/questions/318067/python-converting-strings-for-use-with-ctypes-cvoidp">similar question</a> suggested to use <code>ctypes.cast()</code>.</p>
1
2009-05-12T08:00:35Z
[ "python", "opengl", "ctypes", "pyopengl" ]
Using ctypes.c_void_p as an input to glTexImage2D?
851,587
<p>I'm using a 3rd party DLL to load in some raw image data, and I want to use this raw image data as a texture in openGL. However, the c function returns a void*, and I need to somehow convert this so it will work as the "pixels" parameter to glTexImage2D. Right now my code looks like something this:</p> <pre><code>data = c_void_p(vdll.vlImageGetData()) glTexImage2D(GL_TEXTURE_2D, 1, GL_RGB8, 1024, 1024, 0, GL_RGB, GL_UNSIGNED_BYTE, data ) </code></pre> <p>However, I get a TypeError complaining that data 'cannot be converted to pointer'. Does anyone know how to get this to work?</p> <p>Edit: Figured it out. Basically what I do is this:</p> <pre><code>data = create_string_buffer( BUFFER_SIZE ) data = dll.vlImageGetData() glTexImage2D(GL_TEXTURE_2D, 1, GL_RGB8, 1024, 1024, 0, GL_RGB, GL_UNSIGNED_BYTE, data ) </code></pre>
1
2009-05-12T07:35:45Z
13,619,176
<p>This may or may not help. There is a similar issue on use of c_void_p as a return type. I instead have to return c_longlong AND do some hokey tricks:</p> <p>if I am returning a pointer c_types obejct, I have to cast its reference to a POINTER to c_longlong to get the integer value to return. (NOTE that CFUNCTYPE will not accept POINTER(x) types as a return type):</p> <p>retvalp = cast( byref(retval), POINTER(c_longlong)) #retval is what I WANT to return return retvalp.contents.value</p>
0
2012-11-29T05:04:26Z
[ "python", "opengl", "ctypes", "pyopengl" ]
Django -- User.DoesNotExist does not exist?
851,628
<p>I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code:</p> <pre><code>from django.contrib.auth.models import User ... class SignUpForm (forms.Form): ... def clean_username (self): try: User.objects.get(username=self.cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] raise forms.ValidationError(USERNAME_ALREADY_IN_USE) ... </code></pre>
26
2009-05-12T07:49:16Z
851,863
<p>Can Eclipse resolve attributes created runtime via <code>__metaclass__</code>es?</p> <p>Notice that you never define a <code>DoesNotExist</code> on any of your models and it is not defined on <code>django.db.models.base.Model</code> either.</p>
2
2009-05-12T09:03:12Z
[ "python", "django", "authentication", "django-models", "pydev" ]
Django -- User.DoesNotExist does not exist?
851,628
<p>I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code:</p> <pre><code>from django.contrib.auth.models import User ... class SignUpForm (forms.Form): ... def clean_username (self): try: User.objects.get(username=self.cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] raise forms.ValidationError(USERNAME_ALREADY_IN_USE) ... </code></pre>
26
2009-05-12T07:49:16Z
851,886
<blockquote> <p>Eclipse complains that User.DoesNotExist is undefined.</p> </blockquote> <p>What do you mean by that? Do you have python error and stack trace? This code have to work (as in <a href="http://docs.djangoproject.com/en/1.0/topics/auth/#writing-an-authentication-backend" rel="nofollow">documentation</a>). Looks like an eclipse issue. Just run dev server and see if it works or not:</p> <pre><code>manage.py runserver </code></pre>
0
2009-05-12T09:10:16Z
[ "python", "django", "authentication", "django-models", "pydev" ]
Django -- User.DoesNotExist does not exist?
851,628
<p>I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code:</p> <pre><code>from django.contrib.auth.models import User ... class SignUpForm (forms.Form): ... def clean_username (self): try: User.objects.get(username=self.cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] raise forms.ValidationError(USERNAME_ALREADY_IN_USE) ... </code></pre>
26
2009-05-12T07:49:16Z
851,888
<p>The problem is really with PyDev, not your code. What you have done is absolutely correct, but IDEs will always have difficulty resolving attributes in a dynamic language like Python. In the case of the DoesNotExist exception, it is added via a <code>__metaclass__</code> rather than through normal object inheritance, so PyDev is unlikely to be able to find it. However, it should definitely work.</p>
16
2009-05-12T09:11:26Z
[ "python", "django", "authentication", "django-models", "pydev" ]
Django -- User.DoesNotExist does not exist?
851,628
<p>I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code:</p> <pre><code>from django.contrib.auth.models import User ... class SignUpForm (forms.Form): ... def clean_username (self): try: User.objects.get(username=self.cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] raise forms.ValidationError(USERNAME_ALREADY_IN_USE) ... </code></pre>
26
2009-05-12T07:49:16Z
851,937
<p>Pydev has a workaround for such cases (when the members are defined at runtime). Just add #@UndefinedVariable at the end of the string which cause the warning (or ctrl+1 on keyboard when the cursor is at "DoesNotExist"), and it won't complain.</p>
7
2009-05-12T09:29:50Z
[ "python", "django", "authentication", "django-models", "pydev" ]
Django -- User.DoesNotExist does not exist?
851,628
<p>I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code:</p> <pre><code>from django.contrib.auth.models import User ... class SignUpForm (forms.Form): ... def clean_username (self): try: User.objects.get(username=self.cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] raise forms.ValidationError(USERNAME_ALREADY_IN_USE) ... </code></pre>
26
2009-05-12T07:49:16Z
1,391,255
<p>I just discovered Pydev actually has a nice workaround for this.</p> <p>Go to <strong>Window</strong> > <strong>Preferences</strong>, then <strong>Pydev</strong> > <strong>Editor</strong> > <strong>Code Analysis</strong>.</p> <p>Click the <strong>Undefined</strong> tab and add "DoesNotExist" to the text box titled <strong>Consider the following names as globals</strong>.</p>
19
2009-09-07T23:00:34Z
[ "python", "django", "authentication", "django-models", "pydev" ]
Django -- User.DoesNotExist does not exist?
851,628
<p>I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code:</p> <pre><code>from django.contrib.auth.models import User ... class SignUpForm (forms.Form): ... def clean_username (self): try: User.objects.get(username=self.cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] raise forms.ValidationError(USERNAME_ALREADY_IN_USE) ... </code></pre>
26
2009-05-12T07:49:16Z
2,591,650
<p>You can also solve it in a different way: just go to the User class, and add @DynamicAttrs in the docstring.<br> This will tell PyDev that attributes of the class are added dynamically, and will make it not complain any longer for "issues" like DoesNotExist.</p>
1
2010-04-07T10:34:25Z
[ "python", "django", "authentication", "django-models", "pydev" ]
Django -- User.DoesNotExist does not exist?
851,628
<p>I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code:</p> <pre><code>from django.contrib.auth.models import User ... class SignUpForm (forms.Form): ... def clean_username (self): try: User.objects.get(username=self.cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] raise forms.ValidationError(USERNAME_ALREADY_IN_USE) ... </code></pre>
26
2009-05-12T07:49:16Z
3,069,447
<p>I have same problem on Ubuntu in a VirtualEnv to solve problem I have used this snippets.</p> <blockquote> <p><a href="http://djangosnippets.org/snippets/191/#c3091" rel="nofollow">http://djangosnippets.org/snippets/191/#c3091</a></p> </blockquote> <p>In parituclar he make custom User Fields with code: </p> <pre><code>class UserField(forms.CharField): def clean(self, value): super(UserField, self).clean(value) try: User.objects.get(username=value) raise forms.ValidationError("Someone is already using this username. Please pick an other.") except User.DoesNotExist: return value </code></pre>
1
2010-06-18T12:13:58Z
[ "python", "django", "authentication", "django-models", "pydev" ]
How to read path from a txt file and copy those file to a new directory?
851,689
<blockquote> <pre><code>from shutil import copy f = open(r'C:\temp.txt', 'r') for i in f.readlines(): print i copy(i,r"C:\opencascade") f.close() </code></pre> </blockquote> <p>I am reading path from temp.txt file which has 500 lines each line is a path for specific file to be copied to location "C:\opencascade" How to convert 'i' in above code to be raw string to make the code work</p> <p>Error from interpreter</p> <pre><code> copy(i,r"C:\opencascade") File "C:\Python26\lib\shutil.py", line 88, in copy copyfile(src, dst) File "C:\Python26\lib\shutil.py", line 52, in copyfile fsrc = open(src, 'rb') IOError: [Errno 22] invalid mode ('rb') or filename: 'C:\\OPENCASCADE6.2.0\\ROS\\INC\\toptools_hsequenceofshape.hxx\n' </code></pre>
2
2009-05-12T08:12:54Z
851,799
<p>You have a <code>\n</code> at the and of the filename. </p> <p>Try:</p> <pre><code>copy(i.strip(), r"C:\opencascade") </code></pre>
8
2009-05-12T08:46:03Z
[ "python", "file-io", "copy" ]
How to read path from a txt file and copy those file to a new directory?
851,689
<blockquote> <pre><code>from shutil import copy f = open(r'C:\temp.txt', 'r') for i in f.readlines(): print i copy(i,r"C:\opencascade") f.close() </code></pre> </blockquote> <p>I am reading path from temp.txt file which has 500 lines each line is a path for specific file to be copied to location "C:\opencascade" How to convert 'i' in above code to be raw string to make the code work</p> <p>Error from interpreter</p> <pre><code> copy(i,r"C:\opencascade") File "C:\Python26\lib\shutil.py", line 88, in copy copyfile(src, dst) File "C:\Python26\lib\shutil.py", line 52, in copyfile fsrc = open(src, 'rb') IOError: [Errno 22] invalid mode ('rb') or filename: 'C:\\OPENCASCADE6.2.0\\ROS\\INC\\toptools_hsequenceofshape.hxx\n' </code></pre>
2
2009-05-12T08:12:54Z
11,491,159
<p>Error is single "\" rather than double "\" in the path.</p>
0
2012-07-15T10:28:07Z
[ "python", "file-io", "copy" ]
Django ImageField issue
851,830
<p>I have a similar model</p> <pre><code>Class Student(models.Model): """A simple class which holds the basic info of a student.""" name = models.CharField(max_length=50) age = models.PositiveIntegerField() photo = models.ImageField(upload_to='foobar', blank=True, null=True) </code></pre> <p>As we can see photo field is optional. I wanted all the students who have their images saved in the college DB. For that i did this</p> <pre><code>&gt;&gt;&gt; Student.objects.exclude(photo__name=None) </code></pre> <p>But i am getting this error :</p> <pre><code>FieldError: Join on field 'photo' not permitted. </code></pre> <p>So, How can i extract all those students having their photos?</p> <p>Any sort of help regarding this would be appreciated. Thanks in advance.</p>
10
2009-05-12T08:55:06Z
852,022
<p>It doesn't work because <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#field-lookups">field lookups</a> only work on other models. Here, <code>name</code> is an attribute on the return value of your <code>photo</code> field.</p> <p>Try this instead:</p> <pre><code>Student.objects.exclude(photo__isnull=True) </code></pre> <p>It is preferred to use <code>isnull</code> instead of comparing equality to <code>None</code>.</p> <h3>EDIT:</h3> <p><a href="http://stackoverflow.com/users/89182/jeff-ober">Jeff Ober</a>'s suggestion:</p> <pre><code>Student.objects.exclude(photo='') </code></pre> <p>He says filtering is performed on the actual values stored in DB. In a file field's case the path to the file.</p>
12
2009-05-12T09:57:01Z
[ "python", "django", "django-models" ]
Build a GQL query (for Google App Engine) that has a condition on ReferenceProperty
852,055
<p>Say I have the following model:</p> <pre><code>class Schedule(db.Model): tripCode = db.StringProperty(required=True) station = db.ReferenceProperty(Station, required=True) arrivalTime = db.TimeProperty(required=True) departureTime = db.TimeProperty(required=True) </code></pre> <p>And let's say I have a Station object stored in the var <code>foo</code>.</p> <p>How do I assemble a GQL query that returns all Schedule objects with a reference to the Station object referenced by <code>foo</code>?</p> <p>This is my best (albeit <strong>incorrect</strong>) attempt to form such a query:</p> <pre><code>myQuery = "SELECT * FROM Schedule where station = " + str(foo.key()) </code></pre> <p><em>Once again <code>foo</code> is a <strong>Station</strong> object</em></p>
5
2009-05-12T10:06:18Z
854,910
<p>You shouldn't be inserting user data into a GQL string using string substitution. GQL supports parameter substitution, so you can do this:</p> <pre><code>db.GqlQuery("SELECT * FROM Schedule WHERE station = $1", foo.key()) </code></pre> <p>or, using the Query interface:</p> <pre><code>Schedule.all().filter("station =", foo.key()) </code></pre>
10
2009-05-12T21:17:11Z
[ "python", "google-app-engine", "gql" ]
Build a GQL query (for Google App Engine) that has a condition on ReferenceProperty
852,055
<p>Say I have the following model:</p> <pre><code>class Schedule(db.Model): tripCode = db.StringProperty(required=True) station = db.ReferenceProperty(Station, required=True) arrivalTime = db.TimeProperty(required=True) departureTime = db.TimeProperty(required=True) </code></pre> <p>And let's say I have a Station object stored in the var <code>foo</code>.</p> <p>How do I assemble a GQL query that returns all Schedule objects with a reference to the Station object referenced by <code>foo</code>?</p> <p>This is my best (albeit <strong>incorrect</strong>) attempt to form such a query:</p> <pre><code>myQuery = "SELECT * FROM Schedule where station = " + str(foo.key()) </code></pre> <p><em>Once again <code>foo</code> is a <strong>Station</strong> object</em></p>
5
2009-05-12T10:06:18Z
1,788,018
<p>An even easier thing to do is to change the model definition by adding the 'collection_name' field to the ReferenceProperty: </p> <blockquote> <p>station = db.ReferenceProperty(Station, required=True, collection_name="schedules")</p> </blockquote> <p>Then you can just do: </p> <blockquote> <p>foo.schedules </p> </blockquote> <p>whenever you want to get all the stations' schedules. </p>
7
2009-11-24T05:35:40Z
[ "python", "google-app-engine", "gql" ]
Anyone successfully adopted JaikuEngine?
852,268
<p>Are there real world adaptations of JaikuEngine on Google App Engine? (Question from my boss which wants to use it instead writing our own system)</p>
6
2009-05-12T11:26:33Z
1,037,339
<p>Whilst I love the App-Engine. Does your solution need to be hosted on the AppEngine? If not I would check out <a href="http://identi.ca" rel="nofollow">identi.ca</a> which is based on the Open Source <a href="http://laconi.ca/trac/" rel="nofollow">Laconi.ca</a></p>
1
2009-06-24T09:32:47Z
[ "python", "google-app-engine" ]
Anyone successfully adopted JaikuEngine?
852,268
<p>Are there real world adaptations of JaikuEngine on Google App Engine? (Question from my boss which wants to use it instead writing our own system)</p>
6
2009-05-12T11:26:33Z
1,044,077
<p>Does <a href="http://www.jaiku.com/" rel="nofollow">http://www.jaiku.com/</a> count?</p>
0
2009-06-25T13:54:31Z
[ "python", "google-app-engine" ]
Anyone successfully adopted JaikuEngine?
852,268
<p>Are there real world adaptations of JaikuEngine on Google App Engine? (Question from my boss which wants to use it instead writing our own system)</p>
6
2009-05-12T11:26:33Z
1,052,183
<p>This is jaikuengine running on AppEngine - https://jaiku.appspot.com/ If you wish to have your own version of jaiku, its pretty straightforward. Check this out- <a href="http://code.google.com/p/jaikuengine/" rel="nofollow">http://code.google.com/p/jaikuengine/</a></p>
2
2009-06-27T05:42:16Z
[ "python", "google-app-engine" ]
How the method resolution and invocation works internally in Python?
852,308
<p>How the methods invocation works in Python? I mean, how the python virtual machine interpret it.</p> <p>It's true that the python method resolution could be slower in Python that in Java. What is late binding?</p> <p>What are the differences on the reflection mechanism in these two languages? Where to find good resources explaining these aspects?</p>
5
2009-05-12T11:39:13Z
852,335
<p>Names (methods, functions, variables) are all resolved by looking at the namespace. Namespaces are implemented in CPython as <code>dict</code>s (hash maps).</p> <p>When a name is not found in the instance namespace (<code>dict</code>), python goes for the class, and then for the base classes, following the method resolution order (MRO).</p> <p>All resolving is made at runtime.</p> <p>You can play around with the <a href="http://docs.python.org/library/dis.html" rel="nofollow"><code>dis</code></a> module to see how that happens in bytecode.</p> <p>Simple example:</p> <pre><code>import dis a = 1 class X(object): def method1(self): return 15 def test_namespace(b=None): x = X() x.method1() print a print b dis.dis(test_namespace) </code></pre> <p>That prints:</p> <pre><code> 9 0 LOAD_GLOBAL 0 (X) 3 CALL_FUNCTION 0 6 STORE_FAST 1 (x) 10 9 LOAD_FAST 1 (x) 12 LOAD_ATTR 1 (method1) 15 CALL_FUNCTION 0 18 POP_TOP 11 19 LOAD_GLOBAL 2 (a) 22 PRINT_ITEM 23 PRINT_NEWLINE 12 24 LOAD_FAST 0 (b) 27 PRINT_ITEM 28 PRINT_NEWLINE 29 LOAD_CONST 0 (None) 32 RETURN_VALUE </code></pre> <p>All <code>LOAD</code>s are namespace lookups.</p>
4
2009-05-12T11:48:17Z
[ "java", "python" ]
How the method resolution and invocation works internally in Python?
852,308
<p>How the methods invocation works in Python? I mean, how the python virtual machine interpret it.</p> <p>It's true that the python method resolution could be slower in Python that in Java. What is late binding?</p> <p>What are the differences on the reflection mechanism in these two languages? Where to find good resources explaining these aspects?</p>
5
2009-05-12T11:39:13Z
852,344
<blockquote> <p>It's true that the python method resolution could be slower in Python that in Java. What is late binding?</p> </blockquote> <p>Late binding describes a strategy of how an interpreter or compiler of a particular language decides how to map an identifier to a piece of code. For example, consider writing <code>obj.Foo()</code> in C#. When you compile this, the compiler tries to find the referenced object and insert a reference to the location of the <code>Foo</code> method that will be invoked at runtime. All of this <em>method resolution</em> happens at compile time; we say that names are bound "early".</p> <p>By contrast, Python binds names "late". Method resolution happens at <em>run time</em>: the interpreter simply tries to find the referenced <code>Foo</code> method with the right signature, and if it's not there, a runtime error occurs.</p> <blockquote> <p>What are the differences on the reflection mechanism in these two languages?</p> </blockquote> <p>Dynamic languages tend to have better reflection facilities than static languages, and Python is very powerful in this respect. Still, Java has pretty extensive ways to get at the internals of classes and methods. Nevertheless, you can't get around the verbosity of Java; you'll write much more code to do the same thing in Java than you would in Python. See the <a href="http://java.sun.com/javase/6/docs/api/java/lang/reflect/package-summary.html" rel="nofollow"><strong><code>java.lang.reflect</code></strong></a> API.</p>
1
2009-05-12T11:50:34Z
[ "java", "python" ]
How the method resolution and invocation works internally in Python?
852,308
<p>How the methods invocation works in Python? I mean, how the python virtual machine interpret it.</p> <p>It's true that the python method resolution could be slower in Python that in Java. What is late binding?</p> <p>What are the differences on the reflection mechanism in these two languages? Where to find good resources explaining these aspects?</p>
5
2009-05-12T11:39:13Z
870,650
<p>Method invocation in Python consists of two distinct separable steps. First an attribute lookup is done, then the result of that lookup is invoked. This means that the following two snippets have the same semantics:</p> <pre><code>foo.bar() method = foo.bar method() </code></pre> <p>Attribute lookup in Python is a rather complex process. Say we are looking up attribute named <em>attr</em> on object <em>obj</em>, meaning the following expression in Python code: <em>obj.attr</em></p> <p>First <em>obj</em>'s instance dictionary is searched for "attr", then the instance dictionary of the class of <em>obj</em> and the dictionaries of its parent classes are searched in method resolution order for "attr".</p> <p>Normally if a value is found on the instance, that is returned. But if the lookup on the class results in a value that has both the __get__ and __set__ methods (to be exact, if a dictionary lookup on the values class and parent classes has values for both those keys) then the class attribute is regarded as something called a "data descriptor". This means that the __get__ method on that value is called, passing in the object on which the lookup occurred and the result of that value is returned. If the class attribute isn't found or isn't a data descriptor the value from the instances dictionary is returned.</p> <p>If there is no value in the instance dictionary, then the value from the class lookup is returned. Unless it happens to be a "non-data descriptor", i.e. it has the __get__ method. Then the __get__ method is invoked and the resulting value returned.</p> <p>There is one more special case, if the <em>obj</em> happens to be a class, (an instance of the type <em>type</em>), then the instance value is also checked if it's a descriptor and invoked accordingly.</p> <p>If no value is found on the instance nor its class hierarchy, and the <em>obj</em>'s class has a __getattr__ method, that method is called.</p> <p>The following shows the algorithm as encoded in Python, effectively doing what the getattr() function would do. (excluding any bugs that have slipped in)</p> <pre><code>NotFound = object() # A singleton to signify not found values def lookup_attribute(obj, attr): class_attr_value = lookup_attr_on_class(obj, attr) if is_data_descriptor(class_attr_value): return invoke_descriptor(class_attr_value, obj, obj.__class__) if attr in obj.__dict__: instance_attr_value = obj.__dict__[attr] if isinstance(obj, type) and is_descriptor(instance_attr_value): return invoke_descriptor(instance_attr_value, None, obj) return instance_attr_value if class_attr_value is NotFound: getattr_method = lookup_attr_on_class(obj, '__getattr__') if getattr_method is NotFound: raise AttributeError() return getattr_method(obj, attr) if is_descriptor(class_attr_value): return invoke_descriptor(class_attr_value, obj, obj.__class__) return class_attr_value def lookup_attr_on_class(obj, attr): for parent_class in obj.__class__.__mro__: if attr in parent_class.__dict__: return parent_class.__dict__[attr] return NotFound def is_descriptor(obj): if lookup_attr_on_class(obj, '__get__') is NotFound: return False return True def is_data_descriptor(obj): if not is_descriptor(obj) or lookup_attr_on_class(obj, '__set__') is NotFound : return False return True def invoke_descriptor(descriptor, obj, cls): descriptormethod = lookup_attr_on_class(descriptor, '__get__') return descriptormethod(descriptor, obj, cls) </code></pre> <p>What does all this descriptor nonsense have to with method invocation you ask? Well the thing is, that functions are also objects, and they happen to implement the descriptor protocol. If the attribute lookup finds a function object on the class, it's __get__ methods gets called and returns a "bound method" object. A bound method is just a small wrapper around the function object that stores the object that the function was looked up on, and when invoked, prepends that object to the argument list (where usually for functions that are meant to methods the <em>self</em> argument is).</p> <p>Here's some illustrative code:</p> <pre><code>class Function(object): def __get__(self, obj, cls): return BoundMethod(obj, cls, self.func) # Init and call added so that it would work as a function # decorator if you'd like to experiment with it yourself def __init__(self, the_actual_implementation): self.func = the_actual_implementation def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) class BoundMethod(object): def __init__(self, obj, cls, func): self.obj, self.cls, self.func = obj, cls, func def __call__(self, *args, **kwargs): if self.obj is not None: return self.func(self.obj, *args, **kwargs) elif isinstance(args[0], self.cls): return self.func(*args, **kwargs) raise TypeError("Unbound method expects an instance of %s as first arg" % self.cls) </code></pre> <p>For method resolution order (which in Python's case actually means attribute resolution order) Python uses the C3 algorithm from Dylan. It is too complicated to explain here, so if you're interested see <a href="http://www.python.org/download/releases/2.3/mro/">this article</a>. Unless you are doing some really funky inheritance hierarchies (and you shouldn't), it is enough to know that the lookup order is left to right, depth first, and all subclasses of a class are searched before that class is searched.</p>
7
2009-05-15T20:10:24Z
[ "java", "python" ]
M2Crypto Encrypt/Decrypt using AES256
852,332
<p>Can someone provide me code to encrypt / decrypt using m2crypto aes256 CBC using Python</p>
6
2009-05-12T11:47:20Z
853,525
<p>When it comes to security nothing beats reading the documentation.</p> <p><a href="http://chandlerproject.org/bin/view/Projects/MeTooCrypto" rel="nofollow">http://chandlerproject.org/bin/view/Projects/MeTooCrypto</a></p> <p>Even if I took the time to understand and make the perfect code for you to copy and paste, you would have no idea if I did a good job or not. Not very helpful I know, but I wish you luck and secure data.</p>
-1
2009-05-12T15:56:19Z
[ "python", "aes", "m2crypto" ]
M2Crypto Encrypt/Decrypt using AES256
852,332
<p>Can someone provide me code to encrypt / decrypt using m2crypto aes256 CBC using Python</p>
6
2009-05-12T11:47:20Z
854,417
<p>M2Crypto's documentation is terrible. Sometimes the OpenSSL documentation (m2crypto wraps OpenSSL) can help. Your best bet is to look at the M2Crypto unit tests -- <a href="http://svn.osafoundation.org/m2crypto/trunk/tests/test_evp.py">http://svn.osafoundation.org/m2crypto/trunk/tests/test_evp.py</a> -- look for the <code>test_AES()</code> method.</p>
12
2009-05-12T19:24:30Z
[ "python", "aes", "m2crypto" ]
M2Crypto Encrypt/Decrypt using AES256
852,332
<p>Can someone provide me code to encrypt / decrypt using m2crypto aes256 CBC using Python</p>
6
2009-05-12T11:47:20Z
855,045
<p>Take a look at <a href="http://pypi.python.org/pypi/m2secret/" rel="nofollow">m2secret</a>:</p> <blockquote> <p>Small utility and module for encrypting and decrypting data using symmetric-key algorithms. By default uses 256-bit AES (Rijndael) using CBC, but some options are configurable. PBKDF2 algorithm used to derive key from password.</p> </blockquote>
2
2009-05-12T21:48:36Z
[ "python", "aes", "m2crypto" ]
M2Crypto Encrypt/Decrypt using AES256
852,332
<p>Can someone provide me code to encrypt / decrypt using m2crypto aes256 CBC using Python</p>
6
2009-05-12T11:47:20Z
19,002,390
<pre><code>def encrypt_file(key, in_filename, out_filename,iv): cipher=M2Crypto.EVP.Cipher('aes_256_cfb',key,iv, op=1) with open(in_filename, 'rb') as infile: with open(out_filename, 'wb') as outfile: outfile.write(b) while True: buf = infile.read(1024) if not buf: break outfile.write(cipher.update(buf)) outfile.write( cipher.final() ) outfile.close() infile.close() def decrypt_file(key, in_filename, out_filename,iv): cipher = M2Crypto.EVP.Cipher("aes_256_cfb",key , iv, op = 0) with open(in_filename, 'rb') as infile: with open(out_filename, 'wb') as outfile: while True: buf = infile.read(1024) if not buf: break try: outfile.write(cipher.update(buf)) except: print "here" outfile.write( cipher.final() ) outfile.close() infile.close() </code></pre>
1
2013-09-25T10:26:01Z
[ "python", "aes", "m2crypto" ]
M2Crypto Encrypt/Decrypt using AES256
852,332
<p>Can someone provide me code to encrypt / decrypt using m2crypto aes256 CBC using Python</p>
6
2009-05-12T11:47:20Z
37,945,148
<p>I use following wrapper around M2Crypto (borrowed from <a href="https://cryptography.io/en/latest/fernet/" rel="nofollow">cryptography.io</a>):</p> <pre><code>import os import base64 import M2Crypto class SymmetricEncryption(object): @staticmethod def generate_key(): return base64.b64encode(os.urandom(48)) def __init__(self, key): key = base64.b64decode(key) self.iv = key[:16] self.key = key[16:] def encrypt(self, plaintext): ENCRYPT = 1 cipher = M2Crypto.EVP.Cipher(alg='aes_256_cbc', key=self.key, iv=self.iv, op=ENCRYPT) ciphertext = cipher.update(plaintext) + cipher.final() return base64.b64encode(ciphertext) def decrypt(self, cyphertext): DECRYPT = 0 cipher = M2Crypto.EVP.Cipher(alg='aes_256_cbc', key=self.key, iv=self.iv, op=DECRYPT) plaintext = cipher.update(base64.b64decode(cyphertext)) + cipher.final() return plaintext </code></pre>
1
2016-06-21T12:58:51Z
[ "python", "aes", "m2crypto" ]
Python: getting a reference to a function from inside itself
852,401
<p>If I define a function:</p> <pre><code>def f(x): return x+3 </code></pre> <p>I can later store objects as attributes of the function, like so:</p> <pre><code>f.thing="hello!" </code></pre> <p>I would like to do this from inside the code of the function itself. Problem is, how do I get a reference to the function from inside itself?</p>
18
2009-05-12T12:06:30Z
852,455
<p>The same way, just use its name.</p> <pre><code>&gt;&gt;&gt; def g(x): ... g.r = 4 ... &gt;&gt;&gt; g &lt;function g at 0x0100AD68&gt; &gt;&gt;&gt; g(3) &gt;&gt;&gt; g.r 4 </code></pre>
19
2009-05-12T12:16:43Z
[ "python", "function", "self-reference" ]
Python: getting a reference to a function from inside itself
852,401
<p>If I define a function:</p> <pre><code>def f(x): return x+3 </code></pre> <p>I can later store objects as attributes of the function, like so:</p> <pre><code>f.thing="hello!" </code></pre> <p>I would like to do this from inside the code of the function itself. Problem is, how do I get a reference to the function from inside itself?</p>
18
2009-05-12T12:06:30Z
852,456
<p>If you are trying to do memoization, you can use a dictionary as a default parameter:</p> <pre><code>def f(x, memo={}): if x not in memo: memo[x] = x + 3 return memo[x] </code></pre>
3
2009-05-12T12:17:10Z
[ "python", "function", "self-reference" ]
Python: getting a reference to a function from inside itself
852,401
<p>If I define a function:</p> <pre><code>def f(x): return x+3 </code></pre> <p>I can later store objects as attributes of the function, like so:</p> <pre><code>f.thing="hello!" </code></pre> <p>I would like to do this from inside the code of the function itself. Problem is, how do I get a reference to the function from inside itself?</p>
18
2009-05-12T12:06:30Z
852,971
<p>Or use a closure:</p> <pre><code>def gen_f(): memo = dict() def f(x): try: return memo[x] except KeyError: memo[x] = x + 3 return f f = gen_f() f(123) </code></pre> <p>Somewhat nicer IMHO</p>
2
2009-05-12T14:07:34Z
[ "python", "function", "self-reference" ]
How to dynamically compose an OR query filter in Django?
852,414
<p>From an example you can see a multiple OR query filter:</p> <pre><code>Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) </code></pre> <p>For example, this results in:</p> <pre><code>[&lt;Article: Hello&gt;, &lt;Article: Goodbye&gt;, &lt;Article: Hello and goodbye&gt;] </code></pre> <p>However, I want to create this query filter from a list. How to do that?</p> <p>e.g. <code>[1, 2, 3] -&gt; Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))</code></p>
45
2009-05-12T12:08:51Z
852,423
<p>See the <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#in-bulk-id-list">docs</a>:</p> <pre><code>&gt;&gt;&gt; Blog.objects.in_bulk([1]) {1: &lt;Blog: Beatles Blog&gt;} &gt;&gt;&gt; Blog.objects.in_bulk([1, 2]) {1: &lt;Blog: Beatles Blog&gt;, 2: &lt;Blog: Cheddar Talk&gt;} &gt;&gt;&gt; Blog.objects.in_bulk([]) {} </code></pre> <p>Note that this method only works for primary key lookups, but that seems to be what you're trying to do.</p> <p>So what you want is:</p> <pre><code>Article.objects.in_bulk([1, 2, 3]) </code></pre>
7
2009-05-12T12:11:18Z
[ "python", "django", "django-q" ]
How to dynamically compose an OR query filter in Django?
852,414
<p>From an example you can see a multiple OR query filter:</p> <pre><code>Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) </code></pre> <p>For example, this results in:</p> <pre><code>[&lt;Article: Hello&gt;, &lt;Article: Goodbye&gt;, &lt;Article: Hello and goodbye&gt;] </code></pre> <p>However, I want to create this query filter from a list. How to do that?</p> <p>e.g. <code>[1, 2, 3] -&gt; Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))</code></p>
45
2009-05-12T12:08:51Z
852,427
<p>You can use the |= operator to programmatically update a query using Q objects.</p>
4
2009-05-12T12:12:30Z
[ "python", "django", "django-q" ]
How to dynamically compose an OR query filter in Django?
852,414
<p>From an example you can see a multiple OR query filter:</p> <pre><code>Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) </code></pre> <p>For example, this results in:</p> <pre><code>[&lt;Article: Hello&gt;, &lt;Article: Goodbye&gt;, &lt;Article: Hello and goodbye&gt;] </code></pre> <p>However, I want to create this query filter from a list. How to do that?</p> <p>e.g. <code>[1, 2, 3] -&gt; Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))</code></p>
45
2009-05-12T12:08:51Z
852,428
<p>Maybe it's better to use sql IN statement.</p> <pre><code>Article.objects.filter(id__in=[1, 2, 3]) </code></pre> <p>See <a href="http://docs.djangoproject.com/en/1.0/ref/models/querysets/#in">queryset api reference</a>.</p> <p>If you really need to make queries with dynamic logic, you can do something like this (ugly + not tested):</p> <pre><code>query = Q(field=1) for cond in (2, 3): query = query | Q(field=cond) Article.objects.filter(query) </code></pre>
15
2009-05-12T12:12:40Z
[ "python", "django", "django-q" ]
How to dynamically compose an OR query filter in Django?
852,414
<p>From an example you can see a multiple OR query filter:</p> <pre><code>Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) </code></pre> <p>For example, this results in:</p> <pre><code>[&lt;Article: Hello&gt;, &lt;Article: Goodbye&gt;, &lt;Article: Hello and goodbye&gt;] </code></pre> <p>However, I want to create this query filter from a list. How to do that?</p> <p>e.g. <code>[1, 2, 3] -&gt; Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))</code></p>
45
2009-05-12T12:08:51Z
852,481
<p>You could chain your queries as follows:</p> <pre><code>values = [1,2,3] # Turn list of values into list of Q objects queries = [Q(pk=value) for value in values] # Take one Q object from the list query = queries.pop() # Or the Q object with the ones remaining in the list for item in queries: query |= item # Query the model Article.objects.filter(query) </code></pre>
73
2009-05-12T12:21:28Z
[ "python", "django", "django-q" ]
How to dynamically compose an OR query filter in Django?
852,414
<p>From an example you can see a multiple OR query filter:</p> <pre><code>Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) </code></pre> <p>For example, this results in:</p> <pre><code>[&lt;Article: Hello&gt;, &lt;Article: Goodbye&gt;, &lt;Article: Hello and goodbye&gt;] </code></pre> <p>However, I want to create this query filter from a list. How to do that?</p> <p>e.g. <code>[1, 2, 3] -&gt; Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))</code></p>
45
2009-05-12T12:08:51Z
897,884
<p>A shorter way of writing Dave Webb's answer using <a href="http://docs.python.org/library/functions.html#reduce">python's reduce function</a>:</p> <pre><code>values = [1,2,3] # Turn list of values into one big Q objects query = reduce(lambda q,value: q|Q(pk=value), values, Q()) # Query the model Article.objects.filter(query) </code></pre>
30
2009-05-22T13:36:12Z
[ "python", "django", "django-q" ]
How to dynamically compose an OR query filter in Django?
852,414
<p>From an example you can see a multiple OR query filter:</p> <pre><code>Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) </code></pre> <p>For example, this results in:</p> <pre><code>[&lt;Article: Hello&gt;, &lt;Article: Goodbye&gt;, &lt;Article: Hello and goodbye&gt;] </code></pre> <p>However, I want to create this query filter from a list. How to do that?</p> <p>e.g. <code>[1, 2, 3] -&gt; Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))</code></p>
45
2009-05-12T12:08:51Z
898,170
<pre><code>values = [1, 2, 3] query = reduce(operator.or_, (Q(pk=x) for x in values)) </code></pre>
19
2009-05-22T14:34:19Z
[ "python", "django", "django-q" ]
How to dynamically compose an OR query filter in Django?
852,414
<p>From an example you can see a multiple OR query filter:</p> <pre><code>Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) </code></pre> <p>For example, this results in:</p> <pre><code>[&lt;Article: Hello&gt;, &lt;Article: Goodbye&gt;, &lt;Article: Hello and goodbye&gt;] </code></pre> <p>However, I want to create this query filter from a list. How to do that?</p> <p>e.g. <code>[1, 2, 3] -&gt; Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))</code></p>
45
2009-05-12T12:08:51Z
12,568,718
<p>In case we want to programmatically set what db field we want to query: </p> <pre><code>import operator questions = [('question__contains', 'test'), ('question__gt', 23 )] q_list = [Q(x) for x in questions] Poll.objects.filter(reduce(operator.or_, q_list)) </code></pre>
3
2012-09-24T16:01:10Z
[ "python", "django", "django-q" ]
How to dynamically compose an OR query filter in Django?
852,414
<p>From an example you can see a multiple OR query filter:</p> <pre><code>Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) </code></pre> <p>For example, this results in:</p> <pre><code>[&lt;Article: Hello&gt;, &lt;Article: Goodbye&gt;, &lt;Article: Hello and goodbye&gt;] </code></pre> <p>However, I want to create this query filter from a list. How to do that?</p> <p>e.g. <code>[1, 2, 3] -&gt; Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))</code></p>
45
2009-05-12T12:08:51Z
25,094,050
<p>This one is for dynamic pk list:</p> <pre><code>pk_list = qs.values_list('pk', flat=True) # i.e [] or [1, 2, 3] if len(pk_list) == 0: Article.objects.none() else: q = None for pk in pk_list: if q is None: q = Q(pk=pk) else: q = q | Q(pk=pk) Article.objects.filter(q) </code></pre>
1
2014-08-02T10:30:20Z
[ "python", "django", "django-q" ]
How to dynamically compose an OR query filter in Django?
852,414
<p>From an example you can see a multiple OR query filter:</p> <pre><code>Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) </code></pre> <p>For example, this results in:</p> <pre><code>[&lt;Article: Hello&gt;, &lt;Article: Goodbye&gt;, &lt;Article: Hello and goodbye&gt;] </code></pre> <p>However, I want to create this query filter from a list. How to do that?</p> <p>e.g. <code>[1, 2, 3] -&gt; Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))</code></p>
45
2009-05-12T12:08:51Z
29,149,972
<p>To build more complex queries there is also the option to use built in Q() object's constants Q.OR and Q.AND together with the add() method like so:</p> <pre><code>list = [1, 2, 3] # it gets a bit more complicated if we want to dynamically build # OR queries with dynamic/unknown db field keys, let's say with a list # of db fields that can change like the following # list_with_strings = ['dbfield1', 'dbfield2', 'dbfield3'] # init our q objects variable to use .add() on it q_objects = Q() # loop trough the list and create an OR condition for each item for item in list: q_objects.add(Q(pk=item), Q.OR) # for our list_with_strings we can do the following # q_objects.add(Q(**{item: 1}), Q.OR) queryset = Article.objects.filter(q_objects) # sometimes the following is helpful for debugging (returns the SQL statement) # print queryset.query </code></pre>
22
2015-03-19T16:26:07Z
[ "python", "django", "django-q" ]
How to dynamically compose an OR query filter in Django?
852,414
<p>From an example you can see a multiple OR query filter:</p> <pre><code>Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) </code></pre> <p>For example, this results in:</p> <pre><code>[&lt;Article: Hello&gt;, &lt;Article: Goodbye&gt;, &lt;Article: Hello and goodbye&gt;] </code></pre> <p>However, I want to create this query filter from a list. How to do that?</p> <p>e.g. <code>[1, 2, 3] -&gt; Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))</code></p>
45
2009-05-12T12:08:51Z
34,359,299
<p>easy..<br> from django.db.models import Q import you model args = (Q(visibility=1)|(Q(visibility=0)&amp;Q(user=self.user))) #Tuple parameters={} #dic order = 'create_at' limit = 10</p> <pre><code>Models.objects.filter(*args,**parameters).order_by(order)[:limit] </code></pre>
0
2015-12-18T15:50:12Z
[ "python", "django", "django-q" ]