title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Can bin() be overloaded like oct() and hex() in Python 2.6?
1,002,116
<p>In Python 2.6 (and earlier) the <code>hex()</code> and <code>oct()</code> built-in functions can be overloaded in a class by defining <code>__hex__</code> and <code>__oct__</code> special functions. However there is not a <code>__bin__</code> special function for overloading the behaviour of Python 2.6's new <code>bin()</code> built-in function.</p> <p>I want to know if there is any way of flexibly overloading <code>bin()</code>, and if not I was wondering why the inconsistent interface?</p> <p>I do know that the <code>__index__</code> special function can be used, but this isn't flexible as it can only return an integer. My particular use case is from the <a href="http://code.google.com/p/python-bitstring/">bitstring</a> module, where leading zero bits are considered significant:</p> <pre><code>&gt;&gt;&gt; a = BitString(length=12) # Twelve zero bits &gt;&gt;&gt; hex(a) '0x000' &gt;&gt;&gt; oct(a) '0o0000' &gt;&gt;&gt; bin(a) '0b0' &lt;------ I want it to output '0b000000000000' </code></pre> <p>I suspect that there's no way of achieving this, but I thought it wouldn't hurt to ask!</p>
12
2009-06-16T15:08:55Z
1,002,694
<p>You could achieve the same behaviour as for hex and oct by overriding/replacing the built in bin() function with your own implementation that attempted to call <strong>bin</strong> on the object being passed and fell back to the standard bin() function if the object didn't provide <strong>bin</strong>. However, on the basis that explicit is better than implicit, coding your application to depend on a custom version of bin() is probably not a good idea so maybe just give the function a different name e.g.</p> <pre><code>def mybin(n): try: return n.__bin__() except AttributeError: return bin(n) </code></pre> <p>As for why the inconsistency in the interface, I'm not sure. Maybe it's because bin() was added more recently so it's a slight oversight?</p>
0
2009-06-16T16:49:54Z
[ "python", "binary", "overloading", "python-2.6" ]
Can bin() be overloaded like oct() and hex() in Python 2.6?
1,002,116
<p>In Python 2.6 (and earlier) the <code>hex()</code> and <code>oct()</code> built-in functions can be overloaded in a class by defining <code>__hex__</code> and <code>__oct__</code> special functions. However there is not a <code>__bin__</code> special function for overloading the behaviour of Python 2.6's new <code>bin()</code> built-in function.</p> <p>I want to know if there is any way of flexibly overloading <code>bin()</code>, and if not I was wondering why the inconsistent interface?</p> <p>I do know that the <code>__index__</code> special function can be used, but this isn't flexible as it can only return an integer. My particular use case is from the <a href="http://code.google.com/p/python-bitstring/">bitstring</a> module, where leading zero bits are considered significant:</p> <pre><code>&gt;&gt;&gt; a = BitString(length=12) # Twelve zero bits &gt;&gt;&gt; hex(a) '0x000' &gt;&gt;&gt; oct(a) '0o0000' &gt;&gt;&gt; bin(a) '0b0' &lt;------ I want it to output '0b000000000000' </code></pre> <p>I suspect that there's no way of achieving this, but I thought it wouldn't hurt to ask!</p>
12
2009-06-16T15:08:55Z
1,011,888
<p>As you've already discovered, you can't override <code>bin()</code>, but it doesn't sound like you need to do that. You just want a 0-padded binary value. Unfortunately in python 2.5 and previous, you couldn't use "%b" to indicate binary, so you can't use the "%" string formatting operator to achieve the result you want.</p> <p>Luckily python 2.6 does offer what you want, in the form of the new <a href="http://docs.python.org/library/string.html#string-formatting">str.format()</a> method. I believe that this particular bit of line-noise is what you're looking for:</p> <pre><code>&gt;&gt;&gt; '{0:010b}'.format(19) '0000010011' </code></pre> <p>The syntax for this mini-language is under "<a href="http://docs.python.org/library/string.html#format-specification-mini-language">format specification mini-language</a>" in the docs. To save you some time, I'll explain the string that I'm using:</p> <ol> <li>parameter zero (i.e. <code>19</code>) should be formatted, using</li> <li>a magic "<code>0</code>" to indicate that I want 0-padded, right-aligned number, with</li> <li>10 digits of precision, in</li> <li>binary format.</li> </ol> <p>You can use this syntax to achieve a variety of creative versions of alignment and padding.</p>
11
2009-06-18T10:04:34Z
[ "python", "binary", "overloading", "python-2.6" ]
Can bin() be overloaded like oct() and hex() in Python 2.6?
1,002,116
<p>In Python 2.6 (and earlier) the <code>hex()</code> and <code>oct()</code> built-in functions can be overloaded in a class by defining <code>__hex__</code> and <code>__oct__</code> special functions. However there is not a <code>__bin__</code> special function for overloading the behaviour of Python 2.6's new <code>bin()</code> built-in function.</p> <p>I want to know if there is any way of flexibly overloading <code>bin()</code>, and if not I was wondering why the inconsistent interface?</p> <p>I do know that the <code>__index__</code> special function can be used, but this isn't flexible as it can only return an integer. My particular use case is from the <a href="http://code.google.com/p/python-bitstring/">bitstring</a> module, where leading zero bits are considered significant:</p> <pre><code>&gt;&gt;&gt; a = BitString(length=12) # Twelve zero bits &gt;&gt;&gt; hex(a) '0x000' &gt;&gt;&gt; oct(a) '0o0000' &gt;&gt;&gt; bin(a) '0b0' &lt;------ I want it to output '0b000000000000' </code></pre> <p>I suspect that there's no way of achieving this, but I thought it wouldn't hurt to ask!</p>
12
2009-06-16T15:08:55Z
1,087,788
<p>I think the short answer is 'No, <code>bin()</code> can't be overloaded like <code>oct()</code> and <code>hex()</code>.'</p> <p>As to why, the answer must lie with Python 3.0, which uses <code>__index__</code> to overload <code>hex()</code>, <code>oct()</code> and <code>bin()</code>, and has removed the <code>__oct__</code> and <code>__hex__</code> special functions altogether.</p> <p>So the Python 2.6 <code>bin()</code> looks very much like it's really a Python 3.0 feature that has been back-ported without much consideration that it's doing things the new Python 3 way rather than the old Python 2 way. I'd also guess that it's unlikely to get fixed, even if it is considered to be a bug.</p>
4
2009-07-06T16:01:13Z
[ "python", "binary", "overloading", "python-2.6" ]
Getting distutils to install prebuilt compiled libraries?
1,002,581
<p>I manage an open source project (<A HREF="http://code.google.com/p/echo-nest-remix">Remix</A>, the source is available there) written in python. We ask users to run python setup.py install to install the software. Recently we added a compiled C++ package (a port of SoundTouch -- go to trunk/externals in the source to see it.) We'd like the setup.py file that installs the base Remix libraries to also install the pysoundtouch14 library.</p> <p>However, we don't want users to have to have a gcc or msvc toolchain on their system. We've precompiled binaries for common platforms (linux-i386, windows, mac 10.5 and 10.6), go to trunk/externals/pysoundtouch14/build to see them. I was hoping that a user who does not have gcc or msvc installed could just run pysoundtouch14's setup.py and it would detect the presence of our prebuilt binaries and just copy them to the right place (/Library/Python/2.5/site-packages, for example.) But that doesn't happen. On a new 10.5 system, for example, setup.py complains about no gcc being installed even though the .so it needs to install is already built in the build/ folder.</p> <p>So I have two direct questions: <UL><LI>How can I get setup.py to just "install" prebuilt .so and .pyd files in the right place automatically depending on the platform without requiring a build system? <LI>How can one setup.py (our main setup.py file) also run the setup.py of another included package (pysoundtouch14's setup.py?) </ul></p>
9
2009-06-16T16:27:03Z
1,004,167
<p>Unfortunately, I'd say that overriding install command is the way to go.</p> <p>This can be done easily, using custom distribution command. For example, see [1] <a href="http://svn.zope.org/Zope/branches/2.9/setup.py?rev=69978&amp;view=auto" rel="nofollow">http://svn.zope.org/Zope/branches/2.9/setup.py?rev=69978&amp;view=auto</a></p>
1
2009-06-16T21:55:44Z
[ "python", "open-source", "installer", "compiled" ]
Getting distutils to install prebuilt compiled libraries?
1,002,581
<p>I manage an open source project (<A HREF="http://code.google.com/p/echo-nest-remix">Remix</A>, the source is available there) written in python. We ask users to run python setup.py install to install the software. Recently we added a compiled C++ package (a port of SoundTouch -- go to trunk/externals in the source to see it.) We'd like the setup.py file that installs the base Remix libraries to also install the pysoundtouch14 library.</p> <p>However, we don't want users to have to have a gcc or msvc toolchain on their system. We've precompiled binaries for common platforms (linux-i386, windows, mac 10.5 and 10.6), go to trunk/externals/pysoundtouch14/build to see them. I was hoping that a user who does not have gcc or msvc installed could just run pysoundtouch14's setup.py and it would detect the presence of our prebuilt binaries and just copy them to the right place (/Library/Python/2.5/site-packages, for example.) But that doesn't happen. On a new 10.5 system, for example, setup.py complains about no gcc being installed even though the .so it needs to install is already built in the build/ folder.</p> <p>So I have two direct questions: <UL><LI>How can I get setup.py to just "install" prebuilt .so and .pyd files in the right place automatically depending on the platform without requiring a build system? <LI>How can one setup.py (our main setup.py file) also run the setup.py of another included package (pysoundtouch14's setup.py?) </ul></p>
9
2009-06-16T16:27:03Z
1,008,159
<p>Your first question is a tough one given the multiplatform requirement. If it was just windows, you could use the post-installation script option to run a script to handle the libraries or just use a non-python tool such as <a href="http://nsis.sourceforge.net/Main%5FPage" rel="nofollow">NSIS</a>. I'm not sure what else can be done other than Almad's suggestion.</p> <p>For your second question, you might want to look into <a href="http://www.blueskyonmars.com/projects/paver/" rel="nofollow" title="Paver">Paver</a>.</p>
1
2009-06-17T16:24:01Z
[ "python", "open-source", "installer", "compiled" ]
Automate SSH login under windows
1,002,627
<p>I want to be able to execute openssh with some custom arguments and then be able to automatically login to the server. I want that my script will enter the password if needed and inject 'yes' if I'm prompted to add the fingerprint to the known hosts.</p> <p>I've found SharpSsh for C# that do that, but I also need to use -D parameter and use ProxyCommand that I define in SSH, and the library is quite lacking for that usage.</p> <p>Another thing that I've found was pexcept for Python that should do the trick but I couldn't find where to download it, on the offical page I'm being redirectred from sourceforge to some broken link.</p> <p>Any help would be appreciated,</p> <p>Bill.</p>
1
2009-06-16T16:34:38Z
1,002,641
<p>I hope <a href="http://search.cpan.org/perldoc?Net::SSH::Expect" rel="nofollow">Net::SSH::Expect</a> Perl module will be of help to you.</p>
-1
2009-06-16T16:38:02Z
[ "c#", "python", "windows", "ssh" ]
Automate SSH login under windows
1,002,627
<p>I want to be able to execute openssh with some custom arguments and then be able to automatically login to the server. I want that my script will enter the password if needed and inject 'yes' if I'm prompted to add the fingerprint to the known hosts.</p> <p>I've found SharpSsh for C# that do that, but I also need to use -D parameter and use ProxyCommand that I define in SSH, and the library is quite lacking for that usage.</p> <p>Another thing that I've found was pexcept for Python that should do the trick but I couldn't find where to download it, on the offical page I'm being redirectred from sourceforge to some broken link.</p> <p>Any help would be appreciated,</p> <p>Bill.</p>
1
2009-06-16T16:34:38Z
1,002,674
<p>If you use <a href="http://www.openssh.com/" rel="nofollow"><strong>OpenSSH</strong></a> and then have a script to inject password in clear (meaning, you have stored the password unencrypted) it is defeating the purpose of secure shell. </p> <p>Please strongly consider using <a href="http://www.ssh.com/support/documentation/online/ssh/adminguide/32/Public-Key%5FAuthentication-2.html" rel="nofollow"><strong>public key mechanisms</strong></a> which can be easily and securely automated.</p>
9
2009-06-16T16:46:13Z
[ "c#", "python", "windows", "ssh" ]
Automate SSH login under windows
1,002,627
<p>I want to be able to execute openssh with some custom arguments and then be able to automatically login to the server. I want that my script will enter the password if needed and inject 'yes' if I'm prompted to add the fingerprint to the known hosts.</p> <p>I've found SharpSsh for C# that do that, but I also need to use -D parameter and use ProxyCommand that I define in SSH, and the library is quite lacking for that usage.</p> <p>Another thing that I've found was pexcept for Python that should do the trick but I couldn't find where to download it, on the offical page I'm being redirectred from sourceforge to some broken link.</p> <p>Any help would be appreciated,</p> <p>Bill.</p>
1
2009-06-16T16:34:38Z
1,002,820
<p>i use pexpect for similar purpose and download also work? <a href="http://sourceforge.net/project/downloading.php?group_id=59762&amp;filename=pexpect-2.3.tar.gz" rel="nofollow">http://sourceforge.net/project/downloading.php?group_id=59762&amp;filename=pexpect-2.3.tar.gz</a></p> <p>here is a portion fro my ssh automate script, you can customize it for you usage it may not run out of the box</p> <pre><code>import os import getpass import pexpect import glob import logging import shutil import time class UpdateError(Exception): pass g_password = None def runSshCommand(cmd): global g_password ssh_newkey = 'Are you sure you want to continue connecting' # my ssh command line p=pexpect.spawn(cmd) i=p.expect([ssh_newkey,'password:',pexpect.EOF]) if i==0: print "Saying yes to connection.." p.sendline('yes') i=p.expect([ssh_newkey,'password:',pexpect.EOF]) if i==1: while True: if g_password is None: g_password = getpass.getpass("password:") p.sendline(g_password) i = p.expect(['password:',pexpect.EOF]) if i==0: g_password = None print "Wrong password" else: break elif i==2: raise UpdateError("Got key or connection timeout") return p.before </code></pre>
2
2009-06-16T17:15:02Z
[ "c#", "python", "windows", "ssh" ]
Automate SSH login under windows
1,002,627
<p>I want to be able to execute openssh with some custom arguments and then be able to automatically login to the server. I want that my script will enter the password if needed and inject 'yes' if I'm prompted to add the fingerprint to the known hosts.</p> <p>I've found SharpSsh for C# that do that, but I also need to use -D parameter and use ProxyCommand that I define in SSH, and the library is quite lacking for that usage.</p> <p>Another thing that I've found was pexcept for Python that should do the trick but I couldn't find where to download it, on the offical page I'm being redirectred from sourceforge to some broken link.</p> <p>Any help would be appreciated,</p> <p>Bill.</p>
1
2009-06-16T16:34:38Z
1,003,245
<p>I'll second the recommendation to use public key authentication. Rather than hack around with expect, you might want to consider <a href="http://www.lag.net/paramiko/" rel="nofollow">Paramiko</a> - it's a native SSH client for Python which would greatly simplify the communications process, particularly if you ever need to interact with the remote server and it has support for things like SFTP built-in.</p>
3
2009-06-16T18:42:31Z
[ "c#", "python", "windows", "ssh" ]
Automate SSH login under windows
1,002,627
<p>I want to be able to execute openssh with some custom arguments and then be able to automatically login to the server. I want that my script will enter the password if needed and inject 'yes' if I'm prompted to add the fingerprint to the known hosts.</p> <p>I've found SharpSsh for C# that do that, but I also need to use -D parameter and use ProxyCommand that I define in SSH, and the library is quite lacking for that usage.</p> <p>Another thing that I've found was pexcept for Python that should do the trick but I couldn't find where to download it, on the offical page I'm being redirectred from sourceforge to some broken link.</p> <p>Any help would be appreciated,</p> <p>Bill.</p>
1
2009-06-16T16:34:38Z
1,003,860
<p>There is some <a href="http://www.ualberta.ca/CNS/RESEARCH/LinuxClusters/pka-putty.html" rel="nofollow">excellent documentation</a> on using <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/" rel="nofollow">Putty</a> with generated SSH key authentication. This is an easy and secure way to accomplish your goals. <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/" rel="nofollow">Putty</a> has a great set of features, for a windows SSH app. Even better when you consider that you can <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html" rel="nofollow">get it on the free</a>.</p>
1
2009-06-16T20:46:55Z
[ "c#", "python", "windows", "ssh" ]
Automate SSH login under windows
1,002,627
<p>I want to be able to execute openssh with some custom arguments and then be able to automatically login to the server. I want that my script will enter the password if needed and inject 'yes' if I'm prompted to add the fingerprint to the known hosts.</p> <p>I've found SharpSsh for C# that do that, but I also need to use -D parameter and use ProxyCommand that I define in SSH, and the library is quite lacking for that usage.</p> <p>Another thing that I've found was pexcept for Python that should do the trick but I couldn't find where to download it, on the offical page I'm being redirectred from sourceforge to some broken link.</p> <p>Any help would be appreciated,</p> <p>Bill.</p>
1
2009-06-16T16:34:38Z
11,246,704
<p><code>pexpect</code> can't import on Windows. So, I use <code>plink.exe</code> with a Python subprocess to connect to the ssh server.</p>
0
2012-06-28T14:18:57Z
[ "c#", "python", "windows", "ssh" ]
Automate SSH login under windows
1,002,627
<p>I want to be able to execute openssh with some custom arguments and then be able to automatically login to the server. I want that my script will enter the password if needed and inject 'yes' if I'm prompted to add the fingerprint to the known hosts.</p> <p>I've found SharpSsh for C# that do that, but I also need to use -D parameter and use ProxyCommand that I define in SSH, and the library is quite lacking for that usage.</p> <p>Another thing that I've found was pexcept for Python that should do the trick but I couldn't find where to download it, on the offical page I'm being redirectred from sourceforge to some broken link.</p> <p>Any help would be appreciated,</p> <p>Bill.</p>
1
2009-06-16T16:34:38Z
20,374,140
<p>Another way is to to use openssh and establish a trusted key; if both client and the user account on the server have this key, then openssh does not request a password.</p> <p>I have a script that automates setup of this - it works under cygwin,</p> <p><a href="http://mosermichael.github.io/cstuff/all/projects/2011/07/14/ssh-friends.html" rel="nofollow">http://mosermichael.github.io/cstuff/all/projects/2011/07/14/ssh-friends.html</a></p>
0
2013-12-04T11:28:46Z
[ "c#", "python", "windows", "ssh" ]
pygtk loading a flow of image in only one pixbuf
1,002,841
<p>I'm trying to embed a chartdrawer library that can only give me a bmp image in a buffer.</p> <p>I'm loading this image and have to explicitly call delete on the newly created pixbuf and then call the garbage collector.</p> <p>The drawing method is called each 50ms</p> <p>calling the garbage collector is realy CPU consuming.</p> <p>Is there a way to have only one pixbuf for the all process and thus not have to call gc?</p> <p>Or am I doing everything wrong?</p> <p>Thx in advance for any help</p> <p>Raphaël</p> <p>code:</p> <pre><code> def draw(self, drawArea): #init bmp loader loader = gtk.gdk.PixbufLoader ('bmp') #get a bmp buffer chart = drawArea.outBMP2() #load this buffer loader.write(chart) loader.close() #get the newly created pixbuf pixbuf = loader.get_pixbuf() #and load it in the gtk.Image self.img.set_from_pixbuf(pixbuf) del pixbuf gc.collect() </code></pre>
2
2009-06-16T17:18:09Z
1,004,987
<p>You don't need to call the garbage collector. Python is automatically garbage collected. At the end of your method, <code>pixbuf</code> falls out of scope (you also don't need "<code>del pixbuf</code>") and will be automatically garbage collected. So for starters, delete the last two lines of your method.</p> <p>You might also want to just call your 'draw' method less often, if it's consuming too much CPU. In most applications I imagine the user could deal with updates every 200ms rather than every 50, if every 50ms means there's going to be a CPU problem.</p>
1
2009-06-17T03:36:32Z
[ "python", "pygtk" ]
Large Sqlite database search
1,002,953
<p>How is it possible to implement an efficient large Sqlite db search (more than 90000 entries)?</p> <p>I'm using Python and SQLObject ORM:</p> <pre><code> import re ... def search1(): cr = re.compile(ur'foo') for item in Item.select(): if cr.search(item.name) or cr.search(item.skim): print item.name </code></pre> <p>This function runs in more than 30 seconds. How should I make it run faster? </p> <p><strong>UPD</strong>: The test:</p> <pre><code> for item in Item.select(): pass </code></pre> <p>... takes almost the same time as my initial function (0:00:33.093141 to 0:00:33.322414). So the regexps eat no time.</p> <p>A Sqlite3 shell query:</p> <pre><code> select '' from item where name like '%foo%'; </code></pre> <p>runs in about a second. So the main time consumption happens due to the inefficient ORM's data retrieval from db. I guess SQLObject grabs entire rows here, while Sqlite touches only necessary fields.</p>
2
2009-06-16T17:46:18Z
1,002,972
<p>The best way would be to rework your logic to do the selection in the database instead of in your python program.</p> <p>Instead of doing Item.select(), you should rework it to do Item.select("""name LIKE ....</p> <p>If you do this, and make sure you have the name and skim columns indexed, it will return very quickly. 90000 entries is not a large database.</p>
3
2009-06-16T17:50:45Z
[ "python", "sql", "database", "search", "performance" ]
Large Sqlite database search
1,002,953
<p>How is it possible to implement an efficient large Sqlite db search (more than 90000 entries)?</p> <p>I'm using Python and SQLObject ORM:</p> <pre><code> import re ... def search1(): cr = re.compile(ur'foo') for item in Item.select(): if cr.search(item.name) or cr.search(item.skim): print item.name </code></pre> <p>This function runs in more than 30 seconds. How should I make it run faster? </p> <p><strong>UPD</strong>: The test:</p> <pre><code> for item in Item.select(): pass </code></pre> <p>... takes almost the same time as my initial function (0:00:33.093141 to 0:00:33.322414). So the regexps eat no time.</p> <p>A Sqlite3 shell query:</p> <pre><code> select '' from item where name like '%foo%'; </code></pre> <p>runs in about a second. So the main time consumption happens due to the inefficient ORM's data retrieval from db. I guess SQLObject grabs entire rows here, while Sqlite touches only necessary fields.</p>
2
2009-06-16T17:46:18Z
1,002,995
<p>If you really need to use a regular expression, there's not really anything you can do to speed that up tremendously. </p> <p>The best thing would be to write an sqlite function that performs the comparison for you in the db engine, instead of Python.</p> <p>You could also switch to a db server like postgresql that has support for SIMILAR. </p> <p><a href="http://www.postgresql.org/docs/8.3/static/functions-matching.html" rel="nofollow">http://www.postgresql.org/docs/8.3/static/functions-matching.html</a></p>
0
2009-06-16T17:57:03Z
[ "python", "sql", "database", "search", "performance" ]
Large Sqlite database search
1,002,953
<p>How is it possible to implement an efficient large Sqlite db search (more than 90000 entries)?</p> <p>I'm using Python and SQLObject ORM:</p> <pre><code> import re ... def search1(): cr = re.compile(ur'foo') for item in Item.select(): if cr.search(item.name) or cr.search(item.skim): print item.name </code></pre> <p>This function runs in more than 30 seconds. How should I make it run faster? </p> <p><strong>UPD</strong>: The test:</p> <pre><code> for item in Item.select(): pass </code></pre> <p>... takes almost the same time as my initial function (0:00:33.093141 to 0:00:33.322414). So the regexps eat no time.</p> <p>A Sqlite3 shell query:</p> <pre><code> select '' from item where name like '%foo%'; </code></pre> <p>runs in about a second. So the main time consumption happens due to the inefficient ORM's data retrieval from db. I guess SQLObject grabs entire rows here, while Sqlite touches only necessary fields.</p>
2
2009-06-16T17:46:18Z
1,003,217
<p>30 seconds to fetch 90,000 rows might not be all that bad.</p> <p>Have you benchmarked the time required to do the following?</p> <pre><code> for item in Item.select(): pass </code></pre> <p>Just to see if the time is DB time, network time or application time?</p> <p>If your SQLite DB is physically very large, you could be looking at -- simply -- a lot of physical I/O to read all that database stuff in. </p>
2
2009-06-16T18:35:45Z
[ "python", "sql", "database", "search", "performance" ]
Large Sqlite database search
1,002,953
<p>How is it possible to implement an efficient large Sqlite db search (more than 90000 entries)?</p> <p>I'm using Python and SQLObject ORM:</p> <pre><code> import re ... def search1(): cr = re.compile(ur'foo') for item in Item.select(): if cr.search(item.name) or cr.search(item.skim): print item.name </code></pre> <p>This function runs in more than 30 seconds. How should I make it run faster? </p> <p><strong>UPD</strong>: The test:</p> <pre><code> for item in Item.select(): pass </code></pre> <p>... takes almost the same time as my initial function (0:00:33.093141 to 0:00:33.322414). So the regexps eat no time.</p> <p>A Sqlite3 shell query:</p> <pre><code> select '' from item where name like '%foo%'; </code></pre> <p>runs in about a second. So the main time consumption happens due to the inefficient ORM's data retrieval from db. I guess SQLObject grabs entire rows here, while Sqlite touches only necessary fields.</p>
2
2009-06-16T17:46:18Z
1,005,168
<p>Given your example and expanding on Reed's answer your code could look a bit like the following:</p> <pre><code>import re import sqlalchemy.sql.expression as expr ... def search1(): searchStr = ur'foo' whereClause = expr.or_(itemsTable.c.nameColumn.contains(searchStr), itemsTable.c.skimColumn.contains(searchStr)) for item in Items.select().where(whereClause): print item.name </code></pre> <p>which translates to</p> <pre><code>SELECT * FROM items WHERE name LIKE '%foo%' or skim LIKE '%foo%' </code></pre> <p>This will have the database do all the filtering work for you instead of fetching all 90000 records and doing possibly two regex operations on each record.</p> <p><a href="http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/schema.html?highlight=contains#sqlalchemy.schema.Column.contains" rel="nofollow">You can find some info here on the .contains() method here</a>.</p> <p>As well as the <a href="http://www.sqlalchemy.org/docs/05/sqlexpression.html" rel="nofollow">SQLAlchemy SQL Expression Language Tutorial here</a>.</p> <p>Of course the example above assumes variable names for your itemsTable and the column it has (nameColumn and skimColumn).</p>
0
2009-06-17T04:47:57Z
[ "python", "sql", "database", "search", "performance" ]
Large Sqlite database search
1,002,953
<p>How is it possible to implement an efficient large Sqlite db search (more than 90000 entries)?</p> <p>I'm using Python and SQLObject ORM:</p> <pre><code> import re ... def search1(): cr = re.compile(ur'foo') for item in Item.select(): if cr.search(item.name) or cr.search(item.skim): print item.name </code></pre> <p>This function runs in more than 30 seconds. How should I make it run faster? </p> <p><strong>UPD</strong>: The test:</p> <pre><code> for item in Item.select(): pass </code></pre> <p>... takes almost the same time as my initial function (0:00:33.093141 to 0:00:33.322414). So the regexps eat no time.</p> <p>A Sqlite3 shell query:</p> <pre><code> select '' from item where name like '%foo%'; </code></pre> <p>runs in about a second. So the main time consumption happens due to the inefficient ORM's data retrieval from db. I guess SQLObject grabs entire rows here, while Sqlite touches only necessary fields.</p>
2
2009-06-16T17:46:18Z
1,006,065
<p>I would definitely take a suggestion of Reed to pass the filter to the SQL (forget the index part though).</p> <p>I do not think that selecting only specified fields or all fields make a difference (unless you do have a lot of large fields). I would bet that SQLObject creates/instanciates 80K objects and puts them into a Session/UnitOfWork for tracking. This could definitely take some time.</p> <p>Also if you do not need objects in your session, there must be a way to select just what the fields you need using custom-query creation so that no <code>Item</code> objects are created, but only tuples.</p>
0
2009-06-17T09:40:09Z
[ "python", "sql", "database", "search", "performance" ]
Large Sqlite database search
1,002,953
<p>How is it possible to implement an efficient large Sqlite db search (more than 90000 entries)?</p> <p>I'm using Python and SQLObject ORM:</p> <pre><code> import re ... def search1(): cr = re.compile(ur'foo') for item in Item.select(): if cr.search(item.name) or cr.search(item.skim): print item.name </code></pre> <p>This function runs in more than 30 seconds. How should I make it run faster? </p> <p><strong>UPD</strong>: The test:</p> <pre><code> for item in Item.select(): pass </code></pre> <p>... takes almost the same time as my initial function (0:00:33.093141 to 0:00:33.322414). So the regexps eat no time.</p> <p>A Sqlite3 shell query:</p> <pre><code> select '' from item where name like '%foo%'; </code></pre> <p>runs in about a second. So the main time consumption happens due to the inefficient ORM's data retrieval from db. I guess SQLObject grabs entire rows here, while Sqlite touches only necessary fields.</p>
2
2009-06-16T17:46:18Z
1,802,218
<p>Initially doing regex via Python was considered for y_serial, but that was dropped in favor of SQLite's GLOB (which is far faster). GLOB is similar to LIKE except that it's syntax is more conventional: * instead of %, ? instead of _ .</p> <p>See the Endnotes at <a href="http://yserial.sourceforge.net/" rel="nofollow">http://yserial.sourceforge.net/</a> for more details. </p>
0
2009-11-26T08:11:01Z
[ "python", "sql", "database", "search", "performance" ]
python web framework large project
1,003,131
<p>I need your advices to choose a Python Web Framework for developing a large project:</p> <p>Database (Postgresql)will have at least 500 tables, most of them with a composite primary key, lots of constraints, indexes &amp; queries. About 1,500 views for starting. The project belongs to the financial area. Alwasy new requirements are coming.</p> <p>Will a ORM be helpful?</p>
4
2009-06-16T18:21:43Z
1,003,161
<p>Django has been used by many large organizations (Washington Post, etc.) and can connect with Postgresql easily enough. I use it fairly often and have had no trouble.</p>
13
2009-06-16T18:26:09Z
[ "python", "frameworks", "web-frameworks" ]
python web framework large project
1,003,131
<p>I need your advices to choose a Python Web Framework for developing a large project:</p> <p>Database (Postgresql)will have at least 500 tables, most of them with a composite primary key, lots of constraints, indexes &amp; queries. About 1,500 views for starting. The project belongs to the financial area. Alwasy new requirements are coming.</p> <p>Will a ORM be helpful?</p>
4
2009-06-16T18:21:43Z
1,003,173
<p>Yes. An ORM is essential for mapping SQL stuff to objects. </p> <p>You have three choices.</p> <ol> <li><p>Use someone else's ORM</p></li> <li><p>Roll your own.</p></li> <li><p>Try to execute low-level SQL queries and pick out the fields they want from the result set. This is -- actually -- a kind of ORM with the mappings scattered throughout the applications. It may be fast to execute and appear easy to develop, but it is a maintenance nightmare.</p></li> </ol> <p>If you're designing the tables first, any ORM will be painful. For example, "composite primary key" is generally a bad idea, and with an ORM it's almost always a bad idea. You'll need to have a surrogate primary key. Then you can have all the composite keys with indexes you want. They just won't be "primary".</p> <p>If you design the objects first, then work out tables that will implement the objects, the ORM will be pleasant, simple and will run quickly, also.</p>
7
2009-06-16T18:28:34Z
[ "python", "frameworks", "web-frameworks" ]
python web framework large project
1,003,131
<p>I need your advices to choose a Python Web Framework for developing a large project:</p> <p>Database (Postgresql)will have at least 500 tables, most of them with a composite primary key, lots of constraints, indexes &amp; queries. About 1,500 views for starting. The project belongs to the financial area. Alwasy new requirements are coming.</p> <p>Will a ORM be helpful?</p>
4
2009-06-16T18:21:43Z
1,003,218
<blockquote> <p>Alwasy new requirements are coming.</p> </blockquote> <p>So what you really need is a framework that will allow you to adapt rapidly to changing specs.</p> <p>From personal experience, I can only discuss django, which is great because it allows you to get up and running quickly. </p> <p>If you stick to its ORM, you will have a pretty easy time getting your models fleshed out and connected in useful ways. You will need to familiarize yourself with a database migration tool, because Django does not have one built in. <a href="http://code.google.com/p/dmigrations/" rel="nofollow">dmigrations</a> seems to be a leading tool for this.</p> <p>Another choice for ORM's is <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>, which appears to be a bit more mature out of the box. </p>
0
2009-06-16T18:36:03Z
[ "python", "frameworks", "web-frameworks" ]
python web framework large project
1,003,131
<p>I need your advices to choose a Python Web Framework for developing a large project:</p> <p>Database (Postgresql)will have at least 500 tables, most of them with a composite primary key, lots of constraints, indexes &amp; queries. About 1,500 views for starting. The project belongs to the financial area. Alwasy new requirements are coming.</p> <p>Will a ORM be helpful?</p>
4
2009-06-16T18:21:43Z
1,003,329
<p>Depending on what you want to do, you actually have a few possible frameworks :</p> <p>[Django] Big, strong (to the limit of what a python framework can be), and the older in the race. Used by a few 'big' sites around the world ([Django sites]). Still is a bit of an overkill for almost everything and with a deprecated coding approach.</p> <p>[Turbogears] is a recent framework based on Pylons. Don't know much about it, but got many good feedbacks from friends who tried it.</p> <p>[Pylons] ( which Turbogears2 is based on ). Often saw at the "PHP of Python" , it allow very quick developements from scratch. Even if it can seem inappropriate for big projects, it's often the faster and easier way to go.</p> <p>The last option is [Zope] ( with or without Plone ), but Plone is way to slow, and Zope learning curve is way too long ( not even speaking in replacing the ZODB with an SQL connector ) so if you don't know the framework yet, just forget about it.</p> <p>And yes, An ORM seem mandatory for a project of this size. For Django, you'll have to handle migration to their database models (don't know how hard it is to plug SQLAlchemy in Django). For turbogears and Pylons, the most suitable solution is [SQLAlchemy], which is actually the most complete ( and rising ) ORM for python. For zope ... well, nevermind</p> <p>Last but not least, I'm not sure you're starting on a good basis for your project. 500 tables on any python framework would scare me to death. A boring but rigid language such as java (hibernate+spring+tapestry or so) seem really more appropriate.</p>
2
2009-06-16T18:55:24Z
[ "python", "frameworks", "web-frameworks" ]
python web framework large project
1,003,131
<p>I need your advices to choose a Python Web Framework for developing a large project:</p> <p>Database (Postgresql)will have at least 500 tables, most of them with a composite primary key, lots of constraints, indexes &amp; queries. About 1,500 views for starting. The project belongs to the financial area. Alwasy new requirements are coming.</p> <p>Will a ORM be helpful?</p>
4
2009-06-16T18:21:43Z
1,003,423
<p>Since most of your tables have composite primary keys, you'll want an ORM that supports that functionality. Django's default ORM does not support composite primary keys. SQLAlchemy does have that support (<a href="http://www.sqlalchemy.org/features.html" rel="nofollow">http://www.sqlalchemy.org/features.html</a>). </p> <p>The TurboGears framework uses SQLAlchemy as its default ORM. Pylons lets you use SQLAlchemy as well. </p> <p>There are also ways to get Django to use SQLAlchemy, though I've not tried them myself. I prefer to use Django myself, but given your needs, I'd go with Pylons or TurboGears rather then shoe-horning a different ORM into the system.</p>
5
2009-06-16T19:12:15Z
[ "python", "frameworks", "web-frameworks" ]
python web framework large project
1,003,131
<p>I need your advices to choose a Python Web Framework for developing a large project:</p> <p>Database (Postgresql)will have at least 500 tables, most of them with a composite primary key, lots of constraints, indexes &amp; queries. About 1,500 views for starting. The project belongs to the financial area. Alwasy new requirements are coming.</p> <p>Will a ORM be helpful?</p>
4
2009-06-16T18:21:43Z
1,005,238
<p>For such horrid data-layer complexity as 500 tables with 1500 views, differently from most answers, I would personally prefer to stick with SQL (PostgreSQL offers a really excellent implementation thereof, expecially in the new 8.4 version which you should really lobby for if you have any chance); the only ORM I would [grudgingly] accept is SQLAlchemy (one of the few ORBs I don't really mind -- but the main added value is portability to different DBMS: if you're committed to just one, and in a project of this DB complexity you'd better be, then my personal opinion is that <em>any</em> ORM is just overhead, as the data-access layer developers will need deep familiarity with the specific DBMS to crawl towards acceptable performance).</p> <p>Having picked "raw psycopg2" or SQLAlchemy as the technology for my data-access layer, that would rule out Django (which in my experience only works well with its own ORM -- but that's not suitable for a project of such DB complexity, IMNSHO). I'd go with Werkzeug, personally, as the framework most suitable for highly complex projects requiring ridiculous amounts of flexibility and power -- though Pylons and Turbogears 2 on top of it may be acceptable as a fall-back if the team just doesn't have the web app experience and skill it takes to make truly beautiful music with a flexible framework such as Werkzeug.</p> <p>Last but not least, I'd strongly lobby for Dojo for the presentation layer on the client -- a rich and strongly structured Javascript framework, offering superbly designed functionality for "local data", host access, &amp;c, optimized for the best that each of several browsers (and plug-ins such as Gears) can offer, as well as advanced UI functionality, seems likeliest to lighten the heavy development burden on the back-end team (in fact, I'd strongly recommend looking at offering an essentially RESTful interface on the server side, and delegate all presentation work to Dojo on the client -- see <a href="http://www.thinserverarchitecture.com/" rel="nofollow">this site</a> for more, except I'd be thinking of JSON rather than XML as the preferred interchange format). But, I'll readily admit to knowing far less about the UI side of things than about back-ends, business logic and overall architecture, so take this last paragraph for what it's worth!-)</p>
3
2009-06-17T05:19:23Z
[ "python", "frameworks", "web-frameworks" ]
python web framework large project
1,003,131
<p>I need your advices to choose a Python Web Framework for developing a large project:</p> <p>Database (Postgresql)will have at least 500 tables, most of them with a composite primary key, lots of constraints, indexes &amp; queries. About 1,500 views for starting. The project belongs to the financial area. Alwasy new requirements are coming.</p> <p>Will a ORM be helpful?</p>
4
2009-06-16T18:21:43Z
2,246,687
<p>I would absolutely recommend Repoze.bfg with SQLAlchemy for what you describe. I've done projects now in Django, TurboGears 1, TurboGears 2, Pylons, and dabbled in pure Zope3. BFG is far and away the framework most designed to accomodate a project growing in ways you don't anticipate at the beginning, but is far more lightweight and pared down than Grok or Zope 3. Also, the docs are the best technical docs of all of them, not the <em>easiest</em>, but the ones that answer the hard questions you're going to encounter the best. I'm currently doing a similar thing where we are overhauling a bunch of legacy databases into a new web deliverable app and we're using BFG, some Pylons, Zope 3 adapters, Genshi for templating, SQLAlchemy, and Dojo for the front end. We couldn't be happier with BFG, and it's working out great. BFGs classes as views that are actually zope multi-adapters is absolutely perfect for being able to override only very specific bits for certain domain resources. And the complete lack of magic globals anywhere makes testing and packaging the easiest we've had with any framework.</p> <p>ymmv!</p>
1
2010-02-11T18:29:58Z
[ "python", "frameworks", "web-frameworks" ]
App Engine Datastore IN Operator - how to use?
1,003,247
<p>Reading: <a href="http://code.google.com/appengine/docs/python/datastore/gqlreference.html" rel="nofollow">http://code.google.com/appengine/docs/python/datastore/gqlreference.html</a></p> <p>I want to use:</p> <p> := IN </p> <p>but am unsure how to make it work. Let's assume the following</p> <pre><code>class User(db.Model): name = db.StringProperty() class UniqueListOfSavedItems(db.Model): str = db.StringPropery() datesaved = db.DateTimeProperty() class UserListOfSavedItems(db.Model): name = db.ReferenceProperty(User, collection='user') str = db.ReferenceProperty(UniqueListOfSavedItems, collection='itemlist') </code></pre> <p>How can I do a query which gets me the list of saved items for a user? Obviously I can do:</p> <pre><code>q = db.Gql("SELECT * FROM UserListOfSavedItems WHERE name :=", user[0].name) </code></pre> <p>but that gets me a list of keys. I want to now take that list and get it into a query to get the str field out of UniqueListOfSavedItems. I thought I could do:</p> <pre><code>q2 = db.Gql("SELECT * FROM UniqueListOfSavedItems WHERE := str in q") </code></pre> <p>but something's not right...any ideas? Is it (am at my day job, so can't test this now):</p> <pre><code>q2 = db.Gql("SELECT * FROM UniqueListOfSavedItems __key__ := str in q) </code></pre> <p>side note: what a devilishly difficult problem to search on because all I really care about is the "IN" operator.</p>
3
2009-06-16T18:42:38Z
1,003,656
<p>+1 to Adam for getting me on the right track. Based on his pointer, and doing some searching at Code Search, I have the following solution.</p> <pre><code>usersaveditems = User.Gql(“Select * from UserListOfSavedItems where user =:1”, userkey) saveditemkeys = [] for item in usersaveditems: #this should create a list of keys (references) to the saved item table saveditemkeys.append(item.str()) if len(usersavedsearches &gt; 0): #and this should get me the items that a user saved useritems = db.Gql(“SELECT * FROM UniqueListOfSavedItems WHERE __key__ in :1’, saveditemkeys) </code></pre>
0
2009-06-16T20:03:35Z
[ "python", "google-app-engine", "gql", "gae-datastore" ]
App Engine Datastore IN Operator - how to use?
1,003,247
<p>Reading: <a href="http://code.google.com/appengine/docs/python/datastore/gqlreference.html" rel="nofollow">http://code.google.com/appengine/docs/python/datastore/gqlreference.html</a></p> <p>I want to use:</p> <p> := IN </p> <p>but am unsure how to make it work. Let's assume the following</p> <pre><code>class User(db.Model): name = db.StringProperty() class UniqueListOfSavedItems(db.Model): str = db.StringPropery() datesaved = db.DateTimeProperty() class UserListOfSavedItems(db.Model): name = db.ReferenceProperty(User, collection='user') str = db.ReferenceProperty(UniqueListOfSavedItems, collection='itemlist') </code></pre> <p>How can I do a query which gets me the list of saved items for a user? Obviously I can do:</p> <pre><code>q = db.Gql("SELECT * FROM UserListOfSavedItems WHERE name :=", user[0].name) </code></pre> <p>but that gets me a list of keys. I want to now take that list and get it into a query to get the str field out of UniqueListOfSavedItems. I thought I could do:</p> <pre><code>q2 = db.Gql("SELECT * FROM UniqueListOfSavedItems WHERE := str in q") </code></pre> <p>but something's not right...any ideas? Is it (am at my day job, so can't test this now):</p> <pre><code>q2 = db.Gql("SELECT * FROM UniqueListOfSavedItems __key__ := str in q) </code></pre> <p>side note: what a devilishly difficult problem to search on because all I really care about is the "IN" operator.</p>
3
2009-06-16T18:42:38Z
1,005,813
<p>Since you have a list of keys, you don't need to do a second query - you can do a batch fetch, instead. Try this:</p> <pre><code>#and this should get me the items that a user saved useritems = db.get(saveditemkeys) </code></pre> <p>(Note you don't even need the guard clause - a db.get on 0 entities is short-circuited appropritely.)</p> <p>What's the difference, you may ask? Well, a db.get takes about 20-40ms. A query, on the other hand (GQL or not) takes about 160-200ms. But wait, it gets worse! The IN operator is implemented in Python, and translates to multiple queries, which are executed serially. So if you do a query with an IN filter for 10 keys, you're doing 10 separate 160ms-ish query operations, for a total of about 1.6 seconds latency. A single db.get, in contrast, will have the same effect and take a total of about 30ms.</p>
9
2009-06-17T08:34:16Z
[ "python", "google-app-engine", "gql", "gae-datastore" ]
Number of visitors in Django
1,003,302
<p>In Django, how can I see the number of current visitors? Or how do I determine the number of active sessions?</p> <p>Is this a good method?</p> <p>use django.contrib.sessions.models.Session, set the expiry time short. Every time when somebody does something on the site, update expiry time. Then count the number of sessions that are not expired.</p>
2
2009-06-16T18:50:48Z
1,003,346
<p>You might want to look into something like <a href="http://code.google.com/p/django-tracking/" rel="nofollow">django-tracking</a> for this.</p> <blockquote> <p>django-tracking is a simple attempt at keeping track of visitors to Django-powered Web sites. It also offers basic blacklisting capabilities.</p> </blockquote> <p><strong>Edit</strong>: As for your updated question... [Answer redacted after being corrected by muhuk]</p> <p>Alternatively, I liked the response to this question: <a href="http://stackoverflow.com/questions/978333/how-do-i-find-out-total-number-of-sessions-created-i-e-number-of-logged-in-users">How do I find out total number of sessions created i.e. number of logged in users?</a></p> <p>You might want to try that instead.</p>
6
2009-06-16T18:58:40Z
[ "python", "django" ]
Number of visitors in Django
1,003,302
<p>In Django, how can I see the number of current visitors? Or how do I determine the number of active sessions?</p> <p>Is this a good method?</p> <p>use django.contrib.sessions.models.Session, set the expiry time short. Every time when somebody does something on the site, update expiry time. Then count the number of sessions that are not expired.</p>
2
2009-06-16T18:50:48Z
1,004,658
<p>Edit: Added some more information about why I present this answer here. I found chartbeat when I tried to answer this same question for my django based site. I don't work for them.</p> <p>Not specifically Django, but chartbeat.com is very interesting to add to a website as well.</p> <p>django-tracking is great, +1 for that answer, etc. </p> <p>Couple of things I could not do with django-tracking, that chartbeat helped with; tracked interactions with completely cached pages which never hit the django tracking code and pages not delivered through django (e.g. wordpress, etc.)</p>
-2
2009-06-17T01:22:00Z
[ "python", "django" ]
Number of visitors in Django
1,003,302
<p>In Django, how can I see the number of current visitors? Or how do I determine the number of active sessions?</p> <p>Is this a good method?</p> <p>use django.contrib.sessions.models.Session, set the expiry time short. Every time when somebody does something on the site, update expiry time. Then count the number of sessions that are not expired.</p>
2
2009-06-16T18:50:48Z
8,544,439
<p>There is also a little application django-visits to track visits <a href="https://bitbucket.org/jespino/django-visits" rel="nofollow">https://bitbucket.org/jespino/django-visits</a></p>
0
2011-12-17T11:35:50Z
[ "python", "django" ]
Number of visitors in Django
1,003,302
<p>In Django, how can I see the number of current visitors? Or how do I determine the number of active sessions?</p> <p>Is this a good method?</p> <p>use django.contrib.sessions.models.Session, set the expiry time short. Every time when somebody does something on the site, update expiry time. Then count the number of sessions that are not expired.</p>
2
2009-06-16T18:50:48Z
23,576,572
<p><a href="https://github.com/bruth/django-tracking2" rel="nofollow">django-tracking2</a> can be helpful to track the visitors.</p> <p>As specially this is easy to configure in the deployment like AWS, because it is not required any dependency and environment variables.</p> <p>django-tracking2 tracks the length of time visitors and registered users spend on your site. Although this will work for websites, this is more applicable to web <em>applications</em> with registered users. This does not replace (nor intend) to replace client-side analytics which is great for understanding aggregate flow of page views.</p>
3
2014-05-10T02:43:27Z
[ "python", "django" ]
Python Video Framework
1,003,376
<p>I'm looking for a Python framework that will enable me to play video as well as draw on that video (for labeling purposes). </p> <p>I've tried Pyglet, but this doesn't seem to work particularly well - when drawing on an existing video, there is flicker (even with double buffering and all of that good stuff), and there doesn't seem to be a way to get the frame index in the video during the per-frame callback (only elapsed time since the last frame).</p>
4
2009-06-16T19:03:57Z
1,003,439
<p>Qt (PyQt) has Phonon, which might help out. PyQt is available as GPL or payware. (Qt has LGPL too, but the PyQt wrappers don't)</p>
2
2009-06-16T19:14:12Z
[ "python", "video", "pyglet" ]
Python Video Framework
1,003,376
<p>I'm looking for a Python framework that will enable me to play video as well as draw on that video (for labeling purposes). </p> <p>I've tried Pyglet, but this doesn't seem to work particularly well - when drawing on an existing video, there is flicker (even with double buffering and all of that good stuff), and there doesn't seem to be a way to get the frame index in the video during the per-frame callback (only elapsed time since the last frame).</p>
4
2009-06-16T19:03:57Z
1,003,833
<p>Try the <a href="http://gstreamer.freedesktop.org/modules/gst-python.html" rel="nofollow">Python bindings for GStreamer</a>.</p>
2
2009-06-16T20:40:17Z
[ "python", "video", "pyglet" ]
Python Video Framework
1,003,376
<p>I'm looking for a Python framework that will enable me to play video as well as draw on that video (for labeling purposes). </p> <p>I've tried Pyglet, but this doesn't seem to work particularly well - when drawing on an existing video, there is flicker (even with double buffering and all of that good stuff), and there doesn't seem to be a way to get the frame index in the video during the per-frame callback (only elapsed time since the last frame).</p>
4
2009-06-16T19:03:57Z
1,003,840
<p>Try a Python wrapper for OpenCV such as <a href="http://code.google.com/p/ctypes-opencv/" rel="nofollow">ctypes-opencv</a>. The C API reference is <a href="http://code.google.com/p/ctypes-opencv/" rel="nofollow">here</a>, and the wrapper is very close (see docstrings for any changes).</p> <p>I have used it to draw on video without any flicker, so you should have no problems with that.</p> <p>A rough outline of calls you need:</p> <ul> <li>Load video with cvCreateFileCapture, load font with cvFont.</li> <li>Grab frame with cvQueryFrame, increment your frame counter.</li> <li>Draw on the frame with cvPutText, cvEllipse, etc etc.</li> <li>Display to user with cvShowImage.</li> </ul>
2
2009-06-16T20:42:03Z
[ "python", "video", "pyglet" ]
How to import a module from a directory on level above the current script
1,003,843
<p>For my Python application, I have the following directories structure:</p> <pre><code>\myapp \myapp\utils\ \myapp\utils\GChartWrapper\ \myapp\model\ \myapp\view\ \myapp\controller\ </code></pre> <p>One of my class in \myapp\view\ must import a class called <a href="http://code.google.com/p/google-chartwrapper/">GChartWrapper</a>. However, I am getting an import error...</p> <pre><code>myview.py from myapp.utils.GChartWrapper import * </code></pre> <p>Here is the error:</p> <pre><code>&lt;type 'exceptions.ImportError'&gt;: No module named GChartWrapper.GChart args = ('No module named GChartWrapper.GChart',) message = 'No module named GChartWrapper.GChart' </code></pre> <p>What am I doing wrong? I really have a hard time to import modules/classes in Python...</p>
8
2009-06-16T20:42:51Z
1,003,872
<p>You can change the path where python looks for files.</p> <p>At the top of your source file, add:</p> <pre><code>import sys sys.path.append("..") </code></pre> <p>Or alternatively change the environment variable:</p> <pre><code>export PYTHONPATH=.. </code></pre>
2
2009-06-16T20:49:47Z
[ "python", "import", "gchart" ]
How to import a module from a directory on level above the current script
1,003,843
<p>For my Python application, I have the following directories structure:</p> <pre><code>\myapp \myapp\utils\ \myapp\utils\GChartWrapper\ \myapp\model\ \myapp\view\ \myapp\controller\ </code></pre> <p>One of my class in \myapp\view\ must import a class called <a href="http://code.google.com/p/google-chartwrapper/">GChartWrapper</a>. However, I am getting an import error...</p> <pre><code>myview.py from myapp.utils.GChartWrapper import * </code></pre> <p>Here is the error:</p> <pre><code>&lt;type 'exceptions.ImportError'&gt;: No module named GChartWrapper.GChart args = ('No module named GChartWrapper.GChart',) message = 'No module named GChartWrapper.GChart' </code></pre> <p>What am I doing wrong? I really have a hard time to import modules/classes in Python...</p>
8
2009-06-16T20:42:51Z
1,003,918
<p>The <a href="http://code.google.com/p/google-chartwrapper/source/browse/trunk/GChartWrapper/%5F%5Finit%5F%5F.py"><code>__init__.py</code> file</a> of the GChartWrapper package expects the GChartWrapper package on PYTHONPATH. You can tell by the first line:</p> <pre><code>from GChartWrapper.GChart import * </code></pre> <p>Is it necessary to have the GChartWrapper included package in your package directory structure? If so, then one thing you could do is adding the path where the package resides to sys.path at run time. I take it <code>myview.py</code> is in the <code>myapp\view</code> directory? Then you could do this before importing <code>GChartWrapper</code>:</p> <pre><code>import sys import os sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'utils'))) </code></pre> <p>If it is not necessary to have it in your directory structure, it could be easier to have it installed at the conventional location. You can do that by running the setup.py script that's included in the GChartWrapper source distribution.</p>
7
2009-06-16T21:01:55Z
[ "python", "import", "gchart" ]
How to import a module from a directory on level above the current script
1,003,843
<p>For my Python application, I have the following directories structure:</p> <pre><code>\myapp \myapp\utils\ \myapp\utils\GChartWrapper\ \myapp\model\ \myapp\view\ \myapp\controller\ </code></pre> <p>One of my class in \myapp\view\ must import a class called <a href="http://code.google.com/p/google-chartwrapper/">GChartWrapper</a>. However, I am getting an import error...</p> <pre><code>myview.py from myapp.utils.GChartWrapper import * </code></pre> <p>Here is the error:</p> <pre><code>&lt;type 'exceptions.ImportError'&gt;: No module named GChartWrapper.GChart args = ('No module named GChartWrapper.GChart',) message = 'No module named GChartWrapper.GChart' </code></pre> <p>What am I doing wrong? I really have a hard time to import modules/classes in Python...</p>
8
2009-06-16T20:42:51Z
1,003,949
<p>Or starting in python 2.5 (again assuming myview is in myapp\view:</p> <pre><code>from __future__ import absolute_import from ..utils.GChartWrapper import * </code></pre> <p>See: <a href="http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports" rel="nofollow">http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports</a></p>
2
2009-06-16T21:10:36Z
[ "python", "import", "gchart" ]
How to import a module from a directory on level above the current script
1,003,843
<p>For my Python application, I have the following directories structure:</p> <pre><code>\myapp \myapp\utils\ \myapp\utils\GChartWrapper\ \myapp\model\ \myapp\view\ \myapp\controller\ </code></pre> <p>One of my class in \myapp\view\ must import a class called <a href="http://code.google.com/p/google-chartwrapper/">GChartWrapper</a>. However, I am getting an import error...</p> <pre><code>myview.py from myapp.utils.GChartWrapper import * </code></pre> <p>Here is the error:</p> <pre><code>&lt;type 'exceptions.ImportError'&gt;: No module named GChartWrapper.GChart args = ('No module named GChartWrapper.GChart',) message = 'No module named GChartWrapper.GChart' </code></pre> <p>What am I doing wrong? I really have a hard time to import modules/classes in Python...</p>
8
2009-06-16T20:42:51Z
1,003,970
<p>You don't import modules and packages from arbritary paths. Instead, in python you use packages and absolute imports. That'll avoid all future problems.</p> <p>Example:</p> <p>create the following files:</p> <pre><code>MyApp\myapp\__init__.py MyApp\myapp\utils\__init__.py MyApp\myapp\utils\charts.py MyApp\myapp\model\__init__.py MyApp\myapp\view\__init__.py MyApp\myapp\controller\__init__.py MyApp\run.py MyApp\setup.py MyApp\README </code></pre> <p>The files should be empty except for those:</p> <p><strong><code>MyApp\myapp\utils\charts.py:</code></strong></p> <pre><code>class GChartWrapper(object): def __init__(self): print "DEBUG: An instance of GChartWrapper is being created!" </code></pre> <p><strong><code>MyApp\myapp\view\__init__.py:</code></strong></p> <pre><code>from myapp.utils.charts import GChartWrapper def start(): c = GChartWrapper() # creating instance of the class </code></pre> <p><strong><code>MyApp\run.py:</code></strong></p> <pre><code>from myapp.view import start start() </code></pre> <p>That's all! When you run your entry point (<code>run.py</code>) it calls a function on the view, and that creates an instance of the GChartWrapper class. Using this structure you can import anything anywhere and use it.</p> <p>To complement, in <code>MyApp\setup.py</code> you write an installation program for the MyApp\myapp package. Use <a href="http://docs.python.org/distutils">distutils</a> to write it:</p> <pre><code>from distutils.core import setup setup(name='MyApp', version='1.0', description='My Beautiful Application', author='Martin', author_email='martin@xxxxxxx.com', url='http://stackoverflow.com/questions/1003843/', packages=['myapp'], scripts=['run.py'] ) </code></pre> <p>That is enough. Now when people download the MyApp folder, they can just install it using setup.py and run it using run.py. Distutils can generate packages in a number of formats including windows installable .EXE</p> <p>It's the standard way of distributing python packages/applications.</p>
5
2009-06-16T21:15:02Z
[ "python", "import", "gchart" ]
How to import a module from a directory on level above the current script
1,003,843
<p>For my Python application, I have the following directories structure:</p> <pre><code>\myapp \myapp\utils\ \myapp\utils\GChartWrapper\ \myapp\model\ \myapp\view\ \myapp\controller\ </code></pre> <p>One of my class in \myapp\view\ must import a class called <a href="http://code.google.com/p/google-chartwrapper/">GChartWrapper</a>. However, I am getting an import error...</p> <pre><code>myview.py from myapp.utils.GChartWrapper import * </code></pre> <p>Here is the error:</p> <pre><code>&lt;type 'exceptions.ImportError'&gt;: No module named GChartWrapper.GChart args = ('No module named GChartWrapper.GChart',) message = 'No module named GChartWrapper.GChart' </code></pre> <p>What am I doing wrong? I really have a hard time to import modules/classes in Python...</p>
8
2009-06-16T20:42:51Z
5,666,571
<p>GChartWrapper is also available from PyPI so you can use easy_install or pip to install the module:</p> <pre><code>sudo pip install GChartWrapper==0.9 </code></pre> <p>It will then be automatically added to your PYTHONPATH and then you can remove it from your /myapp/utils directory. If you can't use sudo, look at using virtualenv (and virtualenvwrapper).</p>
0
2011-04-14T16:40:05Z
[ "python", "import", "gchart" ]
Is there a python ftp library for uploading whole directories (including subdirectories)?
1,003,968
<p>So I know about ftplib, but that's a bit too low for me as it still requires me to handle uploading files one at a time as well as determining if there are subdirectories, creating the equivalent subdirectories on the server, cd'ing into those subdirectories and then finally uploading the correct files into those subdirectories. It's an annoying task that I'd rather avoid if I can, what with writing tests, setting up test ftp servers etc etc..</p> <p>Any of you know of a library (<a href="http://www.codinghorror.com/blog/archives/001268.html" rel="nofollow">or mb some code scrawled on the bathroom wall..</a>) that takes care of this for me or should I just accept my fate and roll my own?</p> <p>Thanks</p>
4
2009-06-16T21:14:19Z
1,003,989
<blockquote> <p>The ftputil Python library is a high-level interface to the ftplib module.</p> </blockquote> <p>Looks like this could help. <a href="http://ftputil.sschwarzer.net/trac">ftputil website</a></p>
11
2009-06-16T21:17:48Z
[ "python", "ftp" ]
Is there a python ftp library for uploading whole directories (including subdirectories)?
1,003,968
<p>So I know about ftplib, but that's a bit too low for me as it still requires me to handle uploading files one at a time as well as determining if there are subdirectories, creating the equivalent subdirectories on the server, cd'ing into those subdirectories and then finally uploading the correct files into those subdirectories. It's an annoying task that I'd rather avoid if I can, what with writing tests, setting up test ftp servers etc etc..</p> <p>Any of you know of a library (<a href="http://www.codinghorror.com/blog/archives/001268.html" rel="nofollow">or mb some code scrawled on the bathroom wall..</a>) that takes care of this for me or should I just accept my fate and roll my own?</p> <p>Thanks</p>
4
2009-06-16T21:14:19Z
1,004,258
<p>If wget is installed on your system, you could have your script call it to do the ftp'ing for you. It supports recursive transfers, site mirroring, and many other features.</p>
3
2009-06-16T22:29:52Z
[ "python", "ftp" ]
Why does declaring a descriptor class in the __init__ function break the descriptor functionality?
1,004,168
<p>In class B below I wanted the <code>__set__</code> function in class A to be called whenever you assign a value to <code>B().a</code> . Instead, setting a value to <code>B().a</code> overwrites <code>B().a</code> with the value. Class C assigning to <code>C().a</code> works correctly, but I wanted to have a separate instance of A for each user class, i.e. I don't want changing 'a' in one instance of C() to change 'a' in all other instances. I wrote a couple of tests to help illustrate the problem. Can you help me define a class that will pass both test1 and test2?</p> <pre><code>class A(object): def __set__(self, instance, value): print "__set__ called: ", value class B(object): def __init__(self): self.a = A() class C(object): a = A() def test1( class_in ): o = class_in() o.a = "test" if isinstance(o.a, A): print "pass" else: print "fail" def test2( class_in ): o1, o2 = class_in(), class_in() if o1.a is o2.a: print "fail" else: print "pass" </code></pre>
6
2009-06-16T21:55:47Z
1,004,254
<p>Accordingly to the <a href="http://docs.python.org/reference/datamodel.html#implementing-descriptors" rel="nofollow">documentation</a>:</p> <blockquote> <p><em>The following methods <strong>only apply</strong> when an instance of the class containing the method (a so-called descriptor class) <strong>appears in the class dictionary of another new-style class</strong>, known as the owner class. In the examples below, “the attribute” refers to the attribute whose name is the key of the property in the owner class’ <code>__dict__</code>. Descriptors can only be implemented as new-style classes themselves.</em></p> </blockquote> <p>So you can't have descriptors on instances.</p> <p>However, since the descriptor gets a ref to the instance being used to access it, just use that as a key to storing state and you can have different behavior depending on the instance.</p>
4
2009-06-16T22:29:29Z
[ "python", "descriptor" ]
Why does declaring a descriptor class in the __init__ function break the descriptor functionality?
1,004,168
<p>In class B below I wanted the <code>__set__</code> function in class A to be called whenever you assign a value to <code>B().a</code> . Instead, setting a value to <code>B().a</code> overwrites <code>B().a</code> with the value. Class C assigning to <code>C().a</code> works correctly, but I wanted to have a separate instance of A for each user class, i.e. I don't want changing 'a' in one instance of C() to change 'a' in all other instances. I wrote a couple of tests to help illustrate the problem. Can you help me define a class that will pass both test1 and test2?</p> <pre><code>class A(object): def __set__(self, instance, value): print "__set__ called: ", value class B(object): def __init__(self): self.a = A() class C(object): a = A() def test1( class_in ): o = class_in() o.a = "test" if isinstance(o.a, A): print "pass" else: print "fail" def test2( class_in ): o1, o2 = class_in(), class_in() if o1.a is o2.a: print "fail" else: print "pass" </code></pre>
6
2009-06-16T21:55:47Z
1,004,523
<p>Here's a class that can pass the original tests, but don't try using it in most situations. it fails the isinstance test on itself! </p> <pre><code>class E(object): def __new__(cls, state): class E(object): a = A(state) def __init__(self, state): self.state = state return E(state) #&gt;&gt;&gt; isinstance(E(1), E) #False </code></pre>
0
2009-06-17T00:12:40Z
[ "python", "descriptor" ]
Why does declaring a descriptor class in the __init__ function break the descriptor functionality?
1,004,168
<p>In class B below I wanted the <code>__set__</code> function in class A to be called whenever you assign a value to <code>B().a</code> . Instead, setting a value to <code>B().a</code> overwrites <code>B().a</code> with the value. Class C assigning to <code>C().a</code> works correctly, but I wanted to have a separate instance of A for each user class, i.e. I don't want changing 'a' in one instance of C() to change 'a' in all other instances. I wrote a couple of tests to help illustrate the problem. Can you help me define a class that will pass both test1 and test2?</p> <pre><code>class A(object): def __set__(self, instance, value): print "__set__ called: ", value class B(object): def __init__(self): self.a = A() class C(object): a = A() def test1( class_in ): o = class_in() o.a = "test" if isinstance(o.a, A): print "pass" else: print "fail" def test2( class_in ): o1, o2 = class_in(), class_in() if o1.a is o2.a: print "fail" else: print "pass" </code></pre>
6
2009-06-16T21:55:47Z
22,264,388
<p>I was bitten by a similar issue in that I wanted to class objects with attributes governed by a descriptor. When I did this, I noticed that the attributes were being overwritten in all of the objects such that they weren't individual. </p> <p>I raised a SO question and the resultant answer is here: <a href="http://stackoverflow.com/questions/22259468/class-attribute-changing-value-for-no-reason/22262821#22262821">class attribute changing value for no reason</a></p> <p>A good document link discussing descriptors is here: <a href="http://martyalchin.com/2007/nov/24/python-descriptors-part-2-of-2/" rel="nofollow">http://martyalchin.com/2007/nov/24/python-descriptors-part-2-of-2/</a></p> <p>An example descriptor from the aforementioned link is below:</p> <pre><code>class Numberise(object): def __init__(self, name): self.name = name def __get__(self, instance, owner): if self.name not in instance.__dict__: raise (AttributeError, self.name) return '%o'%(instance.__dict__[self.name]) def __set__(self, instance, value): print ('setting value to: %d'%value) instance.__dict__[self.name] = value </code></pre>
0
2014-03-08T02:53:21Z
[ "python", "descriptor" ]
Django: How to sort a ModelForm's Many2ManyField (Select Tag) according to the object's __unicode__() value?
1,004,202
<p>As stated in the title.</p>
1
2009-06-16T22:08:49Z
4,863,718
<p>The sort would have to be done in Python since the database has no idea what you're doing in <code>__unicode__()</code>. So you'd have to retrieve all of the related model instances into a list, sort the list using the <code>__unicode__()</code> value of the instances, and then use that list wherever you want.</p> <p>The following document has a number of methods for sorting in python: <a href="http://wiki.python.org/moin/HowTo/Sorting/" rel="nofollow">http://wiki.python.org/moin/HowTo/Sorting/</a></p>
0
2011-02-01T14:26:56Z
[ "python", "django" ]
Know any creative ways to interface Python with Tcl?
1,004,434
<p>Here's the situation. The company I work for has quite a bit of existing Tcl code, but some of them want to start using python. It would nice to be able to reuse some of the existing Tcl code, because that's money already spent. Besides, some of the test equipment only has Tcl API's.</p> <p>So, one of the ways I thought of was using the subprocess module to call into some Tcl scripts. </p> <ul> <li>Is subprocess my best bet?</li> <li>Has anyone used this fairly new piece of code: <a href="http://code.google.com/p/plumage/">Plumage</a>? If so what is your experience (not just for Tk)?</li> <li>Any other possible ways that I have not considered?</li> </ul>
15
2009-06-16T23:40:11Z
1,004,463
<p>I've not used it myself, but SWIG might help you out:</p> <p><a href="http://www.swig.org/Doc1.1/HTML/Tcl.html" rel="nofollow">http://www.swig.org/Doc1.1/HTML/Tcl.html</a></p>
0
2009-06-16T23:50:04Z
[ "python", "tcl" ]
Know any creative ways to interface Python with Tcl?
1,004,434
<p>Here's the situation. The company I work for has quite a bit of existing Tcl code, but some of them want to start using python. It would nice to be able to reuse some of the existing Tcl code, because that's money already spent. Besides, some of the test equipment only has Tcl API's.</p> <p>So, one of the ways I thought of was using the subprocess module to call into some Tcl scripts. </p> <ul> <li>Is subprocess my best bet?</li> <li>Has anyone used this fairly new piece of code: <a href="http://code.google.com/p/plumage/">Plumage</a>? If so what is your experience (not just for Tk)?</li> <li>Any other possible ways that I have not considered?</li> </ul>
15
2009-06-16T23:40:11Z
1,004,473
<p>This can be done.</p> <p><a href="http://wiki.tcl.tk/13312" rel="nofollow">http://wiki.tcl.tk/13312</a></p> <p>Specificly look at the typcl extension. </p> <blockquote> <p>Typcl is a bit weird... It's a an extension to use Tcl <em>from</em> Python. It doesn't really require CriTcl and could have been done in standard C.</p> <p>This code demonstrates using Tcl as shared library, and hooking into it at run time (Tcl's stubs architecture makes this delightfully simple). Furthermore, Typcl avoids string conversions where possible (both ways).</p> </blockquote>
3
2009-06-16T23:55:02Z
[ "python", "tcl" ]
Know any creative ways to interface Python with Tcl?
1,004,434
<p>Here's the situation. The company I work for has quite a bit of existing Tcl code, but some of them want to start using python. It would nice to be able to reuse some of the existing Tcl code, because that's money already spent. Besides, some of the test equipment only has Tcl API's.</p> <p>So, one of the ways I thought of was using the subprocess module to call into some Tcl scripts. </p> <ul> <li>Is subprocess my best bet?</li> <li>Has anyone used this fairly new piece of code: <a href="http://code.google.com/p/plumage/">Plumage</a>? If so what is your experience (not just for Tk)?</li> <li>Any other possible ways that I have not considered?</li> </ul>
15
2009-06-16T23:40:11Z
1,004,513
<p>I hope you're ready for this. Standard Python</p> <pre><code>import Tkinter tclsh = Tkinter.Tcl() tclsh.eval(""" proc unknown args {puts "Hello World!"} }"!dlroW olleH" stup{ sgra nwonknu corp """) </code></pre> <p><em>Edit in Re to comment</em>: Python's tcl interpreter is not aware of other installed tcl components. You can deal with that by adding extensions in the usual way to the tcl python actually uses. Here's a link with some detail </p> <ul> <li><a href="http://wiki.python.org/moin/How%20Tkinter%20can%20exploit%20Tcl/Tk%20extensions">How Tkinter can exploit Tcl/Tk extensions</a></li> </ul>
19
2009-06-17T00:10:03Z
[ "python", "tcl" ]
ctypes in Python 2.6 help
1,005,117
<p>I can't seem to get this code to work, I was under the impression I was doing this correctly. </p> <pre><code>from ctypes import * kernel32 = windll.kernel32 string1 = "test" string2 = "test2" kernel32.MessageBox(None, string1, string2, MB_OK) </code></pre> <p>** I tried to change it to MessageBoxA as suggested below ** ** Error I get :: **</p> <pre><code>Traceback (most recent call last): File "C:\&lt;string&gt;", line 6, in &lt;module&gt; File "C:\Python26\Lib\ctypes\__init__.py", line 366, in __getattr__ func = self.__getitem__(name) File "C:\Python26\Lib\ctypes\__init__.py", line 371, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'MessageBoxA' not found </code></pre>
1
2009-06-17T04:26:50Z
1,005,128
<p>The problem is that the function you're trying to call isn't actually named <code>MessageBox()</code>. There are two functions, named <code>MessageBoxA()</code> and <code>MessageBoxW()</code>: the former takes 8-bit ANSI strings, and the latter takes 16-bit Unicode (wide-character) strings. In C, the preprocessor symbol <code>MessageBox</code> is <code>#define</code>d to be either <code>MessageBoxA</code> or <code>MessageBoxW</code>, depending on whether or not Unicode is enabled (specifically, if the symbol <code>_UNICODE</code> is defined).</p> <p>Secondly, according to the <a href="http://msdn.microsoft.com/en-us/library/ms645505%28VS.85%29.aspx" rel="nofollow"><code>MessageBox()</code> documentation</a>, <code>MessageBoxA/W</code> are located in <code>user32.dll</code>, not <code>kernel32.dll</code>.</p> <p>Try this (I can't verify it, since I'm not in front of a Windows box at the moment):</p> <pre><code>user32 = windll.user32 user32.MessageBoxA(None, string1, string2, MB_OK) </code></pre>
0
2009-06-17T04:31:21Z
[ "python", "ctypes" ]
ctypes in Python 2.6 help
1,005,117
<p>I can't seem to get this code to work, I was under the impression I was doing this correctly. </p> <pre><code>from ctypes import * kernel32 = windll.kernel32 string1 = "test" string2 = "test2" kernel32.MessageBox(None, string1, string2, MB_OK) </code></pre> <p>** I tried to change it to MessageBoxA as suggested below ** ** Error I get :: **</p> <pre><code>Traceback (most recent call last): File "C:\&lt;string&gt;", line 6, in &lt;module&gt; File "C:\Python26\Lib\ctypes\__init__.py", line 366, in __getattr__ func = self.__getitem__(name) File "C:\Python26\Lib\ctypes\__init__.py", line 371, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'MessageBoxA' not found </code></pre>
1
2009-06-17T04:26:50Z
1,005,133
<p>MessageBox is defined in user32 not kernel32, you also haven't defined MB_OK so use this instead</p> <pre><code>windll.user32.MessageBoxA(None, string1, string2, 1) </code></pre> <p>Also I recommend using <a href="http://python.net/crew/mhammond/win32/Downloads.html" rel="nofollow">python win32 API</a> isntead of it ,as it has all constant and named functions</p> <p>edit: I mean use this</p> <pre><code>from ctypes import * kernel32 = windll.kernel32 string1 = "test" string2 = "test2" #kernel32.MessageBox(None, string1, string2, MB_OK) windll.user32.MessageBoxA(None, string1, string2, 1) </code></pre> <p>same thing you can do using win32 api as</p> <pre><code>import win32gui win32gui.MessageBox(0, "a", "b", 1) </code></pre>
4
2009-06-17T04:32:48Z
[ "python", "ctypes" ]
ctypes in Python 2.6 help
1,005,117
<p>I can't seem to get this code to work, I was under the impression I was doing this correctly. </p> <pre><code>from ctypes import * kernel32 = windll.kernel32 string1 = "test" string2 = "test2" kernel32.MessageBox(None, string1, string2, MB_OK) </code></pre> <p>** I tried to change it to MessageBoxA as suggested below ** ** Error I get :: **</p> <pre><code>Traceback (most recent call last): File "C:\&lt;string&gt;", line 6, in &lt;module&gt; File "C:\Python26\Lib\ctypes\__init__.py", line 366, in __getattr__ func = self.__getitem__(name) File "C:\Python26\Lib\ctypes\__init__.py", line 371, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'MessageBoxA' not found </code></pre>
1
2009-06-17T04:26:50Z
1,005,451
<p>Oh and anytime you are confused about if a call needs kernel32 or user32 or something of the sorts. Don't be afraid to look for the call on MSDN. They have an <a href="http://msdn.microsoft.com/en-us/library/aa383688%28VS.85%29.aspx" rel="nofollow">Alphabetical List</a> and also a list based on <a href="http://msdn.microsoft.com/en-us/library/aa383686%28VS.85%29.aspx" rel="nofollow">categories</a>. Hope you find them helpful .</p>
0
2009-06-17T06:49:59Z
[ "python", "ctypes" ]
How to distinguish field that requires null=True when blank=True is set in Django models?
1,005,187
<p>Some model fields such as DateTimeField require null=True option when blank=True option is set.</p> <p>I'd like to know which fields require that (maybe dependent on backend DBMS), and there is any way to do this automatically.</p>
2
2009-06-17T04:57:32Z
1,005,209
<p>null=True is used to tell that in DB value can be NULL blank=True is only for django , so django doesn't raise error if field is blank e.g. in admin interface so blank=True has nothing to do with DB NULL requirement will vary from DB to DB, and it is upto you to decide if you want some column NULL or not</p>
2
2009-06-17T05:09:16Z
[ "python", "django", "django-models" ]
How to distinguish field that requires null=True when blank=True is set in Django models?
1,005,187
<p>Some model fields such as DateTimeField require null=True option when blank=True option is set.</p> <p>I'd like to know which fields require that (maybe dependent on backend DBMS), and there is any way to do this automatically.</p>
2
2009-06-17T04:57:32Z
1,005,224
<p><a href="http://www.b-list.org/weblog/2006/jun/28/django-tips-difference-between-blank-and-null/" rel="nofollow">This post</a> should help to understand the difference on <code>blank</code> and <code>null</code> in Django</p>
2
2009-06-17T05:13:44Z
[ "python", "django", "django-models" ]
Using Django JSON serializer for object that is not a Model
1,005,422
<ul> <li>Is it possible to use Django serializer without a Model? </li> <li>How it is done? </li> <li>Will it work with google-app-engine?</li> </ul> <p>I don't use Django framework, but since it is available, I would want to use its resources here and there. Here is the code I tried:</p> <pre><code>from django.core import serializers obj = {'a':42,'q':'meaning of life'} serialised = serializers.serialize('json', obj) </code></pre> <p>this generates an error</p> <pre><code>ERROR ... __init__.py:385] 'str' object has no attribute '_meta' </code></pre>
2
2009-06-17T06:32:57Z
1,005,489
<p>Serializers are only for models. Instead you can use <a href="http://code.google.com/p/simplejson/" rel="nofollow">simplejson</a> bundled with Django.</p> <pre><code>from django.utils import simplejson json_str = simplejson.dumps(my_object) </code></pre> <p>Simplejson 2.0.9 docs are <a href="http://simplejson.googlecode.com/svn/tags/simplejson-2.0.9/docs/index.html" rel="nofollow">here</a>.</p>
15
2009-06-17T07:01:29Z
[ "python", "django", "json", "google-app-engine", "serialization" ]
Using Django JSON serializer for object that is not a Model
1,005,422
<ul> <li>Is it possible to use Django serializer without a Model? </li> <li>How it is done? </li> <li>Will it work with google-app-engine?</li> </ul> <p>I don't use Django framework, but since it is available, I would want to use its resources here and there. Here is the code I tried:</p> <pre><code>from django.core import serializers obj = {'a':42,'q':'meaning of life'} serialised = serializers.serialize('json', obj) </code></pre> <p>this generates an error</p> <pre><code>ERROR ... __init__.py:385] 'str' object has no attribute '_meta' </code></pre>
2
2009-06-17T06:32:57Z
1,009,855
<p>The GQLEncoder class in this library can take a db.Model entity and serialize it. I'm not sure if this is what you're looking for, but it's been useful to me. </p>
0
2009-06-17T22:37:29Z
[ "python", "django", "json", "google-app-engine", "serialization" ]
A question on python sorting efficiency
1,005,494
<p>Alright so I am making a commandline based implementation of a website search feature. The website has a list of all the links I need in alphabetical order. </p> <p>Usage would be something like</p> <pre><code>./find.py LinkThatStartsWithB </code></pre> <p>So it would navigate to the webpage associated with the letter B. My questions is what is the most efficient/smartest way to use the input by the user and navigate to the webpage?</p> <p>What I was thinking at first was something along the lines of using a list and then getting the first letter of the word and using the numeric identifier to tell where to go in list index. </p> <p>(A = 1, B = 2...) Example code:</p> <pre><code>#Use base url as starting point then add extension on end. Base_URL = "http://www.website.com/" #Use list index as representation of letter Alphabetic_Urls = [ "/extensionA.html", "/extensionB.html", "/extensionC.html", ] </code></pre> <p>Or would Dictionary be a better bet?</p> <p>Thanks</p>
1
2009-06-17T07:03:14Z
1,005,500
<p>Dictionary! O(1)</p>
0
2009-06-17T07:05:31Z
[ "python", "sorting" ]
A question on python sorting efficiency
1,005,494
<p>Alright so I am making a commandline based implementation of a website search feature. The website has a list of all the links I need in alphabetical order. </p> <p>Usage would be something like</p> <pre><code>./find.py LinkThatStartsWithB </code></pre> <p>So it would navigate to the webpage associated with the letter B. My questions is what is the most efficient/smartest way to use the input by the user and navigate to the webpage?</p> <p>What I was thinking at first was something along the lines of using a list and then getting the first letter of the word and using the numeric identifier to tell where to go in list index. </p> <p>(A = 1, B = 2...) Example code:</p> <pre><code>#Use base url as starting point then add extension on end. Base_URL = "http://www.website.com/" #Use list index as representation of letter Alphabetic_Urls = [ "/extensionA.html", "/extensionB.html", "/extensionC.html", ] </code></pre> <p>Or would Dictionary be a better bet?</p> <p>Thanks</p>
1
2009-06-17T07:03:14Z
1,005,501
<p>The smartest way here will be whatever makes the code simplest to read. When you've only got 26 items in a list, who cares what algorithm it uses to look through it? You'd have to use something really, <em>really</em> stupid to make it have an impact on performance.</p> <p>If you're really interested in the performance though, you'd need to benchmark different options. Looking at just the complexity doesn't tell the whole story, because it hides the factors involved. For instance, a dictionary lookup will involve computing the hash of the key, looking that up in tables, then checking equality. For short lists, a simple linear search can sometimes be more efficient, depending on how costly the hashing algorithm is.</p> <p>If your example is really accurate though, can't you just take the first letter of the input string and predict the URL from that? (<code>"/extension" + letter + ".html"</code>)</p>
1
2009-06-17T07:05:36Z
[ "python", "sorting" ]
A question on python sorting efficiency
1,005,494
<p>Alright so I am making a commandline based implementation of a website search feature. The website has a list of all the links I need in alphabetical order. </p> <p>Usage would be something like</p> <pre><code>./find.py LinkThatStartsWithB </code></pre> <p>So it would navigate to the webpage associated with the letter B. My questions is what is the most efficient/smartest way to use the input by the user and navigate to the webpage?</p> <p>What I was thinking at first was something along the lines of using a list and then getting the first letter of the word and using the numeric identifier to tell where to go in list index. </p> <p>(A = 1, B = 2...) Example code:</p> <pre><code>#Use base url as starting point then add extension on end. Base_URL = "http://www.website.com/" #Use list index as representation of letter Alphabetic_Urls = [ "/extensionA.html", "/extensionB.html", "/extensionC.html", ] </code></pre> <p>Or would Dictionary be a better bet?</p> <p>Thanks</p>
1
2009-06-17T07:03:14Z
1,005,518
<p>Dictionary would be a good choice if you have (and will always have) a small number of items. If the list of URL's is going to expand in the future you will probably actually want to sort the URL's by their letter and then match the input against that instead of hard-coding the dictionary for each one. </p>
0
2009-06-17T07:09:18Z
[ "python", "sorting" ]
A question on python sorting efficiency
1,005,494
<p>Alright so I am making a commandline based implementation of a website search feature. The website has a list of all the links I need in alphabetical order. </p> <p>Usage would be something like</p> <pre><code>./find.py LinkThatStartsWithB </code></pre> <p>So it would navigate to the webpage associated with the letter B. My questions is what is the most efficient/smartest way to use the input by the user and navigate to the webpage?</p> <p>What I was thinking at first was something along the lines of using a list and then getting the first letter of the word and using the numeric identifier to tell where to go in list index. </p> <p>(A = 1, B = 2...) Example code:</p> <pre><code>#Use base url as starting point then add extension on end. Base_URL = "http://www.website.com/" #Use list index as representation of letter Alphabetic_Urls = [ "/extensionA.html", "/extensionB.html", "/extensionC.html", ] </code></pre> <p>Or would Dictionary be a better bet?</p> <p>Thanks</p>
1
2009-06-17T07:03:14Z
1,005,958
<p>How are you getting this list of URLS?</p> <p>If your commandline app is crawling the website for links, and you are only looking for a single item, building a dictionary is pointless. It will take at least as long to build the dict as it would to just check as you go! eg, just search as:</p> <pre><code>for link in mysite.getallLinks(): if link[0] == firstletter: print link </code></pre> <p>If you are going to be doing multiple searches (rather than just a single commandline parameter), <em>then</em> it might be worth building a dictionary using something like:</p> <pre><code>import collections d=collections.defaultdict(list) for link in mysite.getallLinks(): d[link[0]].append(link) # Dict of first letter -&gt; list of links # Print all links starting with firstletter for link in d[firstletter]: print link </code></pre> <p>Though given that there are just 26 buckets, it's not going to make that much of a difference.</p>
3
2009-06-17T09:07:57Z
[ "python", "sorting" ]
A question on python sorting efficiency
1,005,494
<p>Alright so I am making a commandline based implementation of a website search feature. The website has a list of all the links I need in alphabetical order. </p> <p>Usage would be something like</p> <pre><code>./find.py LinkThatStartsWithB </code></pre> <p>So it would navigate to the webpage associated with the letter B. My questions is what is the most efficient/smartest way to use the input by the user and navigate to the webpage?</p> <p>What I was thinking at first was something along the lines of using a list and then getting the first letter of the word and using the numeric identifier to tell where to go in list index. </p> <p>(A = 1, B = 2...) Example code:</p> <pre><code>#Use base url as starting point then add extension on end. Base_URL = "http://www.website.com/" #Use list index as representation of letter Alphabetic_Urls = [ "/extensionA.html", "/extensionB.html", "/extensionC.html", ] </code></pre> <p>Or would Dictionary be a better bet?</p> <p>Thanks</p>
1
2009-06-17T07:03:14Z
1,010,141
<p>Since it sounds like you're only talking about 26 total items, you probably don't have to worry too much about efficiency. Anything you come up with should be fast enough.</p> <p>In general, I recommend trying to use the data structure that is the best approximation of your problem domain. For example, it sounds like you are trying to map letters to URLs. E.g., this is the "A" url and this is the "B" url. In that case, a mapping data structure like a dict sounds appropriate:</p> <pre><code>html_files = { 'a': '/extensionA.html', 'b': '/extensionB.html', 'c': '/extensionC.html', } </code></pre> <p>Although in this exact example you could actually cheat it and skip the data structure altogether -- <code>'/extension%s.html' % letter.upper()</code> :)</p>
0
2009-06-18T00:13:37Z
[ "python", "sorting" ]
Coding collaboratively for the web
1,005,548
<p>In the past I've done the coding-part of my web-projects mostly by myself. Now, as we are a team working on some project, be it python or php or ..., is there some simple versioning system to use?</p> <p>My hoster doesn't seem to support any kind of this sort. On the other hand, I feel it is too early to start renting a whole server in this phase of the project just to be able to install a versioning system.</p> <p>Any simple ideas how to solve this problem?</p>
3
2009-06-17T07:17:52Z
1,005,561
<p>Try Mercurial (<a href="http://selenic.com/mercurial" rel="nofollow">http://selenic.com/mercurial</a>). If your hosting has ssh and python support, you can run Mercurial on it.</p> <p><strong>UPDATE</strong>: By the way, you don't need a hosting to run Mercurial - it's distributed and works without any servers. If you still want to have a repository on your hosting server - you can have it if your hoster supports ssh and python </p> <p><strong>UPDATE</strong>: <a href="http://bitbucket.org/" rel="nofollow">http://bitbucket.org/</a> - fantastic mercurial hosting, allows 1 private repository and unlimited public repositories for free</p>
3
2009-06-17T07:20:25Z
[ "php", "python", "web-services", "versioning" ]
Coding collaboratively for the web
1,005,548
<p>In the past I've done the coding-part of my web-projects mostly by myself. Now, as we are a team working on some project, be it python or php or ..., is there some simple versioning system to use?</p> <p>My hoster doesn't seem to support any kind of this sort. On the other hand, I feel it is too early to start renting a whole server in this phase of the project just to be able to install a versioning system.</p> <p>Any simple ideas how to solve this problem?</p>
3
2009-06-17T07:17:52Z
1,005,564
<p>See:</p> <ul> <li><a href="http://stackoverflow.com/questions/59791/free-online-private-svn-repositories">http://stackoverflow.com/questions/59791/free-online-private-svn-repositories</a></li> <li><a href="http://stackoverflow.com/questions/146505/can-someone-recommend-a-reliable-cvs-or-svn-hosting-service">http://stackoverflow.com/questions/146505/can-someone-recommend-a-reliable-cvs-or-svn-hosting-service</a></li> <li><a href="http://stackoverflow.com/questions/111292/free-version-control-services">http://stackoverflow.com/questions/111292/free-version-control-services</a></li> </ul>
2
2009-06-17T07:20:37Z
[ "php", "python", "web-services", "versioning" ]
Coding collaboratively for the web
1,005,548
<p>In the past I've done the coding-part of my web-projects mostly by myself. Now, as we are a team working on some project, be it python or php or ..., is there some simple versioning system to use?</p> <p>My hoster doesn't seem to support any kind of this sort. On the other hand, I feel it is too early to start renting a whole server in this phase of the project just to be able to install a versioning system.</p> <p>Any simple ideas how to solve this problem?</p>
3
2009-06-17T07:17:52Z
1,005,632
<p><a href="http://github.com" rel="nofollow">http://github.com</a> Anonymous Sourcecode Hosting, Repository...</p>
1
2009-06-17T07:42:15Z
[ "php", "python", "web-services", "versioning" ]
Coding collaboratively for the web
1,005,548
<p>In the past I've done the coding-part of my web-projects mostly by myself. Now, as we are a team working on some project, be it python or php or ..., is there some simple versioning system to use?</p> <p>My hoster doesn't seem to support any kind of this sort. On the other hand, I feel it is too early to start renting a whole server in this phase of the project just to be able to install a versioning system.</p> <p>Any simple ideas how to solve this problem?</p>
3
2009-06-17T07:17:52Z
1,005,881
<p>Github and the others are free for open source projects only. However, Xp-dev is free as in free beer even to commercial ones. <a href="http://www.xp-dev.com/" rel="nofollow">http://www.xp-dev.com/</a></p>
0
2009-06-17T08:49:04Z
[ "php", "python", "web-services", "versioning" ]
SQLite parameter substitution and quotes
1,005,552
<p>I have this line that works OK:</p> <pre><code>c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name) </code></pre> <p>But I want to use SQLite parameter substitution instead instead of string substitution (because I see <a href="http://docs.python.org/library/sqlite3.html">here</a> that this is safer).</p> <p>This is my (failed) try:</p> <pre><code>t = (name,) c.execute('select cleanseq from cleanseqs WHERE newID="?"',t) </code></pre> <p>But this line returns:</p> <blockquote> <p>'Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.'</p> </blockquote> <p>So the left part of my statement doesn't work. I am supplying one binding (name, in t) but seems that the question mark (?) is not being parsed. If I delete the quotes sourronding the ?, it works. But I want the quotes to remain there since I remember that there are cases where I need them.</p> <p>So the question is: How do I convert this line:</p> <pre><code>c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name) </code></pre>
8
2009-06-17T07:18:25Z
1,005,599
<p>Lose the quotes around ?</p> <pre><code>c.execute('select cleanseq from cleanseqs WHERE newID=?',(t,)) </code></pre> <p>It's treating it as the string "?".</p> <p>Do you need to use double quotes around the whole expression, instead of singles?</p>
4
2009-06-17T07:32:14Z
[ "python", "sqlite", "sqlite3" ]
SQLite parameter substitution and quotes
1,005,552
<p>I have this line that works OK:</p> <pre><code>c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name) </code></pre> <p>But I want to use SQLite parameter substitution instead instead of string substitution (because I see <a href="http://docs.python.org/library/sqlite3.html">here</a> that this is safer).</p> <p>This is my (failed) try:</p> <pre><code>t = (name,) c.execute('select cleanseq from cleanseqs WHERE newID="?"',t) </code></pre> <p>But this line returns:</p> <blockquote> <p>'Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.'</p> </blockquote> <p>So the left part of my statement doesn't work. I am supplying one binding (name, in t) but seems that the question mark (?) is not being parsed. If I delete the quotes sourronding the ?, it works. But I want the quotes to remain there since I remember that there are cases where I need them.</p> <p>So the question is: How do I convert this line:</p> <pre><code>c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name) </code></pre>
8
2009-06-17T07:18:25Z
1,006,006
<p>The library will handle quoting and escaping for you. Simply write your query like this:</p> <pre><code>c.execute('SELECT cleanseq FROM cleanseqs WHERE newID=?', (name,)) </code></pre>
2
2009-06-17T09:22:04Z
[ "python", "sqlite", "sqlite3" ]
SQLite parameter substitution and quotes
1,005,552
<p>I have this line that works OK:</p> <pre><code>c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name) </code></pre> <p>But I want to use SQLite parameter substitution instead instead of string substitution (because I see <a href="http://docs.python.org/library/sqlite3.html">here</a> that this is safer).</p> <p>This is my (failed) try:</p> <pre><code>t = (name,) c.execute('select cleanseq from cleanseqs WHERE newID="?"',t) </code></pre> <p>But this line returns:</p> <blockquote> <p>'Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.'</p> </blockquote> <p>So the left part of my statement doesn't work. I am supplying one binding (name, in t) but seems that the question mark (?) is not being parsed. If I delete the quotes sourronding the ?, it works. But I want the quotes to remain there since I remember that there are cases where I need them.</p> <p>So the question is: How do I convert this line:</p> <pre><code>c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name) </code></pre>
8
2009-06-17T07:18:25Z
1,006,056
<p>about """If I delete the quotes sourronding the ?, it works. But I want the quotes to remain there since I remember that there are cases where I need them."""</p> <p>What you remember from when you were building the whole SQL statement yourself is irrelevant.</p> <p>The new story is: mark with a ? each place in the SQL statement where you want a value substituted then pass in a tuple containing one value per ? -- it's that simple; the wrapper will quote any strings to make sure that they are acceptable SQL constants.</p>
8
2009-06-17T09:37:26Z
[ "python", "sqlite", "sqlite3" ]
SQLite parameter substitution and quotes
1,005,552
<p>I have this line that works OK:</p> <pre><code>c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name) </code></pre> <p>But I want to use SQLite parameter substitution instead instead of string substitution (because I see <a href="http://docs.python.org/library/sqlite3.html">here</a> that this is safer).</p> <p>This is my (failed) try:</p> <pre><code>t = (name,) c.execute('select cleanseq from cleanseqs WHERE newID="?"',t) </code></pre> <p>But this line returns:</p> <blockquote> <p>'Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.'</p> </blockquote> <p>So the left part of my statement doesn't work. I am supplying one binding (name, in t) but seems that the question mark (?) is not being parsed. If I delete the quotes sourronding the ?, it works. But I want the quotes to remain there since I remember that there are cases where I need them.</p> <p>So the question is: How do I convert this line:</p> <pre><code>c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name) </code></pre>
8
2009-06-17T07:18:25Z
1,010,804
<p>I find the named-parameter binding style much more readable -- and <code>sqlite3</code> supports it:</p> <pre><code>c.execute('SELECT cleanseq FROM cleanseqs WHERE newID=:t', locals()) </code></pre> <p>Note: passing <code>{'t': t}</code> or <code>dict(t=t)</code> instead of <code>locals()</code> would be more punctiliously correct, but in my opinion it would interfere with readability when there are several parameters and/or longer names. In any case, I do find the <code>:t</code> better than the <code>?</code>;-).</p>
11
2009-06-18T04:43:40Z
[ "python", "sqlite", "sqlite3" ]
SQLite parameter substitution and quotes
1,005,552
<p>I have this line that works OK:</p> <pre><code>c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name) </code></pre> <p>But I want to use SQLite parameter substitution instead instead of string substitution (because I see <a href="http://docs.python.org/library/sqlite3.html">here</a> that this is safer).</p> <p>This is my (failed) try:</p> <pre><code>t = (name,) c.execute('select cleanseq from cleanseqs WHERE newID="?"',t) </code></pre> <p>But this line returns:</p> <blockquote> <p>'Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.'</p> </blockquote> <p>So the left part of my statement doesn't work. I am supplying one binding (name, in t) but seems that the question mark (?) is not being parsed. If I delete the quotes sourronding the ?, it works. But I want the quotes to remain there since I remember that there are cases where I need them.</p> <p>So the question is: How do I convert this line:</p> <pre><code>c.execute('select cleanseq from cleanseqs WHERE newID="%s"'%name) </code></pre>
8
2009-06-17T07:18:25Z
23,797,896
<p>To anyone who like me found this thread and got really frustrated by people ignoring the fact that sometimes you can't just ignore the quotes (because you're using say a LIKE command) you can fix this by doing something to the effect of:</p> <pre><code>var = name + "%" c.execute('SELECT foo FROM bar WHERE name LIKE ?',(var,)) </code></pre> <p>This will allow you to substitute in wildcards in this situation.</p>
10
2014-05-22T04:35:40Z
[ "python", "sqlite", "sqlite3" ]
What is the runtime complexity of python list functions?
1,005,590
<p>I was writing a python function that looked something like this</p> <pre><code>def foo(some_list): for i in range(0, len(some_list)): bar(some_list[i], i) </code></pre> <p>so that it was called with</p> <pre><code>x = [0, 1, 2, 3, ... ] foo(x) </code></pre> <p>I had assumed that index access of lists was <code>O(1)</code>, but was surprised to find that for large lists this was significantly slower than I expected.</p> <p>My question, then, is how are python lists are implemented, and what is the runtime complexity of the following</p> <ul> <li>Indexing: <code>list[x]</code></li> <li>Popping from the end: <code>list.pop()</code></li> <li>Popping from the beginning: <code>list.pop(0)</code></li> <li>Extending the list: <code>list.append(x)</code></li> </ul> <p>For extra credit, splicing or arbitrary pops.</p>
36
2009-06-17T07:28:54Z
1,005,616
<p>The answer is "undefined". The Python language doesn't define the underlying implementation. Here are some links to a mailing list thread you might be interested in.</p> <ul> <li><p><a href="http://mail.python.org/pipermail/python-list/2003-April/199506.html" rel="nofollow">It is true that Python's lists have been implemented as contiguous vectors in the C implementations of Python so far.</a></p></li> <li><p><a href="http://mail.python.org/pipermail/python-list/2003-April/199585.html" rel="nofollow">I'm not saying that the O() behaviours of these things should be kept a secret or anything. But you need to interpret them in the context of how Python works generally.</a></p></li> </ul> <p>Also, the more Pythonic way of writing your loop would be this:</p> <pre><code>def foo(some_list): for item in some_list: bar(item) </code></pre>
6
2009-06-17T07:37:59Z
[ "python", "complexity-theory" ]
What is the runtime complexity of python list functions?
1,005,590
<p>I was writing a python function that looked something like this</p> <pre><code>def foo(some_list): for i in range(0, len(some_list)): bar(some_list[i], i) </code></pre> <p>so that it was called with</p> <pre><code>x = [0, 1, 2, 3, ... ] foo(x) </code></pre> <p>I had assumed that index access of lists was <code>O(1)</code>, but was surprised to find that for large lists this was significantly slower than I expected.</p> <p>My question, then, is how are python lists are implemented, and what is the runtime complexity of the following</p> <ul> <li>Indexing: <code>list[x]</code></li> <li>Popping from the end: <code>list.pop()</code></li> <li>Popping from the beginning: <code>list.pop(0)</code></li> <li>Extending the list: <code>list.append(x)</code></li> </ul> <p>For extra credit, splicing or arbitrary pops.</p>
36
2009-06-17T07:28:54Z
1,005,662
<p>Can't comment yet, so</p> <p>if you need index and value then use enumerate:</p> <pre><code>for idx, item in enumerate(range(10, 100, 10)): print idx, item </code></pre>
2
2009-06-17T07:53:01Z
[ "python", "complexity-theory" ]
What is the runtime complexity of python list functions?
1,005,590
<p>I was writing a python function that looked something like this</p> <pre><code>def foo(some_list): for i in range(0, len(some_list)): bar(some_list[i], i) </code></pre> <p>so that it was called with</p> <pre><code>x = [0, 1, 2, 3, ... ] foo(x) </code></pre> <p>I had assumed that index access of lists was <code>O(1)</code>, but was surprised to find that for large lists this was significantly slower than I expected.</p> <p>My question, then, is how are python lists are implemented, and what is the runtime complexity of the following</p> <ul> <li>Indexing: <code>list[x]</code></li> <li>Popping from the end: <code>list.pop()</code></li> <li>Popping from the beginning: <code>list.pop(0)</code></li> <li>Extending the list: <code>list.append(x)</code></li> </ul> <p>For extra credit, splicing or arbitrary pops.</p>
36
2009-06-17T07:28:54Z
1,005,674
<p>there is <a href="http://wiki.python.org/moin/TimeComplexity">a very detailed table on python wiki</a> which answers your question.</p> <p>However, in your particular example you should use <code>enumerate</code> to get an index of an iterable within a loop. like so:</p> <pre><code>for i, item in enumerate(some_seq): bar(item, i) </code></pre>
30
2009-06-17T07:57:35Z
[ "python", "complexity-theory" ]
What is the runtime complexity of python list functions?
1,005,590
<p>I was writing a python function that looked something like this</p> <pre><code>def foo(some_list): for i in range(0, len(some_list)): bar(some_list[i], i) </code></pre> <p>so that it was called with</p> <pre><code>x = [0, 1, 2, 3, ... ] foo(x) </code></pre> <p>I had assumed that index access of lists was <code>O(1)</code>, but was surprised to find that for large lists this was significantly slower than I expected.</p> <p>My question, then, is how are python lists are implemented, and what is the runtime complexity of the following</p> <ul> <li>Indexing: <code>list[x]</code></li> <li>Popping from the end: <code>list.pop()</code></li> <li>Popping from the beginning: <code>list.pop(0)</code></li> <li>Extending the list: <code>list.append(x)</code></li> </ul> <p>For extra credit, splicing or arbitrary pops.</p>
36
2009-06-17T07:28:54Z
1,005,888
<p>Lists are indeed O(1) to index - they are implemented as a vector with proportional overallocation, so perform much as you'd expect. The likely reason you were finding this code slower than you expected is the call to "<code>range(0, len(some_list))</code>".</p> <p><code>range()</code> creates a new list of the specified size, so if some_list has 1,000,000 items, you will create a new million item list up front. This behaviour changes in python3 (range is an iterator), to which the python2 equivalent is <a href="http://docs.python.org/library/functions.html#xrange">xrange</a>, or even better for your case, <a href="http://docs.python.org/library/functions.html#enumerate">enumerate</a></p>
5
2009-06-17T08:49:57Z
[ "python", "complexity-theory" ]
What is the runtime complexity of python list functions?
1,005,590
<p>I was writing a python function that looked something like this</p> <pre><code>def foo(some_list): for i in range(0, len(some_list)): bar(some_list[i], i) </code></pre> <p>so that it was called with</p> <pre><code>x = [0, 1, 2, 3, ... ] foo(x) </code></pre> <p>I had assumed that index access of lists was <code>O(1)</code>, but was surprised to find that for large lists this was significantly slower than I expected.</p> <p>My question, then, is how are python lists are implemented, and what is the runtime complexity of the following</p> <ul> <li>Indexing: <code>list[x]</code></li> <li>Popping from the end: <code>list.pop()</code></li> <li>Popping from the beginning: <code>list.pop(0)</code></li> <li>Extending the list: <code>list.append(x)</code></li> </ul> <p>For extra credit, splicing or arbitrary pops.</p>
36
2009-06-17T07:28:54Z
9,955,327
<p>Python list actually nothing but arrays. Thus, </p> <p>indexing takes O(1)</p> <p>for pop and append again it should be O(1) as per the docs</p> <p>Check out following link for details:</p> <p><a href="http://dustycodes.wordpress.com/2012/03/31/pythons-data-structures-complexity-analysis/" rel="nofollow">http://dustycodes.wordpress.com/2012/03/31/pythons-data-structures-complexity-analysis/</a></p>
0
2012-03-31T11:04:51Z
[ "python", "complexity-theory" ]
Can I trace all the functions/methods executing in a python script?
1,005,665
<p>Is there a way to programmatically trace the execution of all python functions/methods? I would like to see what arguments each of them was called with. I really mean all, I'm not interested in a trace decorator. </p> <p>In Ruby, I could alias the method I wanted and add the extra behaviour there.</p>
5
2009-06-17T07:53:23Z
1,005,690
<p>Have a look at the <a href="http://docs.python.org/library/trace.html">trace</a> module.</p> <p>You can also use it via the command line:</p> <pre><code>python -m trace --help </code></pre>
6
2009-06-17T08:03:05Z
[ "python", "debugging", "tracing" ]
What is the easiest way to see if a process with a given pid exists in Python?
1,005,972
<p>In a POSIX system, I want to see if a given process (PID 4356, for example) is running. It would be even better if I could get metadata about that process.</p>
7
2009-06-17T09:12:08Z
1,005,993
<p><a href="http://docs.python.org/library/os.html#os.waitpid" rel="nofollow"><code>os.waitpid()</code></a> might be of help:</p> <pre><code>try: os.waitpid(pid, 0) except OSError: running = False else: running = True </code></pre>
0
2009-06-17T09:19:27Z
[ "python", "posix" ]
What is the easiest way to see if a process with a given pid exists in Python?
1,005,972
<p>In a POSIX system, I want to see if a given process (PID 4356, for example) is running. It would be even better if I could get metadata about that process.</p>
7
2009-06-17T09:12:08Z
1,005,996
<p>One way to do this to get information would be:</p> <pre><code>import commands output = commands.getstatusoutput("ps -ef | awk '{print $2}' | grep MYPID") </code></pre> <p>See: <a href="http://docs.python.org/library/commands.html" rel="nofollow">http://docs.python.org/library/commands.html</a></p> <p>I think:</p> <pre><code>commands.getoutput(...) </code></pre> <p>could be used to get metadata available on the '<code>ps</code>' line. Since you're using a POSIX system, I imagine <code>ps</code> (or equivalent) would be available (e.g. <code>prstat</code> under Solaris).</p>
0
2009-06-17T09:20:14Z
[ "python", "posix" ]
What is the easiest way to see if a process with a given pid exists in Python?
1,005,972
<p>In a POSIX system, I want to see if a given process (PID 4356, for example) is running. It would be even better if I could get metadata about that process.</p>
7
2009-06-17T09:12:08Z
1,006,028
<p>On linux at least the /proc directory has what you are looking for. It's basically system data from the kernel represented as directories and files. All the numeric directories are details of processes. Just use the basic python os functions to get at this data:</p> <pre><code>#ls /proc 1 17 18675 25346 26390 28071 28674 28848 28871 29347 590 851 874 906 9621 9655 devices iomem modules ... #ls /proc/1 auxv cmdline cwd environ exe fd maps mem mounts root stat statm status task wchan #cat /proc/1/cmdline init [3] </code></pre>
4
2009-06-17T09:26:27Z
[ "python", "posix" ]
What is the easiest way to see if a process with a given pid exists in Python?
1,005,972
<p>In a POSIX system, I want to see if a given process (PID 4356, for example) is running. It would be even better if I could get metadata about that process.</p>
7
2009-06-17T09:12:08Z
1,006,030
<p>Look at <code>/proc/pid</code>. This exists only of the process is running, and contains lots of information.</p>
1
2009-06-17T09:27:09Z
[ "python", "posix" ]
What is the easiest way to see if a process with a given pid exists in Python?
1,005,972
<p>In a POSIX system, I want to see if a given process (PID 4356, for example) is running. It would be even better if I could get metadata about that process.</p>
7
2009-06-17T09:12:08Z
1,006,032
<p>Instead of os.waitpid, you can also use os.kill with signal 0:</p> <pre><code>&gt;&gt;&gt; os.kill(8861, 0) &gt;&gt;&gt; os.kill(12765, 0) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; OSError: [Errno 3] No such process &gt;&gt;&gt; </code></pre> <p>Edit: more expansively:</p> <pre><code>import errno import os def pid_exists(pid): try: os.kill(pid, 0) except OSError, e: return e.errno == errno.EPERM else: return True </code></pre> <p>This works fine on my Linux box. I haven't verified that "signal 0" is actually Posix, but it's always worked on every Unix variant I've tried.</p>
10
2009-06-17T09:27:17Z
[ "python", "posix" ]
What is the easiest way to see if a process with a given pid exists in Python?
1,005,972
<p>In a POSIX system, I want to see if a given process (PID 4356, for example) is running. It would be even better if I could get metadata about that process.</p>
7
2009-06-17T09:12:08Z
4,229,851
<p>In a portable way, by using psutil ( <a href="https://github.com/giampaolo/psutil" rel="nofollow">https://github.com/giampaolo/psutil</a> )</p> <pre><code>&gt;&gt;&gt; import psutil, os &gt;&gt;&gt; psutil.pid_exists(342342) False &gt;&gt;&gt; psutil.pid_exists(os.getpid()) True &gt;&gt;&gt; </code></pre>
2
2010-11-19T22:13:22Z
[ "python", "posix" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
1,006,176
<p>First, read the source.</p> <p>Second, use the <code>dir()</code> function.</p>
35
2009-06-17T10:18:01Z
[ "python", "introspection" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
1,006,180
<p>You can list the attributes of a object with dir() in the shell:</p> <pre><code>&gt;&gt;&gt; dir(object()) ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] </code></pre> <p>Of course, there is also the inspect module: <a href="http://docs.python.org/library/inspect.html#module-inspect" rel="nofollow">http://docs.python.org/library/inspect.html#module-inspect</a></p>
4
2009-06-17T10:18:57Z
[ "python", "introspection" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
1,006,194
<pre><code>"""Visit http://diveintopython.net/""" __author__ = "Mark Pilgrim (mark@diveintopython.org)" def info(object, spacing=10, collapse=1): """Print methods and doc strings. Takes module, class, list, dictionary, or string.""" methodList = [e for e in dir(object) if callable(getattr(object, e))] processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s) print "\n".join(["%s %s" % (method.ljust(spacing), processFunc(str(getattr(object, method).__doc__))) for method in methodList]) if __name__ == "__main__": print help.__doc__ </code></pre>
7
2009-06-17T10:21:29Z
[ "python", "introspection" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
1,006,231
<p>Python has a strong set of introspection features. </p> <p>Take a look at the following <a href="http://docs.python.org/library/functions.html">built-in functions</a>:</p> <ul> <li>type()</li> <li>dir()</li> <li>id()</li> <li>getattr()</li> <li>hasattr()</li> <li>globals()</li> <li>locals()</li> <li>callable()</li> </ul> <p>type() and dir() are particularly useful for inspecting the type of an object and its set of attributes, respectively.</p>
143
2009-06-17T10:28:53Z
[ "python", "introspection" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
1,006,349
<p>In addition if you want to look inside list and dictionaries, you can use pprint()</p>
0
2009-06-17T10:57:20Z
[ "python", "introspection" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
1,006,357
<p>pprint and dir together work great</p>
2
2009-06-17T10:59:08Z
[ "python", "introspection" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
1,006,576
<p>If you want to look at parameters and methods, as others have pointed out you may well use <code>pprint</code> or <code>dir()</code></p> <p>If you want to see the actual value of the contents, you can do</p> <p><code>object.__dict__</code></p>
4
2009-06-17T12:01:45Z
[ "python", "introspection" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
1,007,108
<p>If this is for exploration to see what's going on, I'd recommend looking at <a href="http://ipython.scipy.org/moin/">IPython</a>. This adds various shortcuts to obtain an objects documentation, properties and even source code. For instance appending a "?" to a function will give the help for the object (effectively a shortcut for "help(obj)", wheras using two ?'s ("<code>func??</code>") will display the sourcecode if it is available.</p> <p>There are also a lot of additional conveniences, like tab completion, pretty printing of results, result history etc. that make it very handy for this sort of exploratory programming.</p> <p>For more programmatic use of introspection, the basic builtins like <code>dir()</code>, <code>vars()</code>, <code>getattr</code> etc will be useful, but it is well worth your time to check out the <a href="http://docs.python.org/library/inspect.html">inspect</a> module. To fetch the source of a function, use "<code>inspect.getsource</code>" eg, applying it to itself:</p> <pre><code>&gt;&gt;&gt; print inspect.getsource(inspect.getsource) def getsource(object): """Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An IOError is raised if the source code cannot be retrieved.""" lines, lnum = getsourcelines(object) return string.join(lines, '') </code></pre> <p><code>inspect.getargspec</code> is also frequently useful if you're dealing with wrapping or manipulating functions, as it will give the names and default values of function parameters.</p>
13
2009-06-17T13:41:07Z
[ "python", "introspection" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
1,007,121
<p><code>object.__dict__</code></p>
94
2009-06-17T13:43:33Z
[ "python", "introspection" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
1,010,118
<p>Others have already mentioned the dir() built-in which sounds like what you're looking for, but here's another good tip. Many libraries -- including most of the standard library -- are distributed in source form. Meaning you can pretty easily read the source code directly. The trick is in finding it; for example:</p> <pre><code>&gt;&gt;&gt; import string &gt;&gt;&gt; string.__file__ '/usr/lib/python2.5/string.pyc' </code></pre> <p>The *.pyc file is compiled, so remove the trailing 'c' and open up the uncompiled *.py file in your favorite editor or file viewer:</p> <pre><code>/usr/lib/python2.5/string.py </code></pre> <p>I've found this incredibly useful for discovering things like which exceptions are raised from a given API. This kind of detail is rarely well-documented in the Python world.</p>
5
2009-06-18T00:05:15Z
[ "python", "introspection" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
1,010,136
<p>I'm surprised no one's mentioned help yet!</p> <pre><code>In [1]: def foo(): ...: "foo!" ...: In [2]: help(foo) Help on function foo in module __main__: foo() foo! </code></pre> <p>Help lets you read the docstring and get an idea of what attributes a class might have, which is pretty helpful.</p>
26
2009-06-18T00:11:32Z
[ "python", "introspection" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
21,339,520
<p>If you want to look inside a live object, then python's <code>inspect</code> module is a good answer. In general, it works for getting the source code of functions that are defined in a source file somewhere on disk. If you want to get the source of live functions and lambdas that were defined in the interpreter, you can use <code>dill.source.getsource</code> from <a href="https://github.com/uqfoundation/dill" rel="nofollow"><code>dill</code></a>. It also can get the code for from bound or unbound class methods and functions defined in curries... however, you might not be able to compile that code without the enclosing object's code.</p> <pre><code>&gt;&gt;&gt; from dill.source import getsource &gt;&gt;&gt; &gt;&gt;&gt; def add(x,y): ... return x+y ... &gt;&gt;&gt; squared = lambda x:x**2 &gt;&gt;&gt; &gt;&gt;&gt; print getsource(add) def add(x,y): return x+y &gt;&gt;&gt; print getsource(squared) squared = lambda x:x**2 &gt;&gt;&gt; &gt;&gt;&gt; class Foo(object): ... def bar(self, x): ... return x*x+x ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; &gt;&gt;&gt; print getsource(f.bar) def bar(self, x): return x*x+x &gt;&gt;&gt; </code></pre>
0
2014-01-24T18:11:51Z
[ "python", "introspection" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
22,234,897
<p>There is a python code library build just for this purpose: <a href="http://docs.python.org/2/library/inspect.html" rel="nofollow">inspect</a> Introduced in Python 2.7</p>
1
2014-03-06T20:12:04Z
[ "python", "introspection" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
23,145,626
<p>If you're interested in a GUI for this, take a look at <a href="https://pypi.python.org/pypi/objbrowser">objbrowser</a>. It uses the inspect module from the Python standard library for the object introspection underneath.</p> <p><img src="http://i.stack.imgur.com/Vofje.png" alt="objbrowserscreenshot"> </p>
6
2014-04-18T00:30:26Z
[ "python", "introspection" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
38,629,300
<p>Try <a href="https://github.com/symonsoft/ppretty" rel="nofollow">ppretty</a></p> <pre><code>from ppretty import ppretty class A(object): s = 5 def __init__(self): self._p = 8 @property def foo(self): return range(10) print ppretty(A(), indent=' ', depth=2, width=30, seq_length=6, show_protected=True, show_private=False, show_static=True, show_properties=True, show_address=True) </code></pre> <p>Output:</p> <pre><code>__main__.A at 0x1debd68L ( _p = 8, foo = [0, 1, 2, ..., 7, 8, 9], s = 5 ) </code></pre>
2
2016-07-28T07:07:06Z
[ "python", "introspection" ]
How do I look inside a Python object?
1,006,169
<p>I'm starting to code in various projects using Python (including Django web development and Panda3D game development). </p> <p>To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. </p> <p>So say I have a Python object, what would I need to print out its contents? Is that even possible?</p>
118
2009-06-17T10:17:18Z
39,532,497
<p>Two great tools for inspecting code are:</p> <ol> <li><p><a href="https://ipython.org/" rel="nofollow">IPython</a>. A python terminal that allows you to inspect using tab completion.</p></li> <li><p><a href="https://eclipse.org/" rel="nofollow">Eclipse</a> with the <a href="http://www.pydev.org/manual_adv_debugger.html" rel="nofollow">PyDev plugin</a>. It has an excellent debugger that allows you to break at a given spot and inspect objects by browsing all variables as a tree. You can even use the embedded terminal to try code at that spot or type the object and press '.' to have it give code hints for you.</p></li> </ol> <p><a href="http://i.stack.imgur.com/mMuoA.png" rel="nofollow"><img src="http://i.stack.imgur.com/mMuoA.png" alt="enter image description here"></a></p>
0
2016-09-16T13:17:28Z
[ "python", "introspection" ]
A Python buffer that you can truncate from the left?
1,006,171
<p>Right now, I am buffering bytes using strings, StringIO, or cStringIO. But, I often need to remove bytes from the left side of the buffer. A naive approach would rebuild the entire buffer. Is there an optimal way to do this, if left-truncating is a very common operation? Python's garbage collector should actually GC the truncated bytes.</p> <p>Any sort of algorithm for this (keep the buffer in small pieces?), or an existing implementation, would really help.</p> <p>Edit:</p> <p>I tried to use Python 2.7's memoryview for this, but sadly, the data outside the "view" isn't GCed when the original reference is deleted:</p> <pre><code># (This will use ~2GB of memory, not 50MB) memoryview # Requires Python 2.7+ smalls = [] for i in xrange(10): big = memoryview('z'*(200*1000*1000)) small = big[195*1000*1000:] del big smalls.append(small) print '.', </code></pre>
2
2009-06-17T10:17:29Z
1,006,212
<p>Build your buffer as a list of characters or lines and slice the list. Only join as string on output. This is pretty efficient for most types of 'mutable string' behaviour.</p> <p>The GC will collect the truncated bytes because they are no longer referenced in the list.</p> <p>UPDATE: For modifying the list head you can simply reverse the list. This sounds like an inefficient thing to do however python's list implementation optimises this internally.</p> <p>from <a href="http://effbot.org/zone/python-list.htm" rel="nofollow">http://effbot.org/zone/python-list.htm</a> :</p> <blockquote> <p>Reversing is fast, so temporarily reversing the list can often speed things up if you need to remove and insert a bunch of items at the beginning of the list:</p> <pre><code>L.reverse() # append/insert/pop/delete at far end L.reverse() </code></pre> </blockquote>
1
2009-06-17T10:25:03Z
[ "python", "string", "buffer", "memoryview" ]
A Python buffer that you can truncate from the left?
1,006,171
<p>Right now, I am buffering bytes using strings, StringIO, or cStringIO. But, I often need to remove bytes from the left side of the buffer. A naive approach would rebuild the entire buffer. Is there an optimal way to do this, if left-truncating is a very common operation? Python's garbage collector should actually GC the truncated bytes.</p> <p>Any sort of algorithm for this (keep the buffer in small pieces?), or an existing implementation, would really help.</p> <p>Edit:</p> <p>I tried to use Python 2.7's memoryview for this, but sadly, the data outside the "view" isn't GCed when the original reference is deleted:</p> <pre><code># (This will use ~2GB of memory, not 50MB) memoryview # Requires Python 2.7+ smalls = [] for i in xrange(10): big = memoryview('z'*(200*1000*1000)) small = big[195*1000*1000:] del big smalls.append(small) print '.', </code></pre>
2
2009-06-17T10:17:29Z
1,006,527
<p>A <a href="http://docs.python.org/library/collections.html#deque-objects" rel="nofollow">deque</a> will be efficient if left-removal operations are frequent (Unlike using a list, string or buffer, it's amortised O(1) for either-end removal). It will be more costly memory-wise than a string however, as you'll be storing each character as its own string object, rather than a packed sequence.</p> <p>Alternatively, you could create your own implementation (eg. a linked list of string / buffer objects of fixed size), which may store the data more compactly.</p>
3
2009-06-17T11:49:41Z
[ "python", "string", "buffer", "memoryview" ]