title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
python, sqlite error? db is locked? but it isnt?
531,711
<p>I get "database table is locked" error in my sqlite3 db. My script is single threaded, no other app is using the program (i did have it open once in "SQLite Database Browser.exe"). I copied the file, del the original (success) and renamed the copy so i know no process is locking it yet when i run my script everything in table B cannot be written to and it looks like table A is fine. Whats happening?</p> <p>-edit- I fixed it but unsure how. I notice the code not doing the correct things (i copied the wrong field) and after fixing it up and cleaning it, it magically started working again.</p> <p>-edit2-</p> <p>Someone else posted so i might as well update. I think the problem was i was trying to do a statement with a command/cursor in use.</p>
1
2009-02-10T09:50:22Z
531,913
<p>Maybe your application terminated prematurely after a SQLite transaction began. Look for stale <code>-journal</code> files in the directory and delete them.</p> <p>It might be worth skimming through the <a href="http://www.sqlite.org/lockingv3.html" rel="nofollow">documentation</a> as well.</p>
2
2009-02-10T11:22:35Z
[ "python", "sqlite", "locking" ]
python, sqlite error? db is locked? but it isnt?
531,711
<p>I get "database table is locked" error in my sqlite3 db. My script is single threaded, no other app is using the program (i did have it open once in "SQLite Database Browser.exe"). I copied the file, del the original (success) and renamed the copy so i know no process is locking it yet when i run my script everything in table B cannot be written to and it looks like table A is fine. Whats happening?</p> <p>-edit- I fixed it but unsure how. I notice the code not doing the correct things (i copied the wrong field) and after fixing it up and cleaning it, it magically started working again.</p> <p>-edit2-</p> <p>Someone else posted so i might as well update. I think the problem was i was trying to do a statement with a command/cursor in use.</p>
1
2009-02-10T09:50:22Z
1,027,710
<p>Deleting -journal files sounds like bad advice. See <a href="http://stackoverflow.com/questions/151026/how-do-i-unlock-a-sqlite-database/1027493#1027493">this explanation</a>.</p>
2
2009-06-22T15:03:26Z
[ "python", "sqlite", "locking" ]
python, sqlite error? db is locked? but it isnt?
531,711
<p>I get "database table is locked" error in my sqlite3 db. My script is single threaded, no other app is using the program (i did have it open once in "SQLite Database Browser.exe"). I copied the file, del the original (success) and renamed the copy so i know no process is locking it yet when i run my script everything in table B cannot be written to and it looks like table A is fine. Whats happening?</p> <p>-edit- I fixed it but unsure how. I notice the code not doing the correct things (i copied the wrong field) and after fixing it up and cleaning it, it magically started working again.</p> <p>-edit2-</p> <p>Someone else posted so i might as well update. I think the problem was i was trying to do a statement with a command/cursor in use.</p>
1
2009-02-10T09:50:22Z
6,345,495
<p>I've also seen this error when the db file is on an NFS mounted file system.</p>
0
2011-06-14T14:52:50Z
[ "python", "sqlite", "locking" ]
python, sqlite error? db is locked? but it isnt?
531,711
<p>I get "database table is locked" error in my sqlite3 db. My script is single threaded, no other app is using the program (i did have it open once in "SQLite Database Browser.exe"). I copied the file, del the original (success) and renamed the copy so i know no process is locking it yet when i run my script everything in table B cannot be written to and it looks like table A is fine. Whats happening?</p> <p>-edit- I fixed it but unsure how. I notice the code not doing the correct things (i copied the wrong field) and after fixing it up and cleaning it, it magically started working again.</p> <p>-edit2-</p> <p>Someone else posted so i might as well update. I think the problem was i was trying to do a statement with a command/cursor in use.</p>
1
2009-02-10T09:50:22Z
6,513,401
<p>I have run into this problem before also. It occurs often when you have a cursor and connection open and then your program crashes before you can close it properly. In some cases the following function can be used to make sure that the database is unlocked, even after it was not properly committed and closed beforehand:</p> <pre><code>from sqlite3 import dbapi2 as sqlite def unlock_db(db_filename): """Replace db_filename with the name of the SQLite database.""" connection = sqlite.connect(db_filename) connection.commit() connection.close() </code></pre>
1
2011-06-28T21:40:13Z
[ "python", "sqlite", "locking" ]
Django: Perform case-insensitive lookups by default
531,892
<p>I need to perform case-insensitive queries on <code>username</code> by default when using the Django Auth framework.</p> <p>I tried fixing the issue by writing a custom subclass of <code>Queryset</code> and overriding the <code>_filter_or_exclude</code> method and then using that subclass in a custom manager for the User model-</p> <pre><code>from django.db.models import Manager from django.db.models.query import QuerySet from django.contrib.auth.models import UserManager class MyQuerySet(QuerySet): def _filter_or_exclude(self, negate, *args, **kwargs): if 'username' in kwargs: kwargs['username__iexact'] = kwargs['username'] del kwargs['username'] return super(MyQuerySet, self)._filter_or_exclude(negate, *args, **kwargs) class MyUserManager(UserManager): def get_query_set(self): return MyQuerySet(self.model) User.objects = MyUserManager() </code></pre> <p>But this approach didn't work and I am getting an weird error when I try doing <code>User.objects.get(username='Foo')</code>.</p> <p>Any help would be appreciated.</p> <p><strong>Update</strong>: I am including the exact error that I am getting.</p> <pre><code>/usr/lib/python2.5/site-packages/django/db/models/query.py in get(self, *args, **kwargs) 295 keyword arguments. 296 """ --&gt; 297 clone = self.filter(*args, **kwargs) 298 num = len(clone) 299 if num == 1: /usr/lib/python2.5/site-packages/django/db/models/query.py in filter(self, *args, **kwargs) 481 set. 482 """ --&gt; 483 return self._filter_or_exclude(False, *args, **kwargs) 484 485 def exclude(self, *args, **kwargs): /home/ghoseb/src/git/ocricket.git/ocricket/user/models.py in _filter_or_exclude(self, negate, *args, **kwargs) 38 kwargs['username__iexact'] = kwargs['username'] 39 del kwargs['username'] ---&gt; 40 return super(MyQuerySet, self)._filter_or_exclude(negate, *args, **kwargs) 41 42 class MyUserManager(UserManager): /usr/lib/python2.5/site-packages/django/db/models/query.py in _filter_or_exclude(self, negate, *args, **kwargs) 499 clone.query.add_q(~Q(*args, **kwargs)) 500 else: --&gt; 501 clone.query.add_q(Q(*args, **kwargs)) 502 return clone 503 /usr/lib/python2.5/django/db/models/sql/query.py in add_q(self, q_object, used_aliases) /usr/lib/python2.5/django/db/models/sql/query.py in add_filter(self, filter_expr, connector, negate, trim, can_reuse, process_extras) /usr/lib/python2.5/django/db/models/sql/query.py in get_meta(self) &lt;type 'exceptions.AttributeError'&gt;: 'NoneType' object has no attribute '_meta' </code></pre> <p><strong>Update</strong>: By the way, I just wanted to mention that when I copy the logic inside my <code>_filter_or_exclude</code> method into the actual <code>QuerySet</code> class, it works flawlessly.</p>
6
2009-02-10T11:16:41Z
532,049
<p>You don't want to mess with internal features of Django classes. That way lies trouble with every upgrade in the future.</p> <p>If you want to change the way people authenticate, write a custom authentication backend.</p> <p>Here are two recipes.</p> <p><a href="http://www.davidcramer.net/code/224/logging-in-with-email-addresses-in-django.html" rel="nofollow">http://www.davidcramer.net/code/224/logging-in-with-email-addresses-in-django.html</a></p> <p><a href="http://www.djangosnippets.org/snippets/577/" rel="nofollow">http://www.djangosnippets.org/snippets/577/</a></p> <p>Both of these us email instead of username. It's not hard to use case-insensitive query instead of an email query.</p>
4
2009-02-10T12:08:56Z
[ "python", "django", "django-models", "django-orm" ]
Django: Perform case-insensitive lookups by default
531,892
<p>I need to perform case-insensitive queries on <code>username</code> by default when using the Django Auth framework.</p> <p>I tried fixing the issue by writing a custom subclass of <code>Queryset</code> and overriding the <code>_filter_or_exclude</code> method and then using that subclass in a custom manager for the User model-</p> <pre><code>from django.db.models import Manager from django.db.models.query import QuerySet from django.contrib.auth.models import UserManager class MyQuerySet(QuerySet): def _filter_or_exclude(self, negate, *args, **kwargs): if 'username' in kwargs: kwargs['username__iexact'] = kwargs['username'] del kwargs['username'] return super(MyQuerySet, self)._filter_or_exclude(negate, *args, **kwargs) class MyUserManager(UserManager): def get_query_set(self): return MyQuerySet(self.model) User.objects = MyUserManager() </code></pre> <p>But this approach didn't work and I am getting an weird error when I try doing <code>User.objects.get(username='Foo')</code>.</p> <p>Any help would be appreciated.</p> <p><strong>Update</strong>: I am including the exact error that I am getting.</p> <pre><code>/usr/lib/python2.5/site-packages/django/db/models/query.py in get(self, *args, **kwargs) 295 keyword arguments. 296 """ --&gt; 297 clone = self.filter(*args, **kwargs) 298 num = len(clone) 299 if num == 1: /usr/lib/python2.5/site-packages/django/db/models/query.py in filter(self, *args, **kwargs) 481 set. 482 """ --&gt; 483 return self._filter_or_exclude(False, *args, **kwargs) 484 485 def exclude(self, *args, **kwargs): /home/ghoseb/src/git/ocricket.git/ocricket/user/models.py in _filter_or_exclude(self, negate, *args, **kwargs) 38 kwargs['username__iexact'] = kwargs['username'] 39 del kwargs['username'] ---&gt; 40 return super(MyQuerySet, self)._filter_or_exclude(negate, *args, **kwargs) 41 42 class MyUserManager(UserManager): /usr/lib/python2.5/site-packages/django/db/models/query.py in _filter_or_exclude(self, negate, *args, **kwargs) 499 clone.query.add_q(~Q(*args, **kwargs)) 500 else: --&gt; 501 clone.query.add_q(Q(*args, **kwargs)) 502 return clone 503 /usr/lib/python2.5/django/db/models/sql/query.py in add_q(self, q_object, used_aliases) /usr/lib/python2.5/django/db/models/sql/query.py in add_filter(self, filter_expr, connector, negate, trim, can_reuse, process_extras) /usr/lib/python2.5/django/db/models/sql/query.py in get_meta(self) &lt;type 'exceptions.AttributeError'&gt;: 'NoneType' object has no attribute '_meta' </code></pre> <p><strong>Update</strong>: By the way, I just wanted to mention that when I copy the logic inside my <code>_filter_or_exclude</code> method into the actual <code>QuerySet</code> class, it works flawlessly.</p>
6
2009-02-10T11:16:41Z
532,286
<p>Managers can't be added to classes with simple attribute assignment (<code>User.objects = MyManager()</code>). Look at the ModelBase metaclass (db/models/base.py) to see what all is done for you behind the scenes when you subclass Model. </p> <p>You should be able to make it work with <code>User.add_to_class('objects', MyManager())</code>. Alternatively, you could make a <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models" rel="nofollow">proxy subclass</a> of User and add the manager there.</p>
4
2009-02-10T13:17:26Z
[ "python", "django", "django-models", "django-orm" ]
Django: Perform case-insensitive lookups by default
531,892
<p>I need to perform case-insensitive queries on <code>username</code> by default when using the Django Auth framework.</p> <p>I tried fixing the issue by writing a custom subclass of <code>Queryset</code> and overriding the <code>_filter_or_exclude</code> method and then using that subclass in a custom manager for the User model-</p> <pre><code>from django.db.models import Manager from django.db.models.query import QuerySet from django.contrib.auth.models import UserManager class MyQuerySet(QuerySet): def _filter_or_exclude(self, negate, *args, **kwargs): if 'username' in kwargs: kwargs['username__iexact'] = kwargs['username'] del kwargs['username'] return super(MyQuerySet, self)._filter_or_exclude(negate, *args, **kwargs) class MyUserManager(UserManager): def get_query_set(self): return MyQuerySet(self.model) User.objects = MyUserManager() </code></pre> <p>But this approach didn't work and I am getting an weird error when I try doing <code>User.objects.get(username='Foo')</code>.</p> <p>Any help would be appreciated.</p> <p><strong>Update</strong>: I am including the exact error that I am getting.</p> <pre><code>/usr/lib/python2.5/site-packages/django/db/models/query.py in get(self, *args, **kwargs) 295 keyword arguments. 296 """ --&gt; 297 clone = self.filter(*args, **kwargs) 298 num = len(clone) 299 if num == 1: /usr/lib/python2.5/site-packages/django/db/models/query.py in filter(self, *args, **kwargs) 481 set. 482 """ --&gt; 483 return self._filter_or_exclude(False, *args, **kwargs) 484 485 def exclude(self, *args, **kwargs): /home/ghoseb/src/git/ocricket.git/ocricket/user/models.py in _filter_or_exclude(self, negate, *args, **kwargs) 38 kwargs['username__iexact'] = kwargs['username'] 39 del kwargs['username'] ---&gt; 40 return super(MyQuerySet, self)._filter_or_exclude(negate, *args, **kwargs) 41 42 class MyUserManager(UserManager): /usr/lib/python2.5/site-packages/django/db/models/query.py in _filter_or_exclude(self, negate, *args, **kwargs) 499 clone.query.add_q(~Q(*args, **kwargs)) 500 else: --&gt; 501 clone.query.add_q(Q(*args, **kwargs)) 502 return clone 503 /usr/lib/python2.5/django/db/models/sql/query.py in add_q(self, q_object, used_aliases) /usr/lib/python2.5/django/db/models/sql/query.py in add_filter(self, filter_expr, connector, negate, trim, can_reuse, process_extras) /usr/lib/python2.5/django/db/models/sql/query.py in get_meta(self) &lt;type 'exceptions.AttributeError'&gt;: 'NoneType' object has no attribute '_meta' </code></pre> <p><strong>Update</strong>: By the way, I just wanted to mention that when I copy the logic inside my <code>_filter_or_exclude</code> method into the actual <code>QuerySet</code> class, it works flawlessly.</p>
6
2009-02-10T11:16:41Z
18,732,150
<p>Here's a recipe for the auth use case: <a href="http://stackoverflow.com/questions/13190758/django-case-insensitive-matching-of-username-from-auth-user/18731796#18731796">Django : Case insensitive matching of username from auth user?</a> You're probably best off using separate solutions for each of your use cases.</p>
0
2013-09-11T03:24:20Z
[ "python", "django", "django-models", "django-orm" ]
Python file indexing and searching
532,312
<p>I have a large set off files (hdf) that I need to enable search for. For Java I would use Lucene for this, as it's a file and document indexing engine. I don't know what the python equivalent would be though.</p> <p>Can anyone recommend which library I should use for indexing a large collection of files for fast search? Or is the prefered way to roll your own?</p> <p>I have looked at <a href="http://lucene.apache.org/pylucene/">pylucene</a> and <a href="http://pypi.python.org/pypi/Lupy/0.2.1">lupy</a>, but both projects seem rather inactive and unsupported, so I am not sure if should rely on them.</p> <p>Final notes: Woosh and pylucene seems promising, but woosh is still alpha so I am not sure I want to rely on it, and I have problems compiling pylucene, and there are no actual releases off it. After I have looked a bit more at the data, it's mostly numbers and default text strings, so as off now an indexing engine won't help me. Hopefully these libraries will stabilize and later visitors will find some use for them. </p>
9
2009-02-10T13:27:29Z
532,376
<p>I haven't done indexing before, however the following may be helpful :-</p> <ol> <li>pyIndex - <a href="http://rgaucher.info/beta/pyIndex/">http://rgaucher.info/beta/pyIndex/</a> -- File indexing library for Python</li> <li><a href="http://www.xml.com/pub/a/ws/2003/05/13/email.html">http://www.xml.com/pub/a/ws/2003/05/13/email.html</a> -- Thats a script for searching Outlook email using Python and Lucene</li> <li><a href="http://gadfly.sourceforge.net/">http://gadfly.sourceforge.net/</a> - Aaron water's gadfly database (I think you can use this one for indexing. Haven't used it myself.)</li> </ol> <p>As far as using HDF files goes, I have heard of a module called h5py. </p> <p>I hope this helps.</p>
5
2009-02-10T13:42:54Z
[ "python", "search", "indexing", "lucene" ]
Python file indexing and searching
532,312
<p>I have a large set off files (hdf) that I need to enable search for. For Java I would use Lucene for this, as it's a file and document indexing engine. I don't know what the python equivalent would be though.</p> <p>Can anyone recommend which library I should use for indexing a large collection of files for fast search? Or is the prefered way to roll your own?</p> <p>I have looked at <a href="http://lucene.apache.org/pylucene/">pylucene</a> and <a href="http://pypi.python.org/pypi/Lupy/0.2.1">lupy</a>, but both projects seem rather inactive and unsupported, so I am not sure if should rely on them.</p> <p>Final notes: Woosh and pylucene seems promising, but woosh is still alpha so I am not sure I want to rely on it, and I have problems compiling pylucene, and there are no actual releases off it. After I have looked a bit more at the data, it's mostly numbers and default text strings, so as off now an indexing engine won't help me. Hopefully these libraries will stabilize and later visitors will find some use for them. </p>
9
2009-02-10T13:27:29Z
532,426
<p>I'd suggest <a href="http://www.sphinxsearch.com/" rel="nofollow">Sphinx</a>. It's very active, has much more features and seems faster than Lucene.</p>
4
2009-02-10T13:57:01Z
[ "python", "search", "indexing", "lucene" ]
Python file indexing and searching
532,312
<p>I have a large set off files (hdf) that I need to enable search for. For Java I would use Lucene for this, as it's a file and document indexing engine. I don't know what the python equivalent would be though.</p> <p>Can anyone recommend which library I should use for indexing a large collection of files for fast search? Or is the prefered way to roll your own?</p> <p>I have looked at <a href="http://lucene.apache.org/pylucene/">pylucene</a> and <a href="http://pypi.python.org/pypi/Lupy/0.2.1">lupy</a>, but both projects seem rather inactive and unsupported, so I am not sure if should rely on them.</p> <p>Final notes: Woosh and pylucene seems promising, but woosh is still alpha so I am not sure I want to rely on it, and I have problems compiling pylucene, and there are no actual releases off it. After I have looked a bit more at the data, it's mostly numbers and default text strings, so as off now an indexing engine won't help me. Hopefully these libraries will stabilize and later visitors will find some use for them. </p>
9
2009-02-10T13:27:29Z
533,638
<p>Lupy <a href="http://divmod.org/trac/wiki/WhitherLupy">has been retired</a> and the developers recommend PyLucene instead. As for PyLucene, its mailing list activity may be low, but it is definitely supported. In fact, it just recently became an <a href="http://lucene.apache.org/pylucene/#news20090108">official apache subproject</a>.</p> <p>You may also want to look at a new contender: <a href="http://pypi.python.org/pypi/Whoosh/">Whoosh</a>. It's similar to lucene, but implemented in pure python.</p>
8
2009-02-10T18:51:31Z
[ "python", "search", "indexing", "lucene" ]
Python file indexing and searching
532,312
<p>I have a large set off files (hdf) that I need to enable search for. For Java I would use Lucene for this, as it's a file and document indexing engine. I don't know what the python equivalent would be though.</p> <p>Can anyone recommend which library I should use for indexing a large collection of files for fast search? Or is the prefered way to roll your own?</p> <p>I have looked at <a href="http://lucene.apache.org/pylucene/">pylucene</a> and <a href="http://pypi.python.org/pypi/Lupy/0.2.1">lupy</a>, but both projects seem rather inactive and unsupported, so I am not sure if should rely on them.</p> <p>Final notes: Woosh and pylucene seems promising, but woosh is still alpha so I am not sure I want to rely on it, and I have problems compiling pylucene, and there are no actual releases off it. After I have looked a bit more at the data, it's mostly numbers and default text strings, so as off now an indexing engine won't help me. Hopefully these libraries will stabilize and later visitors will find some use for them. </p>
9
2009-02-10T13:27:29Z
770,090
<p>A popular C++ based information retrieval library that is often used with Python is Xapian <a href="http://xapian.org/" rel="nofollow">http://xapian.org/</a></p> <p>It's incredibly quick and can happily manage large amounts of data, however it's not quite as easily extensible as Lucene.</p>
2
2009-04-20T21:08:59Z
[ "python", "search", "indexing", "lucene" ]
What tools would you used to write a modular database in Python?
532,814
<p>I am building a modular application in python. The plugins are not known until runtime.</p> <p>I envisage that many plugins will create/read/update data, which they themselves care about, and other plugins may care about too.</p> <p>An approach I am considering: </p> <ul> <li>one plugin may be concerned with <code>Users</code>. </li> <li>Another plugin may be interested in one or more email addresses for those users. </li> <li>The Users plugin would expose the data, but the email data would not be available for joins outside .</li> </ul> <p><strong>What strategies/tools would you suggest I start constructing and using a modular database?</strong> Is this something an ORM tool could cater for? Is there any other magic I haven't considered?</p> <p>I am envisaging that a side effect of a plugin architecture will make it more likely that the data will end up fairly normalized.</p> <p><strong>Edit</strong>:</p> <ul> <li>by plugins, I mean that the consumers of the plugins do not know about them upfront - they don't import them, rather the host plugins discover the extension plugins, or have them injected in.</li> <li>I am not looking for a database engine/ORM tool that is modular, I am looking to allow plugins to create a modular data model, which can be added to as more plugins are found.</li> <li>I am happy to write my own, but don't want to badly re-implement something that is already existing and much better</li> <li>I am happy to write my own, but don't want to implement a weak design where much stronger ones are more obviously suited to Python.</li> </ul>
1
2009-02-10T15:31:46Z
532,854
<p>Python is already a dynamic programming environment. The imports are not resolved until run time. Python libraries are already a series of plugins. The essential "duck-typing" means that any compatible version of a library can be plugged in at run time.</p> <p>You don't need to add any more dynamic stuff than Python already has. It's already completely dynamic, completely configured at run time.</p> <p><strong>"What strategies/tools would you suggest I start constructing and using a modular database?"</strong></p> <p>I would use one of the existing completely modular databases. I always use an ORM because I prefer to focus on solving a specific problem.</p> <p><hr /></p> <p><strong>Edit</strong></p> <p>All SQL databases are "modular", if you define your schema wisely to keep the "modules" separate from each other. That's what a schema name is for -- to quality the tables within that schema. Nothing to it -- a standard part of SQL92.</p> <p>For a "modular" application, just use a SQL database. Any SQL database. </p> <p>You do have to define the schema, but this can be done "on the fly". Some ORM tools support defining a schema without you having to write a lot of DDL.</p> <p>I like SQLAlchemy -- it handles access and schema definition. I use the Django ORM a lot. It does both schema definition and access, as well.</p>
0
2009-02-10T15:44:37Z
[ "python", "database", "design", "modularity" ]
What tools would you used to write a modular database in Python?
532,814
<p>I am building a modular application in python. The plugins are not known until runtime.</p> <p>I envisage that many plugins will create/read/update data, which they themselves care about, and other plugins may care about too.</p> <p>An approach I am considering: </p> <ul> <li>one plugin may be concerned with <code>Users</code>. </li> <li>Another plugin may be interested in one or more email addresses for those users. </li> <li>The Users plugin would expose the data, but the email data would not be available for joins outside .</li> </ul> <p><strong>What strategies/tools would you suggest I start constructing and using a modular database?</strong> Is this something an ORM tool could cater for? Is there any other magic I haven't considered?</p> <p>I am envisaging that a side effect of a plugin architecture will make it more likely that the data will end up fairly normalized.</p> <p><strong>Edit</strong>:</p> <ul> <li>by plugins, I mean that the consumers of the plugins do not know about them upfront - they don't import them, rather the host plugins discover the extension plugins, or have them injected in.</li> <li>I am not looking for a database engine/ORM tool that is modular, I am looking to allow plugins to create a modular data model, which can be added to as more plugins are found.</li> <li>I am happy to write my own, but don't want to badly re-implement something that is already existing and much better</li> <li>I am happy to write my own, but don't want to implement a weak design where much stronger ones are more obviously suited to Python.</li> </ul>
1
2009-02-10T15:31:46Z
532,894
<p>I personally think that such a plug-in architecture might be a good fit for a schemaless, document-oriented solution like CouchDB. You could assign each plugin its own namespace in the document store and allow the plug-in to store whatever documents it wants to based on whatever schema it may need. </p> <p>However, that's not to say that document-oriented storage is a panacea that will solve all of your design issues, nor that it will entirely replace the RDBMS in your application. But it could certainly complement your plug-in architecture.</p>
3
2009-02-10T15:57:11Z
[ "python", "database", "design", "modularity" ]
What tools would you used to write a modular database in Python?
532,814
<p>I am building a modular application in python. The plugins are not known until runtime.</p> <p>I envisage that many plugins will create/read/update data, which they themselves care about, and other plugins may care about too.</p> <p>An approach I am considering: </p> <ul> <li>one plugin may be concerned with <code>Users</code>. </li> <li>Another plugin may be interested in one or more email addresses for those users. </li> <li>The Users plugin would expose the data, but the email data would not be available for joins outside .</li> </ul> <p><strong>What strategies/tools would you suggest I start constructing and using a modular database?</strong> Is this something an ORM tool could cater for? Is there any other magic I haven't considered?</p> <p>I am envisaging that a side effect of a plugin architecture will make it more likely that the data will end up fairly normalized.</p> <p><strong>Edit</strong>:</p> <ul> <li>by plugins, I mean that the consumers of the plugins do not know about them upfront - they don't import them, rather the host plugins discover the extension plugins, or have them injected in.</li> <li>I am not looking for a database engine/ORM tool that is modular, I am looking to allow plugins to create a modular data model, which can be added to as more plugins are found.</li> <li>I am happy to write my own, but don't want to badly re-implement something that is already existing and much better</li> <li>I am happy to write my own, but don't want to implement a weak design where much stronger ones are more obviously suited to Python.</li> </ul>
1
2009-02-10T15:31:46Z
533,497
<p>Here's a nice treatment of plugins in Python, no database thingies included: <a href="http://martyalchin.com/2008/jan/10/simple-plugin-framework/" rel="nofollow">A Simple Plugin Framework</a>.</p>
0
2009-02-10T18:13:39Z
[ "python", "database", "design", "modularity" ]
What tools would you used to write a modular database in Python?
532,814
<p>I am building a modular application in python. The plugins are not known until runtime.</p> <p>I envisage that many plugins will create/read/update data, which they themselves care about, and other plugins may care about too.</p> <p>An approach I am considering: </p> <ul> <li>one plugin may be concerned with <code>Users</code>. </li> <li>Another plugin may be interested in one or more email addresses for those users. </li> <li>The Users plugin would expose the data, but the email data would not be available for joins outside .</li> </ul> <p><strong>What strategies/tools would you suggest I start constructing and using a modular database?</strong> Is this something an ORM tool could cater for? Is there any other magic I haven't considered?</p> <p>I am envisaging that a side effect of a plugin architecture will make it more likely that the data will end up fairly normalized.</p> <p><strong>Edit</strong>:</p> <ul> <li>by plugins, I mean that the consumers of the plugins do not know about them upfront - they don't import them, rather the host plugins discover the extension plugins, or have them injected in.</li> <li>I am not looking for a database engine/ORM tool that is modular, I am looking to allow plugins to create a modular data model, which can be added to as more plugins are found.</li> <li>I am happy to write my own, but don't want to badly re-implement something that is already existing and much better</li> <li>I am happy to write my own, but don't want to implement a weak design where much stronger ones are more obviously suited to Python.</li> </ul>
1
2009-02-10T15:31:46Z
542,544
<p>Here's how I'd do it: Each plugin should create it's own private tables and perform operations by joining the private tables with the host tables.</p> <p>Suppose your host application has a user table like: (users: id, name, password) and someone wants to write a plugin to store and display each user's blog address. </p> <p>The naive approach will be to add a "blogaddress" column to the users table.</p> <p>The modular approach will be to have a blog address table that can be joined with the host application's table at runtime. That way, when you want to uninstall the plugin, you can just delete the extra tables and things return to the way they were. </p> <p>Relational databases are designed for the purpose of making joins easy anyway.</p>
1
2009-02-12T17:56:00Z
[ "python", "database", "design", "modularity" ]
Lightweight pickle for basic types in python?
532,934
<p>All I want to do is serialize and unserialize tuples of strings or ints.</p> <p>I looked at pickle.dumps() but the byte overhead is significant. Basically it looks like it takes up about 4x as much space as it needs to. Besides, all I need is basic types and have no need to serialize objects.</p> <p>marshal is a little better in terms of space but the result is full of nasty \x00 bytes. Ideally I would like the result to be human readable.</p> <p>I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()?</p> <p>This is getting stored in a db, not a file. Byte overhead matters because it could make the difference between requiring a TEXT column versus a varchar, and generally data compactness affects all areas of db performance.</p>
6
2009-02-10T16:03:57Z
532,983
<p>There are some persistence builtins mentioned in the <a href="http://docs.python.org/library/persistence.html" rel="nofollow">python documentation</a> but I don't think any of these is remarkable smaller in the produced filesize.</p> <p>You could alway use the <a href="http://docs.python.org/library/configparser.html" rel="nofollow">configparser</a> but there you only get string, int, float, bool.</p>
1
2009-02-10T16:15:16Z
[ "python", "serialization", "pickle" ]
Lightweight pickle for basic types in python?
532,934
<p>All I want to do is serialize and unserialize tuples of strings or ints.</p> <p>I looked at pickle.dumps() but the byte overhead is significant. Basically it looks like it takes up about 4x as much space as it needs to. Besides, all I need is basic types and have no need to serialize objects.</p> <p>marshal is a little better in terms of space but the result is full of nasty \x00 bytes. Ideally I would like the result to be human readable.</p> <p>I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()?</p> <p>This is getting stored in a db, not a file. Byte overhead matters because it could make the difference between requiring a TEXT column versus a varchar, and generally data compactness affects all areas of db performance.</p>
6
2009-02-10T16:03:57Z
532,989
<p>"the byte overhead is significant"</p> <p>Why does this matter? It does the job. If you're running low on disk space, I'd be glad to sell you a 1Tb for $500. </p> <p>Have you run it? Is performance a problem? Can you demonstrate that the performance of serialization is <strong>the</strong> problem?</p> <p>"I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()?"</p> <p>Nothing simpler than repr and eval.</p> <p>What's wrong with eval?</p> <p>Is is the "someone could insert malicious code into the file where I serialized my lists" issue?</p> <p>Who -- specifically -- is going to find and edit this file to put in malicious code? Anything you do to secure this (i.e., encryption) removes "simple" from it. </p>
0
2009-02-10T16:15:50Z
[ "python", "serialization", "pickle" ]
Lightweight pickle for basic types in python?
532,934
<p>All I want to do is serialize and unserialize tuples of strings or ints.</p> <p>I looked at pickle.dumps() but the byte overhead is significant. Basically it looks like it takes up about 4x as much space as it needs to. Besides, all I need is basic types and have no need to serialize objects.</p> <p>marshal is a little better in terms of space but the result is full of nasty \x00 bytes. Ideally I would like the result to be human readable.</p> <p>I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()?</p> <p>This is getting stored in a db, not a file. Byte overhead matters because it could make the difference between requiring a TEXT column versus a varchar, and generally data compactness affects all areas of db performance.</p>
6
2009-02-10T16:03:57Z
533,045
<p>Take a look at <a href="http://docs.python.org/library/json.html">json</a>, at least the generated <code>dumps</code> are readable with many other languages.</p> <blockquote> <p>JSON (JavaScript Object Notation) <a href="http://json.org">http://json.org</a> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format.</p> </blockquote>
12
2009-02-10T16:28:58Z
[ "python", "serialization", "pickle" ]
Lightweight pickle for basic types in python?
532,934
<p>All I want to do is serialize and unserialize tuples of strings or ints.</p> <p>I looked at pickle.dumps() but the byte overhead is significant. Basically it looks like it takes up about 4x as much space as it needs to. Besides, all I need is basic types and have no need to serialize objects.</p> <p>marshal is a little better in terms of space but the result is full of nasty \x00 bytes. Ideally I would like the result to be human readable.</p> <p>I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()?</p> <p>This is getting stored in a db, not a file. Byte overhead matters because it could make the difference between requiring a TEXT column versus a varchar, and generally data compactness affects all areas of db performance.</p>
6
2009-02-10T16:03:57Z
533,150
<p>personally i would use <a href="http://pyyaml.org/wiki/PyYAML">yaml</a>. it's on par with json for encoding size, but it can represent some more complex things (e.g. classes, recursive structures) when necessary. </p> <pre><code>In [1]: import yaml In [2]: x = [1, 2, 3, 'pants'] In [3]: print(yaml.dump(x)) [1, 2, 3, pants] In [4]: y = yaml.load('[1, 2, 3, pants]') In [5]: y Out[5]: [1, 2, 3, 'pants'] </code></pre>
8
2009-02-10T16:47:10Z
[ "python", "serialization", "pickle" ]
Lightweight pickle for basic types in python?
532,934
<p>All I want to do is serialize and unserialize tuples of strings or ints.</p> <p>I looked at pickle.dumps() but the byte overhead is significant. Basically it looks like it takes up about 4x as much space as it needs to. Besides, all I need is basic types and have no need to serialize objects.</p> <p>marshal is a little better in terms of space but the result is full of nasty \x00 bytes. Ideally I would like the result to be human readable.</p> <p>I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()?</p> <p>This is getting stored in a db, not a file. Byte overhead matters because it could make the difference between requiring a TEXT column versus a varchar, and generally data compactness affects all areas of db performance.</p>
6
2009-02-10T16:03:57Z
533,280
<p>If you need a space efficient solution you can use Google Protocol buffers.</p> <p><a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html">Protocol buffers - Encoding</a></p> <p><a href="http://code.google.com/apis/protocolbuffers/docs/pythontutorial.html">Protocol buffers - Python Tutorial</a></p>
6
2009-02-10T17:14:10Z
[ "python", "serialization", "pickle" ]
Lightweight pickle for basic types in python?
532,934
<p>All I want to do is serialize and unserialize tuples of strings or ints.</p> <p>I looked at pickle.dumps() but the byte overhead is significant. Basically it looks like it takes up about 4x as much space as it needs to. Besides, all I need is basic types and have no need to serialize objects.</p> <p>marshal is a little better in terms of space but the result is full of nasty \x00 bytes. Ideally I would like the result to be human readable.</p> <p>I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()?</p> <p>This is getting stored in a db, not a file. Byte overhead matters because it could make the difference between requiring a TEXT column versus a varchar, and generally data compactness affects all areas of db performance.</p>
6
2009-02-10T16:03:57Z
533,381
<p>Maybe you're not using the right protocol:</p> <pre><code>&gt;&gt;&gt; import pickle &gt;&gt;&gt; a = range(1, 100) &gt;&gt;&gt; len(pickle.dumps(a)) 492 &gt;&gt;&gt; len(pickle.dumps(a, pickle.HIGHEST_PROTOCOL)) 206 </code></pre> <p>See the documentation for <a href="http://docs.python.org/library/pickle.html#data-stream-format">pickle data formats</a>.</p>
8
2009-02-10T17:39:57Z
[ "python", "serialization", "pickle" ]
Lightweight pickle for basic types in python?
532,934
<p>All I want to do is serialize and unserialize tuples of strings or ints.</p> <p>I looked at pickle.dumps() but the byte overhead is significant. Basically it looks like it takes up about 4x as much space as it needs to. Besides, all I need is basic types and have no need to serialize objects.</p> <p>marshal is a little better in terms of space but the result is full of nasty \x00 bytes. Ideally I would like the result to be human readable.</p> <p>I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()?</p> <p>This is getting stored in a db, not a file. Byte overhead matters because it could make the difference between requiring a TEXT column versus a varchar, and generally data compactness affects all areas of db performance.</p>
6
2009-02-10T16:03:57Z
1,437,394
<p>Luckily there is solution which uses COMPRESSION, and solves the general problem involving any arbitrary Python object including new classes. Rather than micro-manage mere tuples sometimes it's better to use a DRY tool.<br /> Your code will be more crisp and readily refactored in similar future situations. </p> <p>y_serial.py module :: warehouse Python objects with SQLite</p> <p>"Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data."</p> <p><a href="http://yserial.sourceforge.net" rel="nofollow">http://yserial.sourceforge.net</a></p> <p>[If you are still concerned, why not stick those tuples in a dictionary, then apply y_serial to the dictionary. Probably any overhead will vanish due to the transparent compression in the background by zlib.]</p> <p>As to readability, the documentation also gives details on why cPickle was selected over json.</p>
-1
2009-09-17T08:09:07Z
[ "python", "serialization", "pickle" ]
Extend standard python logging, to include the line number where a log method was invoked
533,048
<p>Is it possible to somehow decorate/extend the python standard logging system, so that when a logging method is invoked it also logs the file and the line number where it was invoked or maybe the method that invoked it.</p>
41
2009-02-10T16:29:23Z
533,077
<p>Sure, check <a href="http://docs.python.org/library/logging.html#formatter-objects">formatters</a> in logging docs. Specifically the lineno and pathname variables.</p> <blockquote> <p><strong>%(pathname)s</strong> Full pathname of the source file where the logging call was issued(if available).</p> <p><strong>%(filename)s</strong> Filename portion of pathname.</p> <p><strong>%(module)s</strong> Module (name portion of filename).</p> <p><strong>%(funcName)s</strong> Name of function containing the logging call.</p> <p><strong>%(lineno)d</strong> Source line number where the logging call was issued (if available).</p> </blockquote> <p>Looks something like this:</p> <pre><code>formatter = logging.Formatter('[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s','%m-%d %H:%M:%S') </code></pre>
71
2009-02-10T16:33:26Z
[ "python", "logging" ]
How to integrate Django and Cygwin?
533,125
<p>I have a Windows box with cygwin, python and django installed.</p> <p>Now I want to run django-admin, but when I do I get the error:</p> <pre><code>$ django-admin.py c:\Python26\python.exe: can't open file '/usr/bin/django-admin.py': [Errno 2] No such file or directory </code></pre>
9
2009-02-10T16:42:14Z
533,184
<p>Hi From <a href="http://docs.djangoproject.com/en/dev/ref/django-admin/?from=olddocs">here</a></p> <blockquote> <p>For Windows users, who do not have symlinking functionality available, you can copy django-admin.py to a location on your existing path or edit the PATH settings (under Settings - Control Panel - System - Advanced - Environment...) to point to its installed location.</p> </blockquote> <p>hope this helps</p>
5
2009-02-10T16:53:05Z
[ "python", "django", "cygwin" ]
How to integrate Django and Cygwin?
533,125
<p>I have a Windows box with cygwin, python and django installed.</p> <p>Now I want to run django-admin, but when I do I get the error:</p> <pre><code>$ django-admin.py c:\Python26\python.exe: can't open file '/usr/bin/django-admin.py': [Errno 2] No such file or directory </code></pre>
9
2009-02-10T16:42:14Z
543,381
<p>Sort of sounds like the windows version of Python is trying to run instead of the cygwin one. What happens if you type this:</p> <pre><code>$ python django-admin.py </code></pre> <p>Here I'm assuming </p> <pre><code>$ which python </code></pre> <p>Finds the cygwin version of python (which will be something like /usr/bin/python).</p> <p>You may also try (temporarily) uninstalling the windows version of python and use only cygwin.</p>
0
2009-02-12T21:28:46Z
[ "python", "django", "cygwin" ]
How to integrate Django and Cygwin?
533,125
<p>I have a Windows box with cygwin, python and django installed.</p> <p>Now I want to run django-admin, but when I do I get the error:</p> <pre><code>$ django-admin.py c:\Python26\python.exe: can't open file '/usr/bin/django-admin.py': [Errno 2] No such file or directory </code></pre>
9
2009-02-10T16:42:14Z
543,512
<p>Help us help you. Is there a reason why you are running the windows python interpreter (c:\Python26\python.exe) as oppose to the cygwin python interpreter (/usr/bin/python.exe)? That could be your problem. So to troubleshoot that, you might consider removing the windows native interpreter or simply making sure the cygwin path is listed before the c:\Python26 path in the windows global PATH variable.</p>
0
2009-02-12T21:50:41Z
[ "python", "django", "cygwin" ]
How to integrate Django and Cygwin?
533,125
<p>I have a Windows box with cygwin, python and django installed.</p> <p>Now I want to run django-admin, but when I do I get the error:</p> <pre><code>$ django-admin.py c:\Python26\python.exe: can't open file '/usr/bin/django-admin.py': [Errno 2] No such file or directory </code></pre>
9
2009-02-10T16:42:14Z
550,413
<p>Add the location of your django/bin folder (or wherever else you keep django-admin.py) to your PYTHONPATH environment variable.</p>
0
2009-02-15T06:22:40Z
[ "python", "django", "cygwin" ]
How to integrate Django and Cygwin?
533,125
<p>I have a Windows box with cygwin, python and django installed.</p> <p>Now I want to run django-admin, but when I do I get the error:</p> <pre><code>$ django-admin.py c:\Python26\python.exe: can't open file '/usr/bin/django-admin.py': [Errno 2] No such file or directory </code></pre>
9
2009-02-10T16:42:14Z
558,172
<p>Like Brian mentioned you are running the Windows version of Python which won't work with the Cygwin installation.</p> <p>A word of warning. When I first started using Django, I tried installing it in Cygwin and had a variety of problems and ended up switching to the regular Windows version of Python. Unfortunately, I didn't document all my issues, but I remember some of them had to do with the database libraries. Anyway, that was a few months ago when I knew less about Django than I do now. Maybe the problems I ran into have been solved and perhaps now that I know more I could get it to work, but running Django on Cygwin does seem to be the road less traveled. Good luck. :)</p>
0
2009-02-17T18:34:32Z
[ "python", "django", "cygwin" ]
How to integrate Django and Cygwin?
533,125
<p>I have a Windows box with cygwin, python and django installed.</p> <p>Now I want to run django-admin, but when I do I get the error:</p> <pre><code>$ django-admin.py c:\Python26\python.exe: can't open file '/usr/bin/django-admin.py': [Errno 2] No such file or directory </code></pre>
9
2009-02-10T16:42:14Z
791,703
<p>I just ran into the exact same problem. I've found that if you already have the windows version of python installed, it seems to get priority over the cygwin version. I solved the problem by editing /etc/profile and changed:</p> <pre><code>PATH=/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:$PATH </code></pre> <p>...to:</p> <pre><code>PATH=/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin: </code></pre> <p>...which I <i>think</i> stops cygwin from adding the normal windows path. Once you've got that working, download django into some directory, move into that directory and type:</p> <pre><code>python setup.py install </code></pre> <p>I was having problems to begin with because I had omitted the 'python' bit at the start</p>
4
2009-04-26T22:11:14Z
[ "python", "django", "cygwin" ]
How to integrate Django and Cygwin?
533,125
<p>I have a Windows box with cygwin, python and django installed.</p> <p>Now I want to run django-admin, but when I do I get the error:</p> <pre><code>$ django-admin.py c:\Python26\python.exe: can't open file '/usr/bin/django-admin.py': [Errno 2] No such file or directory </code></pre>
9
2009-02-10T16:42:14Z
11,465,527
<p>Just copy the <strong>django-admin.py</strong> to the current location you are working on for e.g</p> <p>on Cygwin:</p> <pre><code>&lt;root&gt;/projects/ </code></pre> <p>on your windows directory it will look like this:</p> <pre><code>C:\cygwin\home\&lt;your computer name&gt;\projects\ </code></pre> <p>once you copy the file, you can create your project by typing this command:</p> <pre><code>$ python django-admin.py startproject mysite </code></pre> <p>and that's all - you have completed your first project using the Cygwin linux-like environment.</p>
0
2012-07-13T06:52:37Z
[ "python", "django", "cygwin" ]
How to integrate Django and Cygwin?
533,125
<p>I have a Windows box with cygwin, python and django installed.</p> <p>Now I want to run django-admin, but when I do I get the error:</p> <pre><code>$ django-admin.py c:\Python26\python.exe: can't open file '/usr/bin/django-admin.py': [Errno 2] No such file or directory </code></pre>
9
2009-02-10T16:42:14Z
11,465,595
<p>As for the step on how to start your django in cygwin</p> <p>first open your windows command prompt then register the python environment by doing this:</p> <pre class="lang-none prettyprint-override"><code>Path %path%;C:\Python27;C:\Python27\Scripts </code></pre> <p>then now go to the installation folder of your cygwin</p> <pre class="lang-none prettyprint-override"><code>cd C:\cygwin </code></pre> <p>then run the <strong>cygwin.bat</strong> like this:</p> <pre class="lang-none prettyprint-override"><code>C:\cygwin&gt;cygwin.bat &lt;enter&gt; </code></pre> <p>then cygwin will open, and type <strong>python</strong> to see if it now working</p> <pre class="lang-none prettyprint-override"><code>$ python </code></pre> <p>Voila we are done!</p>
0
2012-07-13T06:58:35Z
[ "python", "django", "cygwin" ]
What does 'self' refer to in a @classmethod?
533,300
<p>I thought I was starting to get a grip on "the Python way" of programming. Methods of a class accept self as the first parameter to refer to the instance of the class whose context the method is being called in. The @classmethod decorator refers to a method whose functionality is associated with the class, but which doesn't reference a specific instance.</p> <p>So, what does the first parameter of a @classmethod (canonically 'self') refer to if the method is meant to be called without an instance reference?</p>
15
2009-02-10T17:18:53Z
533,315
<p><a href="http://docs.python.org/library/functions.html#classmethod">class itself</a>:</p> <blockquote> <p>A class method receives the class as implicit first argument, just like an instance method receives the instance.</p> </blockquote> <pre><code>class C: @classmethod def f(cls): print(cls.__name__, type(cls)) &gt;&gt;&gt; C.f() C &lt;class 'type'&gt; </code></pre> <p>and it's <code>cls</code> canonically, btw</p>
32
2009-02-10T17:22:58Z
[ "python", "self", "class-method" ]
What does 'self' refer to in a @classmethod?
533,300
<p>I thought I was starting to get a grip on "the Python way" of programming. Methods of a class accept self as the first parameter to refer to the instance of the class whose context the method is being called in. The @classmethod decorator refers to a method whose functionality is associated with the class, but which doesn't reference a specific instance.</p> <p>So, what does the first parameter of a @classmethod (canonically 'self') refer to if the method is meant to be called without an instance reference?</p>
15
2009-02-10T17:18:53Z
533,316
<p>The class object gets passed as the first parameter. For example:</p> <pre><code>class Foo(object): @classmethod def bar(self): return self() </code></pre> <p>Would return an instance of the Foo class.</p> <p><strong>EDIT</strong>:</p> <p>Note that the last line would be self() not self. self would return the class itself, while self() returns an instance.</p>
1
2009-02-10T17:23:17Z
[ "python", "self", "class-method" ]
What does 'self' refer to in a @classmethod?
533,300
<p>I thought I was starting to get a grip on "the Python way" of programming. Methods of a class accept self as the first parameter to refer to the instance of the class whose context the method is being called in. The @classmethod decorator refers to a method whose functionality is associated with the class, but which doesn't reference a specific instance.</p> <p>So, what does the first parameter of a @classmethod (canonically 'self') refer to if the method is meant to be called without an instance reference?</p>
15
2009-02-10T17:18:53Z
533,331
<p>The first parameter of a classmethod is named <code>cls</code> by convention and refers to the the class object <em>on which the method it was invoked</em>.</p> <pre><code>&gt;&gt;&gt; class A(object): ... @classmethod ... def m(cls): ... print cls is A ... print issubclass(cls, A) &gt;&gt;&gt; class B(A): pass &gt;&gt;&gt; a = A() &gt;&gt;&gt; a.m() True True &gt;&gt;&gt; b = B() &gt;&gt;&gt; b.m() False True </code></pre>
12
2009-02-10T17:28:00Z
[ "python", "self", "class-method" ]
What does 'self' refer to in a @classmethod?
533,300
<p>I thought I was starting to get a grip on "the Python way" of programming. Methods of a class accept self as the first parameter to refer to the instance of the class whose context the method is being called in. The @classmethod decorator refers to a method whose functionality is associated with the class, but which doesn't reference a specific instance.</p> <p>So, what does the first parameter of a @classmethod (canonically 'self') refer to if the method is meant to be called without an instance reference?</p>
15
2009-02-10T17:18:53Z
15,393,431
<p>Django does some strange stuff with a class method here:</p> <pre><code>class BaseFormSet(StrAndUnicode): """ A collection of instances of the same Form class. """ def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList): ... self.prefix = prefix or self.get_default_prefix() ... </code></pre> <p>Even though get_default_prefix is declared this way (in the same class):</p> <pre><code> @classmethod def get_default_prefix(cls): return 'form' </code></pre>
0
2013-03-13T18:22:16Z
[ "python", "self", "class-method" ]
Disable pixmap background defined by GTK theme per application
533,321
<p>For our (open source) fullscreen text editor we're changing background colors of <code>gtk.Window</code>, <code>gtk.Fixed</code>, etc. to custom colors. This works fine, but some <a href="http://en.wikipedia.org/wiki/GTK%2B" rel="nofollow">GTK</a> themes (e.g. <a href="http://sourceforge.net/projects/mac4lin/" rel="nofollow">Mac4Lin</a>) define background pixmaps instead of background colors for some widgets. Those background pixmaps won't go away when calling modify_bg() methods of those widgets.</p> <p>I know I can set pixmaps with <code>bg_pixmap[NORMAL] = 'blabla.png'</code> and that I can define my own gtkrc overrides with gtk.rc_parse_string(). But I don't know how to unset <code>bg_pixmap[NORMAL]</code>.</p> <p>So, how would I do that?</p>
3
2009-02-10T17:25:31Z
534,151
<p>Yes ofcourse Mac4Lin uses pixmaps for more granular appearance to match MAC look. Well to disable those backgroud you dont need to override it.</p> <p>if you want background pixmap as its parent's, set it as</p> <pre><code>bg_pixmap[state] = "&lt;parent&gt;" </code></pre> <p>and to disable set it as</p> <pre><code>bg_pixmap[state] = "&lt;none&gt;" </code></pre>
2
2009-02-10T20:50:24Z
[ "python", "gtk", "pygtk" ]
Dynamic/runtime method creation (code generation) in Python
533,382
<p>I need to generate code for a method at runtime. It's important to be able to run arbitrary code and have a docstring.</p> <p>I came up with a solution combining <code>exec</code> and <code>setattr</code>, here's a dummy example:</p> <pre><code>class Viking(object): def __init__(self): code = ''' def dynamo(self, arg): """ dynamo's a dynamic method! """ self.weight += 1 return arg * self.weight ''' self.weight = 50 d = {} exec code.strip() in d setattr(self.__class__, 'dynamo', d['dynamo']) if __name__ == "__main__": v = Viking() print v.dynamo(10) print v.dynamo(10) print v.dynamo.__doc__ </code></pre> <p>Is there a better / safer / more idiomatic way of achieving the same result?</p>
32
2009-02-10T17:40:05Z
533,581
<p>Python will let you declare a function in a function, so you don't have to do the <code>exec</code> trickery.</p> <pre><code>def __init__(self): def dynamo(self, arg): """ dynamo's a dynamic method! """ self.weight += 1 return arg * self.weight self.weight = 50 setattr(self.__class__, 'dynamo', dynamo) </code></pre> <p>If you want to have several versions of the function, you can put all of this in a loop and vary what you name them in the <code>setattr</code> function:</p> <pre><code>def __init__(self): for i in range(0,10): def dynamo(self, arg, i=i): """ dynamo's a dynamic method! """ self.weight += i return arg * self.weight setattr(self.__class__, 'dynamo_'+i, dynamo) self.weight = 50 </code></pre> <p>(I know this isn't great code, but it gets the point across). As far as setting the docstring, I know that's possible but I'd have to look it up in the documentation.</p> <p><strong>Edit</strong>: You can set the docstring via <code>dynamo.__doc__</code>, so you could do something like this in your loop body:</p> <pre><code>dynamo.__doc__ = "Adds %s to the weight" % i </code></pre> <p><strong>Another Edit</strong>: With help from @eliben and @bobince, the closure problem should be solved.</p>
6
2009-02-10T18:38:43Z
[ "python", "metaprogramming", "exec" ]
Dynamic/runtime method creation (code generation) in Python
533,382
<p>I need to generate code for a method at runtime. It's important to be able to run arbitrary code and have a docstring.</p> <p>I came up with a solution combining <code>exec</code> and <code>setattr</code>, here's a dummy example:</p> <pre><code>class Viking(object): def __init__(self): code = ''' def dynamo(self, arg): """ dynamo's a dynamic method! """ self.weight += 1 return arg * self.weight ''' self.weight = 50 d = {} exec code.strip() in d setattr(self.__class__, 'dynamo', d['dynamo']) if __name__ == "__main__": v = Viking() print v.dynamo(10) print v.dynamo(10) print v.dynamo.__doc__ </code></pre> <p>Is there a better / safer / more idiomatic way of achieving the same result?</p>
32
2009-02-10T17:40:05Z
533,583
<p>Function docstrings and names are mutable properties. You can do anything you want in the inner function, or even have multiple versions of the inner function that makedynamo() chooses between. No need to build any code out of strings.</p> <p>Here's a snippet out of the interpreter:</p> <pre><code>&gt;&gt;&gt; def makedynamo(i): ... def innerdynamo(): ... print "in dynamo %d" % i ... innerdynamo.__doc__ = "docstring for dynamo%d" % i ... innerdynamo.__name__ = "dynamo%d" % i ... return innerdynamo &gt;&gt;&gt; dynamo10 = makedynamo(10) &gt;&gt;&gt; help(dynamo10) Help on function dynamo10 in module __main__: dynamo10() docstring for dynamo10 </code></pre>
9
2009-02-10T18:38:47Z
[ "python", "metaprogramming", "exec" ]
Dynamic/runtime method creation (code generation) in Python
533,382
<p>I need to generate code for a method at runtime. It's important to be able to run arbitrary code and have a docstring.</p> <p>I came up with a solution combining <code>exec</code> and <code>setattr</code>, here's a dummy example:</p> <pre><code>class Viking(object): def __init__(self): code = ''' def dynamo(self, arg): """ dynamo's a dynamic method! """ self.weight += 1 return arg * self.weight ''' self.weight = 50 d = {} exec code.strip() in d setattr(self.__class__, 'dynamo', d['dynamo']) if __name__ == "__main__": v = Viking() print v.dynamo(10) print v.dynamo(10) print v.dynamo.__doc__ </code></pre> <p>Is there a better / safer / more idiomatic way of achieving the same result?</p>
32
2009-02-10T17:40:05Z
534,597
<p>Based on Theran's code, but extending it to methods on classes:</p> <pre> <code> class Dynamo(object): pass def add_dynamo(cls,i): def innerdynamo(self): print "in dynamo %d" % i innerdynamo.__doc__ = "docstring for dynamo%d" % i innerdynamo.__name__ = "dynamo%d" % i setattr(cls,innerdynamo.__name__,innerdynamo) for i in range(2): add_dynamo(Dynamo, i) d=Dynamo() d.dynamo0() d.dynamo1() </code> </pre> <p>Which should print:</p> <pre> <code> in dynamo 0 in dynamo 1 </code> </pre>
54
2009-02-10T22:46:31Z
[ "python", "metaprogramming", "exec" ]
Dynamic/runtime method creation (code generation) in Python
533,382
<p>I need to generate code for a method at runtime. It's important to be able to run arbitrary code and have a docstring.</p> <p>I came up with a solution combining <code>exec</code> and <code>setattr</code>, here's a dummy example:</p> <pre><code>class Viking(object): def __init__(self): code = ''' def dynamo(self, arg): """ dynamo's a dynamic method! """ self.weight += 1 return arg * self.weight ''' self.weight = 50 d = {} exec code.strip() in d setattr(self.__class__, 'dynamo', d['dynamo']) if __name__ == "__main__": v = Viking() print v.dynamo(10) print v.dynamo(10) print v.dynamo.__doc__ </code></pre> <p>Is there a better / safer / more idiomatic way of achieving the same result?</p>
32
2009-02-10T17:40:05Z
2,539,707
<p>Pardon me for my bad English.</p> <p>I recently need to generate dynamic function to bind each menu item to open particular frame on wxPython. Here is what i do.</p> <p>first, i create a list of mapping between the menu item and the frame.</p> <pre><code>menus = [(self.menuItemFile, FileFrame), (self.menuItemEdit, EditFrame)] </code></pre> <p>the first item on the mapping is the menu item and the last item is the frame to be opened. Next, i bind the wx.EVT_MENU event from each of the menu item to particular frame.</p> <pre><code>for menu in menus: f = genfunc(self, menu[1]) self.Bind(wx.EVT_MENU, f, menu[0]) </code></pre> <p>genfunc function is the dynamic function builder, here is the code:</p> <pre><code>def genfunc(parent, form): def OnClick(event): f = form(parent) f.Maximize() f.Show() return OnClick </code></pre>
0
2010-03-29T16:51:41Z
[ "python", "metaprogramming", "exec" ]
In python 2.4, how can I execute external commands with csh instead of bash?
533,398
<p>Without using the new 2.6 subprocess module, how can I get either os.popen or os.system to execute my commands using the tcsh instead of bash? I need to source some scripts which are written in tcsh before executing some other commands and I need to do this within python2.4.</p> <p>EDIT Thanks for answers using 'tcsh -c', but I'd like to avoid this because I have to do escape madness. The string will be interpreted by bash and then interpreted by tcsh. I'll have to do something like:</p> <pre><code>os.system("tcsh -c '"+re.compile("'").sub(r"""'"'"'""",my_cmd)+"'") </code></pre> <p>Can't I just tell python to open up a 'tcsh' sub-process instead of a 'bash' subprocess? Is that possible?</p> <p>P.S. I realize that bash is the cat's meow, but I'm working in a corporate environment and I'm going to choose to <em>not</em> fight a tcsh vs bash battle -- bigger fish to fry.</p>
2
2009-02-10T17:44:23Z
533,422
<p>How about:</p> <pre><code>&gt;&gt;&gt; os.system("tcsh your_own_script") </code></pre> <p>Or just write the script and add</p> <pre><code>#!/bin/tcsh </code></pre> <p>at the beginning of the file and let the OS take care of that.</p>
5
2009-02-10T17:50:02Z
[ "python", "shell", "csh", "tcsh" ]
In python 2.4, how can I execute external commands with csh instead of bash?
533,398
<p>Without using the new 2.6 subprocess module, how can I get either os.popen or os.system to execute my commands using the tcsh instead of bash? I need to source some scripts which are written in tcsh before executing some other commands and I need to do this within python2.4.</p> <p>EDIT Thanks for answers using 'tcsh -c', but I'd like to avoid this because I have to do escape madness. The string will be interpreted by bash and then interpreted by tcsh. I'll have to do something like:</p> <pre><code>os.system("tcsh -c '"+re.compile("'").sub(r"""'"'"'""",my_cmd)+"'") </code></pre> <p>Can't I just tell python to open up a 'tcsh' sub-process instead of a 'bash' subprocess? Is that possible?</p> <p>P.S. I realize that bash is the cat's meow, but I'm working in a corporate environment and I'm going to choose to <em>not</em> fight a tcsh vs bash battle -- bigger fish to fry.</p>
2
2009-02-10T17:44:23Z
533,435
<p>Just prefix the shell as part of your command. I don't have tcsh installed but with zsh:</p> <pre><code>&gt;&gt;&gt; os.system ("zsh -c 'echo $0'") zsh 0 </code></pre>
10
2009-02-10T17:53:19Z
[ "python", "shell", "csh", "tcsh" ]
In python 2.4, how can I execute external commands with csh instead of bash?
533,398
<p>Without using the new 2.6 subprocess module, how can I get either os.popen or os.system to execute my commands using the tcsh instead of bash? I need to source some scripts which are written in tcsh before executing some other commands and I need to do this within python2.4.</p> <p>EDIT Thanks for answers using 'tcsh -c', but I'd like to avoid this because I have to do escape madness. The string will be interpreted by bash and then interpreted by tcsh. I'll have to do something like:</p> <pre><code>os.system("tcsh -c '"+re.compile("'").sub(r"""'"'"'""",my_cmd)+"'") </code></pre> <p>Can't I just tell python to open up a 'tcsh' sub-process instead of a 'bash' subprocess? Is that possible?</p> <p>P.S. I realize that bash is the cat's meow, but I'm working in a corporate environment and I'm going to choose to <em>not</em> fight a tcsh vs bash battle -- bigger fish to fry.</p>
2
2009-02-10T17:44:23Z
533,479
<p>Just set the shell to use to be <code>tcsh</code>:</p> <pre><code>&gt;&gt;&gt; os.environ['SHELL'] = 'tcsh' &gt;&gt;&gt; os.environ['SHELL'] 'tcsh' &gt;&gt;&gt; os.system("echo $SHELL") tcsh </code></pre>
-1
2009-02-10T18:06:53Z
[ "python", "shell", "csh", "tcsh" ]
In python 2.4, how can I execute external commands with csh instead of bash?
533,398
<p>Without using the new 2.6 subprocess module, how can I get either os.popen or os.system to execute my commands using the tcsh instead of bash? I need to source some scripts which are written in tcsh before executing some other commands and I need to do this within python2.4.</p> <p>EDIT Thanks for answers using 'tcsh -c', but I'd like to avoid this because I have to do escape madness. The string will be interpreted by bash and then interpreted by tcsh. I'll have to do something like:</p> <pre><code>os.system("tcsh -c '"+re.compile("'").sub(r"""'"'"'""",my_cmd)+"'") </code></pre> <p>Can't I just tell python to open up a 'tcsh' sub-process instead of a 'bash' subprocess? Is that possible?</p> <p>P.S. I realize that bash is the cat's meow, but I'm working in a corporate environment and I'm going to choose to <em>not</em> fight a tcsh vs bash battle -- bigger fish to fry.</p>
2
2009-02-10T17:44:23Z
534,049
<p><code>os.system()</code> calls <code>system(3)</code> directly, and this system call is the one that "chooses" the shell. I put that in quotes, because <code>system(3)</code> will always execute <code>/bin/sh</code>.</p> <p>Thus, if you want Python to use a different shell, you have several options:</p> <ul> <li><p>Change the symlink <code>/bin/sh</code> to point to <code>tcsh</code>. This will have an effect on the whole system, which shouldn't be a problem since scripts that need bash features should start with <code>/bin/bash</code> anyway.</p></li> <li><p>Run your Python script from a <code>chroot</code> environment where <code>/bin/sh</code> points to <code>tcsh</code>.</p></li> <li><p>Replace <code>/bin/sh</code> with a script that executes <code>bash</code> or <code>tcsh</code> depending on who calls it (you could, for example, pass an additional environment variable.)</p></li> <li><p>Put everything you want to execute in <code>tcsh</code> in a separate shell script and call that with <code>os.system('tcsh -c...')</code>. This way you don't have to escape anything.</p></li> </ul>
-2
2009-02-10T20:27:51Z
[ "python", "shell", "csh", "tcsh" ]
What is a mixin, and why are they useful?
533,631
<p>In "<a href="http://rads.stackoverflow.com/amzn/click/0596009259">Programming Python</a>", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? </p> <p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&amp;pg=RA1-PA584&amp;lpg=RA1-PA584&amp;dq=programming+python+guimixin&amp;source=bl&amp;ots=HU833giXzH&amp;sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&amp;hl=en&amp;ei=x8iRSaTTF5iq-ganpbGPCw&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result">this example</a> (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right? </p> <p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p>
540
2009-02-10T18:50:42Z
533,675
<p>First, you should note that mixins only exist in multiple-inheritance languages. You can't do a mixin in Java or C#. </p> <p>Basically, a mixin is a stand-alone base type that provides limited functionality and polymorphic resonance for a child class. If you're thinking in C#, think of an interface that you don't have to actually implement because it's already implemented; you just inherit from it and benefit from its functionality. </p> <p>Mixins are typically narrow in scope and not meant to be extended. </p> <p>[edit -- as to why:]</p> <p>I suppose I should address why, since you asked. The big benefit is that you don't have to do it yourself over and over again. In C#, the biggest place where a mixin could benefit might be from the <a href="http://blog.jawaji.com/2008/08/disposal-pattern-c.html">Disposal pattern</a>. Whenever you implement IDisposable, you almost always want to follow the same pattern, but you end up writing and re-writing the same basic code with minor variations. If there were an extendable Disposal mixin, you could save yourself a lot of extra typing. </p> <p>[edit 2 -- to answer your other questions]</p> <blockquote> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p> </blockquote> <p>Yes. The difference between a mixin and standard multiple inheritance is just a matter of semantics; a class that has multiple inheritance might utilize a mixin as part of that multiple inheritance. </p> <p>The point of a mixin is to create a type that can be "mixed in" to any other type via inheritance without affecting the inheriting type while still offering some beneficial functionality for that type. </p> <p>Again, think of an interface that is already implemented. </p> <p>I personally don't use mixins since I develop primarily in a language that doesn't support them, so I'm having a really difficult time coming up with a decent example that will just supply that "ahah!" moment for you. But I'll try again. I'm going to use an example that's contrived -- most languages already provide the feature in some way or another -- but that will, hopefully, explain how mixins are supposed to be created and used. Here goes:</p> <p>Suppose you have a type that you want to be able to serialize to and from XML. You want the type to provide a "ToXML" method that returns a string containing an XML fragment with the data values of the type, and a "FromXML" that allows the type to reconstruct its data values from an XML fragment in a string. Again, this is a contrived example, so perhaps you use a file stream, or an XML Writer class from your language's runtime library... whatever. The point is that you want to serialize your object to XML and get a new object back from XML. </p> <p>The other important point in this example is that you want to do this in a generic way. You don't want to have to implement a "ToXML" and "FromXML" method for every type that you want to serialize, you want some generic means of ensuring that your type will do this and it just works. You want code reuse. </p> <p>If your language supported it, you could create the XmlSerializable mixin to do your work for you. This type would implement the ToXML and the FromXML methods. It would, using some mechanism that's not important to the example, be capable of gathering all the necessary data from any type that it's mixed in with to build the XML fragment returned by ToXML and it would be equally capable of restoring that data when FromXML is called. </p> <p>And.. that's it. To use it, you would have any type that needs to be serialized to XML inherit from XmlSerializable. Whenever you needed to serialize or deserialize that type, you would simply call ToXML or FromXML. In fact, since XmlSerializable is a fully-fledged type and polymorphic, you could conceivably build a document serializer that doesn't know anything about your original type, accepting only, say, an array of XmlSerializable types. </p> <p>Now imagine using this scenario for other things, like creating a mixin that ensures that every class that mixes it in logs every method call, or a mixin that provides transactionality to the type that mixes it in. The list can go on and on. </p> <p>If you just think of a mixin as a small base type designed to add a small amount of functionality to a type without otherwise affecting that type, then you're golden. </p> <p>Hopefully. :)</p>
152
2009-02-10T19:00:51Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
What is a mixin, and why are they useful?
533,631
<p>In "<a href="http://rads.stackoverflow.com/amzn/click/0596009259">Programming Python</a>", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? </p> <p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&amp;pg=RA1-PA584&amp;lpg=RA1-PA584&amp;dq=programming+python+guimixin&amp;source=bl&amp;ots=HU833giXzH&amp;sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&amp;hl=en&amp;ei=x8iRSaTTF5iq-ganpbGPCw&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result">this example</a> (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right? </p> <p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p>
540
2009-02-10T18:50:42Z
533,714
<p>Maybe an example from ruby can help:</p> <p>You can include the mixin <code>Comparable</code> and define one function <code>"&lt;=&gt;(other)"</code>, the mixin provides all those functions:</p> <pre><code>&lt;(other) &gt;(other) ==(other) &lt;=(other) &gt;=(other) between?(other) </code></pre> <p>It does this by invoking <code>&lt;=&gt;(other)</code> and giving back the right result.</p> <p><code>"instance &lt;=&gt; other"</code> returns 0 if both objects are equal, less than 0 if <code>instance</code> is bigger than <code>other</code> and more than 0 if <code>other</code> is bigger.</p>
6
2009-02-10T19:08:50Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
What is a mixin, and why are they useful?
533,631
<p>In "<a href="http://rads.stackoverflow.com/amzn/click/0596009259">Programming Python</a>", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? </p> <p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&amp;pg=RA1-PA584&amp;lpg=RA1-PA584&amp;dq=programming+python+guimixin&amp;source=bl&amp;ots=HU833giXzH&amp;sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&amp;hl=en&amp;ei=x8iRSaTTF5iq-ganpbGPCw&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result">this example</a> (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right? </p> <p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p>
540
2009-02-10T18:50:42Z
533,768
<p>I'd advise against mix-ins in new Python code, if you can find any other way around it (such as composition-instead-of-inheritance, or just monkey-patching methods into your own classes) that isn't much more effort.</p> <p>In old-style classes you could use mix-ins as a way of grabbing a few methods from another class. But in the new-style world everything, even the mix-in, inherits from <code>object</code>. That means that any use of multiple inheritance naturally introduces <a href="http://www.python.org/download/releases/2.2.3/descrintro/#mro">MRO issues</a>.</p> <p>There are ways to make multiple-inheritance MRO work in Python, most notably the super() function, but it means you have to do your whole class hierarchy using super(), and it's considerably more difficult to understand the flow of control.</p>
9
2009-02-10T19:21:19Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
What is a mixin, and why are they useful?
533,631
<p>In "<a href="http://rads.stackoverflow.com/amzn/click/0596009259">Programming Python</a>", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? </p> <p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&amp;pg=RA1-PA584&amp;lpg=RA1-PA584&amp;dq=programming+python+guimixin&amp;source=bl&amp;ots=HU833giXzH&amp;sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&amp;hl=en&amp;ei=x8iRSaTTF5iq-ganpbGPCw&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result">this example</a> (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right? </p> <p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p>
540
2009-02-10T18:50:42Z
534,284
<p>Perhaps a couple of examples will help.</p> <p>If you're building a class and you want it to act like a dictionary, you can define all the various <code>__ __</code> methods necessary. But that's a bit of a pain. As an alternative, you can just define a few, and inherit (in addition to any other inheritance) from <code>UserDict.DictMixin</code> (moved to <code>collections.DictMixin</code> in py3k). This will have the effect of automatically defining all the rest of the dictionary api.</p> <p>A second example: the GUI toolkit wxPython allows you to make list controls with multiple columns (like, say, the file display in Windows Explorer). By default, these lists are fairly basic. You can add additional functionality, such as the ability to sort the list by a particular column by clicking on the column header, by inheriting from ListCtrl and adding appropriate mixins.</p>
6
2009-02-10T21:27:41Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
What is a mixin, and why are they useful?
533,631
<p>In "<a href="http://rads.stackoverflow.com/amzn/click/0596009259">Programming Python</a>", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? </p> <p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&amp;pg=RA1-PA584&amp;lpg=RA1-PA584&amp;dq=programming+python+guimixin&amp;source=bl&amp;ots=HU833giXzH&amp;sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&amp;hl=en&amp;ei=x8iRSaTTF5iq-ganpbGPCw&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result">this example</a> (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right? </p> <p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p>
540
2009-02-10T18:50:42Z
547,714
<p>A mixin is a special kind of multiple inheritance. There are two main situations where mixins are used:</p> <ol> <li>You want to provide a lot of optional features for a class.</li> <li>You want to use one particular feature in a lot of different classes.</li> </ol> <p>For an example of number one, consider <a href="http://werkzeug.pocoo.org/docs/wrappers/">werkzeug's request and response system</a>. I can make a plain old request object by saying:</p> <pre><code>from werkzeug import BaseRequest class Request(BaseRequest): pass </code></pre> <p>If I want to add accept header support, I would make that</p> <pre><code>from werkzeug import BaseRequest, AcceptMixin class Request(BaseRequest, AcceptMixin): pass </code></pre> <p>If I wanted to make a request object that supports accept headers, etags, authentication, and user agent support, I could do this:</p> <pre><code>from werkzeug import BaseRequest, AcceptMixin, ETagRequestMixin, UserAgentMixin, AuthorizationMixin class Request(BaseRequest, AcceptMixin, ETagRequestMixin, UserAgentMixin, AuthorizationMixin): pass </code></pre> <p>The difference is subtle, but in the above examples, the mixin classes weren't made to stand on their own. In more traditional multiple inheritance, The AuthenticationMixin (for example) would probably be something more like Authenticator. That is, the class would probably be designed to stand on its own.</p>
386
2009-02-13T21:15:17Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
What is a mixin, and why are they useful?
533,631
<p>In "<a href="http://rads.stackoverflow.com/amzn/click/0596009259">Programming Python</a>", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? </p> <p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&amp;pg=RA1-PA584&amp;lpg=RA1-PA584&amp;dq=programming+python+guimixin&amp;source=bl&amp;ots=HU833giXzH&amp;sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&amp;hl=en&amp;ei=x8iRSaTTF5iq-ganpbGPCw&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result">this example</a> (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right? </p> <p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p>
540
2009-02-10T18:50:42Z
560,204
<p>It's not a Python example but in <a href="http://www.digitalmars.com/d/1.0/template-mixin.html" rel="nofollow">the D programing language</a> the term <a href="http://www.digitalmars.com/d/1.0/template-mixin.html" rel="nofollow"><code>mixin</code></a> is used to refer to a construct used much the same way; adding a pile of stuff to a class. </p> <p>In D (which by the way doesn't do MI) this is done by inserting a template (think syntactically aware and safe macros and you will be close) into a scope. This allows for a single line of code in a class, struct, function, module or whatever to expand to any number of declarations.</p>
5
2009-02-18T08:00:23Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
What is a mixin, and why are they useful?
533,631
<p>In "<a href="http://rads.stackoverflow.com/amzn/click/0596009259">Programming Python</a>", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? </p> <p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&amp;pg=RA1-PA584&amp;lpg=RA1-PA584&amp;dq=programming+python+guimixin&amp;source=bl&amp;ots=HU833giXzH&amp;sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&amp;hl=en&amp;ei=x8iRSaTTF5iq-ganpbGPCw&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result">this example</a> (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right? </p> <p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p>
540
2009-02-10T18:50:42Z
5,403,666
<p>I read that you have a c# background. So a good starting point might be a mixin implementation for .NET.</p> <p>You might want to check out the codeplex project at <a href="http://remix.codeplex.com/" rel="nofollow">http://remix.codeplex.com/</a></p> <p>Watch the lang.net Symposium link to get an overview. There is still more to come on documentation on codeplex page.</p> <p>regards Stefan </p>
1
2011-03-23T10:16:56Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
What is a mixin, and why are they useful?
533,631
<p>In "<a href="http://rads.stackoverflow.com/amzn/click/0596009259">Programming Python</a>", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? </p> <p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&amp;pg=RA1-PA584&amp;lpg=RA1-PA584&amp;dq=programming+python+guimixin&amp;source=bl&amp;ots=HU833giXzH&amp;sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&amp;hl=en&amp;ei=x8iRSaTTF5iq-ganpbGPCw&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result">this example</a> (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right? </p> <p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p>
540
2009-02-10T18:50:42Z
11,008,499
<p>Mixins is a concept in Programming in which the class provides functionalities but it is not meant to be used for instantiation. Main purpose of Mixins is to provide functionalities which are standalone and it would be best if the mixins itself do not have inheritance with other mixins and also avoid state. In languages such as Ruby, there is some direct language support but for Python, there isn't. However, you could used multi-class inheritance to execute the functionality provided in Python.</p> <p>I watched this video <a href="http://www.youtube.com/watch?v=v_uKI2NOLEM">http://www.youtube.com/watch?v=v_uKI2NOLEM</a> to understand the basics of mixins. It is quite useful for a beginner to understand the basics of mixins and how they work and the problems you might face in implementing them.</p> <p>Wikipedia is still the best: <a href="http://en.wikipedia.org/wiki/Mixin">http://en.wikipedia.org/wiki/Mixin</a></p>
12
2012-06-13T05:06:32Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
What is a mixin, and why are they useful?
533,631
<p>In "<a href="http://rads.stackoverflow.com/amzn/click/0596009259">Programming Python</a>", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? </p> <p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&amp;pg=RA1-PA584&amp;lpg=RA1-PA584&amp;dq=programming+python+guimixin&amp;source=bl&amp;ots=HU833giXzH&amp;sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&amp;hl=en&amp;ei=x8iRSaTTF5iq-ganpbGPCw&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result">this example</a> (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right? </p> <p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p>
540
2009-02-10T18:50:42Z
11,739,457
<p>mixin gives a way to add functionality in a class, i.e you can interact with methods defined in a module by including the module inside the desired class. Though ruby doesn't supports multiple inheritance but provides mixin as an alternative to achieve that.</p> <p>here is an example that explains how multiple inheritance is achieved using mixin.</p> <pre><code>module A # you create a module def a1 # lets have a method 'a1' in it end def a2 # Another method 'a2' end end module B # let's say we have another module def b1 # A method 'b1' end def b2 #another method b2 end end class Sample # we create a class 'Sample' include A # including module 'A' in the class 'Sample' (mixin) include B # including module B as well def S1 #class 'Sample' contains a method 's1' end end samp = Sample.new # creating an instance object 'samp' # we can access methods from module A and B in our class(power of mixin) samp.a1 # accessing method 'a1' from module A samp.a2 # accessing method 'a2' from module A samp.b1 # accessing method 'b1' from module B samp.b2 # accessing method 'a2' from module B samp.s1 # accessing method 's1' inside the class Sample </code></pre>
3
2012-07-31T11:49:59Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
What is a mixin, and why are they useful?
533,631
<p>In "<a href="http://rads.stackoverflow.com/amzn/click/0596009259">Programming Python</a>", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? </p> <p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&amp;pg=RA1-PA584&amp;lpg=RA1-PA584&amp;dq=programming+python+guimixin&amp;source=bl&amp;ots=HU833giXzH&amp;sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&amp;hl=en&amp;ei=x8iRSaTTF5iq-ganpbGPCw&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result">this example</a> (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right? </p> <p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p>
540
2009-02-10T18:50:42Z
15,372,409
<p>I just used a python mixin to implement unit testing for python milters. Normally, a milter talks to an MTA, making unit testing difficult. The test mixin overrides methods that talk to the MTA, and create a simulated environment driven by test cases instead.</p> <p>So, you take an unmodified milter application, like spfmilter, and mixin TestBase, like this:</p> <pre><code>class TestMilter(TestBase,spfmilter.spfMilter): def __init__(self): TestBase.__init__(self) spfmilter.config = spfmilter.Config() spfmilter.config.access_file = 'test/access.db' spfmilter.spfMilter.__init__(self) </code></pre> <p>Then, use TestMilter in the test cases for the milter application:</p> <pre><code>def testPass(self): milter = TestMilter() rc = milter.connect('mail.example.com',ip='192.0.2.1') self.assertEqual(rc,Milter.CONTINUE) rc = milter.feedMsg('test1',sender='good@example.com') self.assertEqual(rc,Milter.CONTINUE) milter.close() </code></pre> <p><a href="http://pymilter.cvs.sourceforge.net/viewvc/pymilter/pymilter/Milter/test.py?revision=1.6&amp;view=markup" rel="nofollow">http://pymilter.cvs.sourceforge.net/viewvc/pymilter/pymilter/Milter/test.py?revision=1.6&amp;view=markup</a></p>
3
2013-03-12T21:22:43Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
What is a mixin, and why are they useful?
533,631
<p>In "<a href="http://rads.stackoverflow.com/amzn/click/0596009259">Programming Python</a>", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? </p> <p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&amp;pg=RA1-PA584&amp;lpg=RA1-PA584&amp;dq=programming+python+guimixin&amp;source=bl&amp;ots=HU833giXzH&amp;sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&amp;hl=en&amp;ei=x8iRSaTTF5iq-ganpbGPCw&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result">this example</a> (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right? </p> <p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p>
540
2009-02-10T18:50:42Z
17,491,186
<p>I think of them as a disciplined way of using multiple inheritance - because ultimately a mixin is just another python class that (might) follow the conventions about classes that are called mixins.</p> <p>My understanding of the conventions that govern something you would call a Mixin are that a Mixin:</p> <ul> <li>adds methods but not instance variables (class constants are OK)</li> <li>only inherits from <code>object</code> (in Python)</li> </ul> <p>That way it limits the potential complexity of multiple inheritance, and makes it reasonably easy to track the flow of your program by limiting where you have to look (compared to full multiple inheritance). They are similar to ruby modules.</p> <p>If I want to add instance variables (with more flexibility than allowed for by single inheritance) then I tend to go for composition.</p> <p>Having said that, I have seen classes called XYZMixin that do have instance variables.</p>
17
2013-07-05T14:26:37Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
What is a mixin, and why are they useful?
533,631
<p>In "<a href="http://rads.stackoverflow.com/amzn/click/0596009259">Programming Python</a>", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? </p> <p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&amp;pg=RA1-PA584&amp;lpg=RA1-PA584&amp;dq=programming+python+guimixin&amp;source=bl&amp;ots=HU833giXzH&amp;sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&amp;hl=en&amp;ei=x8iRSaTTF5iq-ganpbGPCw&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result">this example</a> (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right? </p> <p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p>
540
2009-02-10T18:50:42Z
20,022,860
<p>This answer aims to explain mixins <strong>with examples</strong> that are:</p> <ul> <li><p><strong>self-contained</strong>: short, with no need to know any libraries to understand the example.</p></li> <li><p><strong>in Python</strong>, not in other languages.</p> <p>It is understandable that there were examples from other languages such as Ruby since the term is much more common in those languages, but this is a <em>Python</em> thread.</p></li> </ul> <p>It shall also consider the controversial question:</p> <blockquote> <p>Is multiple inheritance necessary or not to characterize a mixin?</p> </blockquote> <p><strong>Definitions</strong></p> <p>I have yet to see a citation from an "authoritative" source clearly saying what is a mixin in Python.</p> <p>I have seen 2 possible definitions of a mixin (if they are to be considered as different from other similar concepts such as abstract base classes), and people don't entirely agree on which one is correct.</p> <p>The consensus may vary between different languages.</p> <p><strong>Definition 1: no multiple inheritance</strong></p> <p>A mixin is a class such that some method of the class uses a method which is not defined in the class.</p> <p>Therefore the class is not meant to be instantiated, but rather serve as a base class. Otherwise the instance would have methods that cannot be called without raising an exception.</p> <p>A constraint which some sources add is that the class may not contain data, only methods, but I don't see why this is necessary. In practice however, many useful mixins don't have any data, and base classes without data are simpler to use.</p> <p>A classic example is the implementation of all comparison operators from only <code>&lt;=</code> and <code>==</code>:</p> <pre><code>class ComparableMixin(object): """This class has methods which use `&lt;=` and `==`, but this class does NOT implement those methods.""" def __ne__(self, other): return not (self == other) def __lt__(self, other): return self &lt;= other and (self != other) def __gt__(self, other): return not self &lt;= other def __ge__(self, other): return self == other or self &gt; other class Integer(ComparableMixin): def __init__(self, i): self.i = i def __le__(self, other): return self.i &lt;= other.i def __eq__(self, other): return self.i == other.i assert Integer(0) &lt; Integer(1) assert Integer(0) != Integer(1) assert Integer(1) &gt; Integer(0) assert Integer(1) &gt;= Integer(1) # It is possible to instantiate a mixin: o = ComparableMixin() # but one of its methods raise an exception: #o != o </code></pre> <p>This particular example could have been achieved via the <code>functools.total_ordering()</code> decorator, but the game here was to reinvent the wheel:</p> <pre><code>import functools @functools.total_ordering class Integer(object): def __init__(self, i): self.i = i def __le__(self, other): return self.i &lt;= other.i def __eq__(self, other): return self.i == other.i assert Integer(0) &lt; Integer(1) assert Integer(0) != Integer(1) assert Integer(1) &gt; Integer(0) assert Integer(1) &gt;= Integer(1) </code></pre> <p><strong>Definition 2: multiple inheritance</strong></p> <p>A mixin is a design pattern in which some method of a base class uses a method it does not define, and that method is meant to be implemented by <em>another base class</em>, not by the derived like in Definition 1.</p> <p>The term <em>mixin class</em> refers to base classes which are intended to be used in that design pattern (TODO those that use the method, or those that implement it?)</p> <p>It is not easy to decide if a given class is a mixin or not: the method could be just implemented on the derived class, in which case we're back to Definition 1. You have to consider the author's intentions.</p> <p>This pattern is interesting because it is possible to recombine functionalities with different choices of base classes:</p> <pre><code>class HasMethod1(object): def method(self): return 1 class HasMethod2(object): def method(self): return 2 class UsesMethod10(object): def usesMethod(self): return self.method() + 10 class UsesMethod20(object): def usesMethod(self): return self.method() + 20 class C1_10(HasMethod1, UsesMethod10): pass class C1_20(HasMethod1, UsesMethod20): pass class C2_10(HasMethod2, UsesMethod10): pass class C2_20(HasMethod2, UsesMethod20): pass assert C1_10().usesMethod() == 11 assert C1_20().usesMethod() == 21 assert C2_10().usesMethod() == 12 assert C2_20().usesMethod() == 22 # Nothing prevents implementing the method # on the base class like in Definition 1: class C3_10(UsesMethod10): def method(self): return 3 assert C3_10().usesMethod() == 13 </code></pre> <p><strong>Authoritative Python occurrences</strong></p> <p>At the <a href="http://docs.python.org/dev/library/collections.abc.html">official documentatiton for collections.abc</a> the documentation explicitly uses the term <em>Mixin Methods</em>.</p> <p>It states that if a class:</p> <ul> <li>implements <code>__next__</code></li> <li>inherits from a single class <code>Iterator</code></li> </ul> <p>then the class gets an <code>__iter__</code> <em>mixin method</em> for free.</p> <p>Therefore at least on this point of the documentation, <strong>mixin does not not require multiple inheritance</strong>, and is coherent with Definition 1.</p> <p>The documentation could of course be contradictory at different points, and other important Python libraries might be using the other definition in their documentation.</p> <p>This page also uses the term <code>Set mixin</code>, which clearly suggests that classes like <code>Set</code> and <code>Iterator</code> can be called Mixin classes.</p> <p><strong>In other languages</strong></p> <ul> <li><p>Ruby: Clearly does not require multiple inheritance for mixin, as mentioned in major reference books such as <a href="http://rads.stackoverflow.com/amzn/click/1937785491">Programming Ruby</a> and The Ruby programming Language</p></li> <li><p>C++: A method that is not implemented is a pure virtual method.</p> <p>Definition 1 coincides with the definition of an abstract class (a class that has a pure virtual method). That class cannot be instantiated.</p> <p>Definition 2 is not possible, since it is not possible to implement pure virtual methods from other base classes in C++.</p> <p>It might be possible however to achieve a similar effect with templates as mentioned <a href="http://www.helplib.com/qa/43662?start=10#yf_sen_43704_1">here</a>.</p></li> </ul>
77
2013-11-16T19:36:03Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
What is a mixin, and why are they useful?
533,631
<p>In "<a href="http://rads.stackoverflow.com/amzn/click/0596009259">Programming Python</a>", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? </p> <p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&amp;pg=RA1-PA584&amp;lpg=RA1-PA584&amp;dq=programming+python+guimixin&amp;source=bl&amp;ots=HU833giXzH&amp;sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&amp;hl=en&amp;ei=x8iRSaTTF5iq-ganpbGPCw&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result">this example</a> (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right? </p> <p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p>
540
2009-02-10T18:50:42Z
25,871,340
<p>Re Ciro Santilli: It is actually possible to use your second definition of mixins in C++ using interfaces</p> <pre><code>#include &lt;iostream&gt; struct Interface { virtual int method() const = 0; }; class HasMethod1 : public virtual Interface { int method() const {return 1;} }; class HasMethod2 : public virtual Interface { int method() const {return 2;} }; class UsesMethod10 : public virtual Interface { public: int usesMethod() const {return 10+method();} }; class UsesMethod20 : public virtual Interface { public: int usesMethod() const {return 20+method();} }; template &lt;typename T1, typename T2&gt; struct Combination : public T1, public T2 { }; int main() { std::cout &lt;&lt; Combination&lt;HasMethod1, UsesMethod10&gt;().usesMethod() &lt;&lt; std::endl; std::cout &lt;&lt; Combination&lt;HasMethod2, UsesMethod10&gt;().usesMethod() &lt;&lt; std::endl; std::cout &lt;&lt; Combination&lt;HasMethod1, UsesMethod20&gt;().usesMethod() &lt;&lt; std::endl; std::cout &lt;&lt; Combination&lt;HasMethod2, UsesMethod20&gt;().usesMethod() &lt;&lt; std::endl; return 0; } </code></pre> <p>It would probably be better to use a form of CRTP to do so, but I'm not going to go overboard here.</p>
1
2014-09-16T14:23:14Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
What is a mixin, and why are they useful?
533,631
<p>In "<a href="http://rads.stackoverflow.com/amzn/click/0596009259">Programming Python</a>", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? </p> <p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&amp;pg=RA1-PA584&amp;lpg=RA1-PA584&amp;dq=programming+python+guimixin&amp;source=bl&amp;ots=HU833giXzH&amp;sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&amp;hl=en&amp;ei=x8iRSaTTF5iq-ganpbGPCw&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result">this example</a> (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right? </p> <p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p>
540
2009-02-10T18:50:42Z
27,653,307
<p>I think there have been some good explanations here but I wanted to provide another perspective.</p> <p>In Scala, you can do mixins as has been described here but what is very interesting is that the mixins are actually 'fused' together to create a new kind of class to inherit from. In essence, you do not inherit from multiple classes/mixins, but rather, generate a new kind of class with all the properties of the mixin to inherit from. This makes sense since Scala is based on the JVM where multiple-inheritance is not currently supported (as of Java 8). This mixin class type, by the way, is a special type called a Trait in Scala.</p> <p>It's hinted at in the way a class is defined: class NewClass extends FirstMixin with SecondMixin with ThirdMixin ...</p> <p>I'm not sure if the CPython interpreter does the same (mixin class-composition) but I wouldn't be surprised. Also, coming from a C++ background, I would not call an ABC or 'interface' equivalent to a mixin -- it's a similar concept but divergent in use and implementation.</p>
6
2014-12-26T05:54:36Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
What is a mixin, and why are they useful?
533,631
<p>In "<a href="http://rads.stackoverflow.com/amzn/click/0596009259">Programming Python</a>", Mark Lutz mentions "mixins". I'm from a C/C++/C# background and I have not heard the term before. What is a mixin? </p> <p>Reading between the lines of <a href="http://books.google.com/books?id=5zYVUIl7F0QC&amp;pg=RA1-PA584&amp;lpg=RA1-PA584&amp;dq=programming+python+guimixin&amp;source=bl&amp;ots=HU833giXzH&amp;sig=jwLpxSp4m_VbOYQ897UDkGNx_2U&amp;hl=en&amp;ei=x8iRSaTTF5iq-ganpbGPCw&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result">this example</a> (which I've linked to because it's quite long), I'm presuming it's a case of using multiple inheritance to extend a class as opposed to 'proper' subclassing. Is this right? </p> <p>Why would I want to do that rather than put the new functionality into a subclass? For that matter, why would a mixin/multiple inheritance approach be better than using composition?</p> <p>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</p>
540
2009-02-10T18:50:42Z
36,222,493
<blockquote> <h1>What separates a mixin from multiple inheritance? Is it just a matter of semantics?</h1> </blockquote> <p>A mixin is a limited form of multiple inheritance. In some languages the mechanism for adding a mixin to a class is slightly different (in terms of syntax) from that of inheritance.</p> <p>In the context of Python especially, a mixin is a parent class that provides functionality to subclasses but is not intended to be instantiated itself. </p> <p>What might cause you to say, "that's just multiple inheritance, not really a mixin" is if the class that might be confused for a mixin can actually be instantiated and used - so indeed it is a semantic, and very real, difference.</p> <h2>A Contrived Example</h2> <p>This is a mixin that is mostly for demonstration purposes - most objects will evolve beyond the usefulness of this repr:</p> <pre><code>class SimpleInitReprMixin(object): """mixin, don't instantiate - useful for classes instantiable by keyword arguments to their __init__ method. """ __slots__ = () # allow subclasses to use __slots__ to prevent __dict__ def __repr__(self): kwarg_strings = [] d = getattr(self, '__dict__', None) if d is not None: for k, v in d.items(): kwarg_strings.append('{k}={v}'.format(k=k, v=repr(v))) slots = getattr(self, '__slots__', None) if slots is not None: for k in slots: v = getattr(self, k, None) kwarg_strings.append('{k}={v}'.format(k=k, v=repr(v))) return '{name}({kwargs})'.format( name=type(self).__name__, kwargs=', '.join(kwarg_strings) ) </code></pre> <p>and usage would be:</p> <pre><code>class Foo(SimpleInitReprMixin): # add other mixins and/or extend another class here __slots__ = 'foo', def __init__(self, foo=None): self.foo = foo super(Foo, self).__init__() </code></pre> <p>And usage:</p> <pre><code>&gt;&gt;&gt; f1 = Foo('bar') &gt;&gt;&gt; f2 = Foo() &gt;&gt;&gt; f1 Foo(foo='bar') &gt;&gt;&gt; f2 Foo(foo=None) </code></pre>
1
2016-03-25T15:05:09Z
[ "python", "oop", "multiple-inheritance", "mixins" ]
How do I use the the Django ORM to query this many-to-many example?
533,726
<p>I have the following models:</p> <pre><code>class Author(models.Model): author_name = models.CharField() class Book(models.Model): book_name = models.CharField() class AuthorBook(models.Model): author_id = models.ForeignKeyField(Author) book_id = models.ForeignKeyField(Book) </code></pre> <p>With that being said, I'm trying to emulate this query using the Django ORM (select all of the books written by a specific author, noting that Authors can have many books and Books can have many Authors):</p> <pre><code>SELECT book_name FROM authorbook, book WHERE authorbook.author_id = 1 AND authorbook.book_id = book.id </code></pre> <p>I've read <a href="http://www.djangoproject.com/documentation/models/many_to_many/">this FAQ page</a> on the Django website, but before I modify my model structure and remove AuthorBook, I was curious if I could emulate that query using the current structure.</p>
5
2009-02-10T19:12:06Z
533,770
<p>You should be able to do:</p> <pre><code>books = Book.objects.filter(authorbook__author_id=1) </code></pre> <p>to get a QuerySet of Book objects matching your author_id restriction.</p> <p>The nice thing about Django is you can cook this up and play around with it in the shell. You may also find <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships">http://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships</a> to be useful.</p>
14
2009-02-10T19:21:36Z
[ "python", "django", "django-orm" ]
How do I use the the Django ORM to query this many-to-many example?
533,726
<p>I have the following models:</p> <pre><code>class Author(models.Model): author_name = models.CharField() class Book(models.Model): book_name = models.CharField() class AuthorBook(models.Model): author_id = models.ForeignKeyField(Author) book_id = models.ForeignKeyField(Book) </code></pre> <p>With that being said, I'm trying to emulate this query using the Django ORM (select all of the books written by a specific author, noting that Authors can have many books and Books can have many Authors):</p> <pre><code>SELECT book_name FROM authorbook, book WHERE authorbook.author_id = 1 AND authorbook.book_id = book.id </code></pre> <p>I've read <a href="http://www.djangoproject.com/documentation/models/many_to_many/">this FAQ page</a> on the Django website, but before I modify my model structure and remove AuthorBook, I was curious if I could emulate that query using the current structure.</p>
5
2009-02-10T19:12:06Z
533,799
<p>"AuthorBook" seems not correctly modeled.</p> <p>You should use a <code>ManyToManyField</code>:</p> <pre><code>class Book(models.Model): name = models.CharField() authors = models.ManyToManyField(Author) </code></pre> <p>Then you can do:</p> <pre><code>books = Book.objects.filter(authors__id=1) </code></pre>
14
2009-02-10T19:28:58Z
[ "python", "django", "django-orm" ]
Get the cartesian product of a series of lists in Python
533,905
<p>How can I get the Cartesian product (every possible combination of values) from a group of lists?</p> <p>Input: </p> <pre><code>somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] </code></pre> <p>Desired output:</p> <pre><code>[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...] </code></pre>
131
2009-02-10T19:54:17Z
533,917
<p>In Python 2.6+</p> <pre><code>import itertools for element in itertools.product(*somelists): print element </code></pre> <p>Documentation: <a href="https://docs.python.org/2/library/itertools.html#itertools.product">Python 2 - itertools.product</a></p>
159
2009-02-10T19:58:01Z
[ "python", "list" ]
Get the cartesian product of a series of lists in Python
533,905
<p>How can I get the Cartesian product (every possible combination of values) from a group of lists?</p> <p>Input: </p> <pre><code>somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] </code></pre> <p>Desired output:</p> <pre><code>[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...] </code></pre>
131
2009-02-10T19:54:17Z
533,919
<pre><code>import itertools &gt;&gt;&gt; for i in itertools.product([1,2,3],['a','b'],[4,5]): ... print i ... (1, 'a', 4) (1, 'a', 5) (1, 'b', 4) (1, 'b', 5) (2, 'a', 4) (2, 'a', 5) (2, 'b', 4) (2, 'b', 5) (3, 'a', 4) (3, 'a', 5) (3, 'b', 4) (3, 'b', 5) &gt;&gt;&gt; </code></pre>
42
2009-02-10T19:58:31Z
[ "python", "list" ]
Get the cartesian product of a series of lists in Python
533,905
<p>How can I get the Cartesian product (every possible combination of values) from a group of lists?</p> <p>Input: </p> <pre><code>somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] </code></pre> <p>Desired output:</p> <pre><code>[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...] </code></pre>
131
2009-02-10T19:54:17Z
533,928
<p>with <a href="http://docs.python.org/library/itertools.html#itertools.permutations">itertools.product</a>:</p> <pre><code>import itertools result = list(itertools.product(*somelists)) </code></pre>
7
2009-02-10T20:01:26Z
[ "python", "list" ]
Get the cartesian product of a series of lists in Python
533,905
<p>How can I get the Cartesian product (every possible combination of values) from a group of lists?</p> <p>Input: </p> <pre><code>somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] </code></pre> <p>Desired output:</p> <pre><code>[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...] </code></pre>
131
2009-02-10T19:54:17Z
533,934
<p>In Python 2.6 and above you can use 'itertools.product`. In older versions of Python you can use the following (almost -- see documentation) equivalent <a href="http://docs.python.org/library/itertools.html#itertools.product">code from the documentation</a>:</p> <pre><code>def product(*args, **kwds): # product('ABCD', 'xy') --&gt; Ax Ay Bx By Cx Cy Dx Dy # product(range(2), repeat=3) --&gt; 000 001 010 011 100 101 110 111 pools = map(tuple, args) * kwds.get('repeat', 1) result = [[]] for pool in pools: result = [x+[y] for x in result for y in pool] for prod in result: yield tuple(prod) </code></pre> <p>The result of both is an iterator, so if you really need a list for furthert processing, use <code>list(result)</code>.</p>
9
2009-02-10T20:02:47Z
[ "python", "list" ]
Get the cartesian product of a series of lists in Python
533,905
<p>How can I get the Cartesian product (every possible combination of values) from a group of lists?</p> <p>Input: </p> <pre><code>somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] </code></pre> <p>Desired output:</p> <pre><code>[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...] </code></pre>
131
2009-02-10T19:54:17Z
534,085
<p>For Python 2.5 and older:</p> <pre><code>&gt;&gt;&gt; [(a, b, c) for a in [1,2,3] for b in ['a','b'] for c in [4,5]] [(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5), (2, 'b', 4), (2, 'b', 5), (3, 'a', 4), (3, 'a', 5), (3, 'b', 4), (3, 'b', 5)] </code></pre> <p>Here's a recursive version of <code>product()</code> (just an illustration):</p> <pre><code>def product(*args): if not args: return iter(((),)) # yield tuple() return (items + (item,) for items in product(*args[:-1]) for item in args[-1]) </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; list(product([1,2,3], ['a','b'], [4,5])) [(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5), (2, 'b', 4), (2, 'b', 5), (3, 'a', 4), (3, 'a', 5), (3, 'b', 4), (3, 'b', 5)] &gt;&gt;&gt; list(product([1,2,3])) [(1,), (2,), (3,)] &gt;&gt;&gt; list(product([])) [] &gt;&gt;&gt; list(product()) [()] </code></pre>
24
2009-02-10T20:38:16Z
[ "python", "list" ]
Get the cartesian product of a series of lists in Python
533,905
<p>How can I get the Cartesian product (every possible combination of values) from a group of lists?</p> <p>Input: </p> <pre><code>somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] </code></pre> <p>Desired output:</p> <pre><code>[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...] </code></pre>
131
2009-02-10T19:54:17Z
17,102,114
<p>Here is a recursive generator, which doesn't store any temporary lists</p> <pre><code>def product(ar_list): if not ar_list: yield () else: for a in ar_list[0]: for prod in product(ar_list[1:]): yield (a,)+prod print list(product([[1,2],[3,4],[5,6]])) </code></pre> <p>Output:</p> <pre><code>[(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6)] </code></pre>
2
2013-06-14T06:08:27Z
[ "python", "list" ]
Get the cartesian product of a series of lists in Python
533,905
<p>How can I get the Cartesian product (every possible combination of values) from a group of lists?</p> <p>Input: </p> <pre><code>somelists = [ [1, 2, 3], ['a', 'b'], [4, 5] ] </code></pre> <p>Desired output:</p> <pre><code>[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), (2, 'a', 5) ...] </code></pre>
131
2009-02-10T19:54:17Z
33,425,736
<p>Just to add a bit to what has already been said: if you use sympy, you can use symbols rather than strings which makes them mathematically useful.</p> <pre><code>import itertools import sympy x, y = sympy.symbols('x y') somelist = [[x,y], [1,2,3], [4,5]] somelist2 = [[1,2], [1,2,3], [4,5]] for element in itertools.product(*somelist): print element </code></pre> <p>About <a href="http://sympy.com" rel="nofollow">sympy</a>.</p>
1
2015-10-29T22:28:11Z
[ "python", "list" ]
Python Golf: what's the most concise way of turning this list of lists into a dictionary:
534,608
<p>I have a list of lists that looks like this:</p> <pre><code>[['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] </code></pre> <p>and I want to turn it into a dictionary where each key is a name and each value is a number corresponding to the position of its sublist in the list:</p> <pre><code>{'Tom': 0, 'Dick': 0, 'Harry': 1, 'John': 1, 'Mike': 1, 'Bob': 2} </code></pre> <p>I tried various list comprehensions, but I couldn't get it to work right with the nested lists. I could use a nested loop, like this:</p> <pre><code>names = [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] names_dict = {} for i, name_sublist in enumerate(names): for name in name_sublist: names_dict[name] = i </code></pre> <p>but I suspect there is a shorter, more elegant way of doing it.</p>
3
2009-02-10T22:49:02Z
534,615
<pre><code>names_dict = dict((name,index) for index,lst in enumerate(names) for name in lst) </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; names = [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] &gt;&gt;&gt; names_dict = dict((name,index) ... for index,lst in enumerate(names) ... for name in lst) &gt;&gt;&gt; names_dict {'Tom': 0, 'Mike': 1, 'Dick': 0, 'Harry': 1, 'Bob': 2, 'John': 1} </code></pre>
14
2009-02-10T22:51:09Z
[ "python", "code-golf" ]
Python Golf: what's the most concise way of turning this list of lists into a dictionary:
534,608
<p>I have a list of lists that looks like this:</p> <pre><code>[['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] </code></pre> <p>and I want to turn it into a dictionary where each key is a name and each value is a number corresponding to the position of its sublist in the list:</p> <pre><code>{'Tom': 0, 'Dick': 0, 'Harry': 1, 'John': 1, 'Mike': 1, 'Bob': 2} </code></pre> <p>I tried various list comprehensions, but I couldn't get it to work right with the nested lists. I could use a nested loop, like this:</p> <pre><code>names = [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] names_dict = {} for i, name_sublist in enumerate(names): for name in name_sublist: names_dict[name] = i </code></pre> <p>but I suspect there is a shorter, more elegant way of doing it.</p>
3
2009-02-10T22:49:02Z
534,686
<p>Same idea as MizardX, but slightly smaller and prettier in Python 3.0 using <a href="http://www.python.org/dev/peps/pep-0274/" rel="nofollow">dict comprehensions:</a></p> <pre><code>&gt;&gt;&gt; names = [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] &gt;&gt;&gt; names_dict = {name:index for index, lst in enumerate(names) for name in lst} &gt;&gt;&gt; names_dict {'Tom': 0, 'Mike': 1, 'Dick': 0, 'Harry': 1, 'Bob': 2, 'John': 1} </code></pre>
19
2009-02-10T23:09:25Z
[ "python", "code-golf" ]
Python Golf: what's the most concise way of turning this list of lists into a dictionary:
534,608
<p>I have a list of lists that looks like this:</p> <pre><code>[['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] </code></pre> <p>and I want to turn it into a dictionary where each key is a name and each value is a number corresponding to the position of its sublist in the list:</p> <pre><code>{'Tom': 0, 'Dick': 0, 'Harry': 1, 'John': 1, 'Mike': 1, 'Bob': 2} </code></pre> <p>I tried various list comprehensions, but I couldn't get it to work right with the nested lists. I could use a nested loop, like this:</p> <pre><code>names = [['Tom', 'Dick'], ['Harry', 'John', 'Mike'], ['Bob']] names_dict = {} for i, name_sublist in enumerate(names): for name in name_sublist: names_dict[name] = i </code></pre> <p>but I suspect there is a shorter, more elegant way of doing it.</p>
3
2009-02-10T22:49:02Z
4,673,778
<p>python 2.6</p> <pre><code>dict([(t,l.index(x)) for x in l for t in x]) </code></pre> <p>python3.0</p> <pre><code>{t:l.index(x) for x in l for t in x} </code></pre> <p>if l is the list of names</p>
1
2011-01-12T20:39:19Z
[ "python", "code-golf" ]
How to create a GUID/UUID in Python
534,839
<p>How do I create a GUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python?</p>
245
2009-02-10T23:51:21Z
534,847
<p>"The uuid module, in Python 2.5 and up, provides RFC compliant UUID generation. See the module docs and the RFC for details."</p> <p>Docs:</p> <ul> <li>Python 2: <a href="http://docs.python.org/2/library/uuid.html">http://docs.python.org/2/library/uuid.html</a></li> <li>Python 3: <a href="https://docs.python.org/3/library/uuid.html">https://docs.python.org/3/library/uuid.html</a></li> </ul> <p><a href="http://code.activestate.com/lists/python-list/72693/">http://code.activestate.com/lists/python-list/72693/</a></p>
169
2009-02-10T23:54:26Z
[ "python", "guid", "uuid" ]
How to create a GUID/UUID in Python
534,839
<p>How do I create a GUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python?</p>
245
2009-02-10T23:51:21Z
534,851
<p>If you're using Python 2.5 or later, the <a href="https://docs.python.org/2/library/uuid.html#module-uuid"><strong>uuid module</strong></a> is already included with the Python standard distribution.</p> <p>Ex: </p> <pre><code>&gt;&gt;&gt; import uuid &gt;&gt;&gt; uuid.uuid4() UUID('5361a11b-615c-42bf-9bdb-e2c3790ada14') </code></pre>
242
2009-02-10T23:55:52Z
[ "python", "guid", "uuid" ]
How to create a GUID/UUID in Python
534,839
<p>How do I create a GUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python?</p>
245
2009-02-10T23:51:21Z
10,984,286
<p>I use GUIDs as random keys for database type operations.</p> <p>The hexadecimal form, with the dashes and extra characters seem unnecessarily long to me. But I also like that strings representing hexadecimal numbers are very safe in that they do not contain characters that can cause problems in some situations such as '+','=', etc..</p> <p>Instead of hexadecimal, I use a url-safe base64 string. The following does not conform to any UUID/GUID spec though (other than having the required amount of randomness).</p> <pre><code>import base64 import uuid # get a UUID - URL safe, Base64 def get_a_uuid(): r_uuid = base64.urlsafe_b64encode(uuid.uuid4().bytes) return r_uuid.replace('=', '') </code></pre>
19
2012-06-11T16:47:53Z
[ "python", "guid", "uuid" ]
How to create a GUID/UUID in Python
534,839
<p>How do I create a GUID in Python that is platform independent? I hear there is a method using ActivePython on Windows but it's Windows only because it uses COM. Is there a method using plain Python?</p>
245
2009-02-10T23:51:21Z
27,302,466
<p>Copied from : <a href="https://docs.python.org/2/library/uuid.html">https://docs.python.org/2/library/uuid.html</a> (Since the links posted were not active and they keep updating)</p> <pre><code>&gt;&gt;&gt; import uuid &gt;&gt;&gt; # make a UUID based on the host ID and current time &gt;&gt;&gt; uuid.uuid1() UUID('a8098c1a-f86e-11da-bd1a-00112444be1e') &gt;&gt;&gt; # make a UUID using an MD5 hash of a namespace UUID and a name &gt;&gt;&gt; uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org') UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e') &gt;&gt;&gt; # make a random UUID &gt;&gt;&gt; uuid.uuid4() UUID('16fd2706-8baf-433b-82eb-8c7fada847da') &gt;&gt;&gt; # make a UUID using a SHA-1 hash of a namespace UUID and a name &gt;&gt;&gt; uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org') UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d') &gt;&gt;&gt; # make a UUID from a string of hex digits (braces and hyphens ignored) &gt;&gt;&gt; x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}') &gt;&gt;&gt; # convert a UUID to a string of hex digits in standard form &gt;&gt;&gt; str(x) '00010203-0405-0607-0809-0a0b0c0d0e0f' &gt;&gt;&gt; # get the raw 16 bytes of the UUID &gt;&gt;&gt; x.bytes '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' &gt;&gt;&gt; # make a UUID from a 16-byte string &gt;&gt;&gt; uuid.UUID(bytes=x.bytes) UUID('00010203-0405-0607-0809-0a0b0c0d0e0f') </code></pre>
43
2014-12-04T19:34:05Z
[ "python", "guid", "uuid" ]
Subtracting 2 lists in Python
534,855
<p>Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like</p> <pre><code>[2,2,2] - [1,1,1] = [1,1,1] </code></pre> <p>Should I use tuples?</p> <p>If none of them defines these operands on these types, can I define it instead?</p> <p>If not, should I create a new vector3 class?</p>
33
2009-02-10T23:57:22Z
534,862
<p>If you have two lists called 'a' and 'b', you can do: <code>[m - n for m,n in zip(a,b)]</code></p>
2
2009-02-10T23:59:49Z
[ "python", "list", "tuples", "vector" ]
Subtracting 2 lists in Python
534,855
<p>Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like</p> <pre><code>[2,2,2] - [1,1,1] = [1,1,1] </code></pre> <p>Should I use tuples?</p> <p>If none of them defines these operands on these types, can I define it instead?</p> <p>If not, should I create a new vector3 class?</p>
33
2009-02-10T23:57:22Z
534,866
<p>If this is something you end up doing frequently, and with different operations, you should probably create a class to handle cases like this, or better use some library like <a href="http://numpy.scipy.org/">Numpy</a>.</p> <p>Otherwise, look for <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions">list comprehensions</a> used with the <a href="http://docs.python.org/library/functions.html#zip">zip</a> builtin function:</p> <pre><code>[a_i - b_i for a_i, b_i in zip(a, b)] </code></pre>
77
2009-02-11T00:00:52Z
[ "python", "list", "tuples", "vector" ]
Subtracting 2 lists in Python
534,855
<p>Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like</p> <pre><code>[2,2,2] - [1,1,1] = [1,1,1] </code></pre> <p>Should I use tuples?</p> <p>If none of them defines these operands on these types, can I define it instead?</p> <p>If not, should I create a new vector3 class?</p>
33
2009-02-10T23:57:22Z
534,872
<p>Check out the <a href="http://numpy.scipy.org/">NumPy</a> package for python.</p>
7
2009-02-11T00:01:51Z
[ "python", "list", "tuples", "vector" ]
Subtracting 2 lists in Python
534,855
<p>Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like</p> <pre><code>[2,2,2] - [1,1,1] = [1,1,1] </code></pre> <p>Should I use tuples?</p> <p>If none of them defines these operands on these types, can I define it instead?</p> <p>If not, should I create a new vector3 class?</p>
33
2009-02-10T23:57:22Z
534,876
<p>If you plan on performing more than simple one liners, it would be better to implement your own class and override the appropriate operators as they apply to your case.</p> <p>Taken from <a href="http://www.math.okstate.edu/~ullrich/PyPlug/" rel="nofollow">Mathematics in Python</a>:</p> <pre><code>class Vector: def __init__(self, data): self.data = data def __repr__(self): return repr(self.data) def __add__(self, other): data = [] for j in range(len(self.data)): data.append(self.data[j] + other.data[j]) return Vector(data) x = Vector([1, 2, 3]) print x + x </code></pre>
3
2009-02-11T00:03:52Z
[ "python", "list", "tuples", "vector" ]
Subtracting 2 lists in Python
534,855
<p>Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like</p> <pre><code>[2,2,2] - [1,1,1] = [1,1,1] </code></pre> <p>Should I use tuples?</p> <p>If none of them defines these operands on these types, can I define it instead?</p> <p>If not, should I create a new vector3 class?</p>
33
2009-02-10T23:57:22Z
534,910
<p>If your lists are a and b, you can do:</p> <pre><code>map(int.__sub__, a, b) </code></pre> <p>But you probably shouldn't. No one will know what it means.</p>
2
2009-02-11T00:17:55Z
[ "python", "list", "tuples", "vector" ]
Subtracting 2 lists in Python
534,855
<p>Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like</p> <pre><code>[2,2,2] - [1,1,1] = [1,1,1] </code></pre> <p>Should I use tuples?</p> <p>If none of them defines these operands on these types, can I define it instead?</p> <p>If not, should I create a new vector3 class?</p>
33
2009-02-10T23:57:22Z
534,914
<p>Here's an alternative to list comprehensions. Map iterates through the list(s) (the latter arguments), doing so simulataneously, and passes their elements as arguments to the function (the first arg). It returns the resulting list.</p> <pre><code>map(operator.sub, a, b) </code></pre> <p>This code because has less syntax (which is more aesthetic for me), and apparently it's 40% faster for lists of length 5 (see bobince's comment). Still, either solution will work.</p>
49
2009-02-11T00:19:03Z
[ "python", "list", "tuples", "vector" ]
Subtracting 2 lists in Python
534,855
<p>Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like</p> <pre><code>[2,2,2] - [1,1,1] = [1,1,1] </code></pre> <p>Should I use tuples?</p> <p>If none of them defines these operands on these types, can I define it instead?</p> <p>If not, should I create a new vector3 class?</p>
33
2009-02-10T23:57:22Z
535,220
<p>A slightly different Vector class.</p> <pre><code>class Vector( object ): def __init__(self, *data): self.data = data def __repr__(self): return repr(self.data) def __add__(self, other): return tuple( (a+b for a,b in zip(self.data, other.data) ) ) def __sub__(self, other): return tuple( (a-b for a,b in zip(self.data, other.data) ) ) Vector(1, 2, 3) - Vector(1, 1, 1) </code></pre>
3
2009-02-11T02:44:23Z
[ "python", "list", "tuples", "vector" ]
Subtracting 2 lists in Python
534,855
<p>Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like</p> <pre><code>[2,2,2] - [1,1,1] = [1,1,1] </code></pre> <p>Should I use tuples?</p> <p>If none of them defines these operands on these types, can I define it instead?</p> <p>If not, should I create a new vector3 class?</p>
33
2009-02-10T23:57:22Z
535,830
<p>I'd have to recommend <a href="http://numpy.scipy.org/">NumPy</a> as well</p> <p>Not only is it faster for doing vector math, but it also has a ton of convenience functions.</p> <p>If you want something even faster for 1d vectors, try <a href="http://www.excamera.com/articles/25/vop.html">vop</a></p> <p>It's similar to MatLab, but free and stuff. Here's an example of what you'd do</p> <pre><code>from numpy import matrix a = matrix((2,2,2)) b = matrix((1,1,1)) ret = a - b print ret &gt;&gt; [[1 1 1]] </code></pre> <p>Boom.</p>
5
2009-02-11T07:59:28Z
[ "python", "list", "tuples", "vector" ]
Subtracting 2 lists in Python
534,855
<p>Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like</p> <pre><code>[2,2,2] - [1,1,1] = [1,1,1] </code></pre> <p>Should I use tuples?</p> <p>If none of them defines these operands on these types, can I define it instead?</p> <p>If not, should I create a new vector3 class?</p>
33
2009-02-10T23:57:22Z
1,543,384
<p>Try this:</p> <pre><code>list(array([1,2,3])-1) </code></pre>
-1
2009-10-09T12:03:44Z
[ "python", "list", "tuples", "vector" ]
Subtracting 2 lists in Python
534,855
<p>Right now I have vector3 values represented as lists. is there a way to subtract 2 of these like vector3 values, like</p> <pre><code>[2,2,2] - [1,1,1] = [1,1,1] </code></pre> <p>Should I use tuples?</p> <p>If none of them defines these operands on these types, can I define it instead?</p> <p>If not, should I create a new vector3 class?</p>
33
2009-02-10T23:57:22Z
23,389,512
<p>If you want the result in list :</p> <pre><code>list(numpy.array(list1)-numpy.array(list2)) </code></pre> <p>if not remove list.</p>
0
2014-04-30T13:31:36Z
[ "python", "list", "tuples", "vector" ]
practice with threads in python
535,331
<p>I know that Python has a <a href="http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock" rel="nofollow">global lock</a> and i've read Glyph's explaination of <a href="http://stackoverflow.com/questions/203912/does-python-support-multiprocessor-multicore-programming/204150#204150">python multithreading</a>. But I still want to try it out. What I decided to do as an easy (conceptually) task was to do horizontal and vertical edge detection on a picture. </p> <p>Here's what's happening (pseudocode):</p> <pre><code>for pixels in picture: apply sobel operator horizontal for pixels in picture: apply sobel operator vertical </code></pre> <p><a href="http://en.wikipedia.org/wiki/Sobel_operator" rel="nofollow">info on sobel operator</a>.</p> <p>These two loops can run completely independent of each other, and so would be prime candidates for multithreading. (running these two loops on any significantly large picture can take 10+ seconds). However, when I have tried to use the <code>threading</code> module in python, it takes twice as long because of the global lock. My question is should I abandon all hope of doing this in two threads in python and try in another language? If i can forge ahead, what module(s) should I use? If not, what language should I experiment in?</p>
2
2009-02-11T03:42:33Z
535,347
<p>If the sobel operator is CPU-bound, then you won't get any benefit from multiple threads because python does not take advantage of multiple cores.</p> <p>Conceivably you could spin off multiple processes, though I'm not sure if that would be practical for working on a single image.</p> <p>10 seconds doesn't seem like a lot of time to waste. If you're concerned about time because you'll be processing many images, then it might be easier to run multiple processes and have each process deal with a separate subset of the images.</p>
3
2009-02-11T03:50:21Z
[ "python", "multithreading", "image-manipulation" ]
practice with threads in python
535,331
<p>I know that Python has a <a href="http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock" rel="nofollow">global lock</a> and i've read Glyph's explaination of <a href="http://stackoverflow.com/questions/203912/does-python-support-multiprocessor-multicore-programming/204150#204150">python multithreading</a>. But I still want to try it out. What I decided to do as an easy (conceptually) task was to do horizontal and vertical edge detection on a picture. </p> <p>Here's what's happening (pseudocode):</p> <pre><code>for pixels in picture: apply sobel operator horizontal for pixels in picture: apply sobel operator vertical </code></pre> <p><a href="http://en.wikipedia.org/wiki/Sobel_operator" rel="nofollow">info on sobel operator</a>.</p> <p>These two loops can run completely independent of each other, and so would be prime candidates for multithreading. (running these two loops on any significantly large picture can take 10+ seconds). However, when I have tried to use the <code>threading</code> module in python, it takes twice as long because of the global lock. My question is should I abandon all hope of doing this in two threads in python and try in another language? If i can forge ahead, what module(s) should I use? If not, what language should I experiment in?</p>
2
2009-02-11T03:42:33Z
535,399
<p>Python 2.6 now includes the <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow"><strong>mulitprocessing</strong></a> module (formerly <a href="http://pyprocessing.berlios.de/doc/index.html" rel="nofollow"><strong>processing</strong></a> module on older versions of Python). </p> <p>It has essentially the same interface as the <strong>threading</strong> module, but launches the execution into separate processes rather than threads. This allows Python to take advantage of multiple cores/CPUs and scales well for CPU-intensive tasks compared to the threading module approach.</p>
7
2009-02-11T04:10:34Z
[ "python", "multithreading", "image-manipulation" ]
practice with threads in python
535,331
<p>I know that Python has a <a href="http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock" rel="nofollow">global lock</a> and i've read Glyph's explaination of <a href="http://stackoverflow.com/questions/203912/does-python-support-multiprocessor-multicore-programming/204150#204150">python multithreading</a>. But I still want to try it out. What I decided to do as an easy (conceptually) task was to do horizontal and vertical edge detection on a picture. </p> <p>Here's what's happening (pseudocode):</p> <pre><code>for pixels in picture: apply sobel operator horizontal for pixels in picture: apply sobel operator vertical </code></pre> <p><a href="http://en.wikipedia.org/wiki/Sobel_operator" rel="nofollow">info on sobel operator</a>.</p> <p>These two loops can run completely independent of each other, and so would be prime candidates for multithreading. (running these two loops on any significantly large picture can take 10+ seconds). However, when I have tried to use the <code>threading</code> module in python, it takes twice as long because of the global lock. My question is should I abandon all hope of doing this in two threads in python and try in another language? If i can forge ahead, what module(s) should I use? If not, what language should I experiment in?</p>
2
2009-02-11T03:42:33Z
535,431
<p>Bulk matrix operations like the Sobel operator will definitely realize significant speed gains by (correctly) using <a href="http://www.mathworks.com/company/newsletters/news_notes/clevescorner/winter2000.cleve.html" rel="nofollow">Matlab/Octave</a>. It is possible that <a href="http://www.scipy.org/NumPy_for_Matlab_Users" rel="nofollow">NumPy</a> may provide similar speedups for matrix/array ops.</p>
0
2009-02-11T04:24:28Z
[ "python", "multithreading", "image-manipulation" ]
practice with threads in python
535,331
<p>I know that Python has a <a href="http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock" rel="nofollow">global lock</a> and i've read Glyph's explaination of <a href="http://stackoverflow.com/questions/203912/does-python-support-multiprocessor-multicore-programming/204150#204150">python multithreading</a>. But I still want to try it out. What I decided to do as an easy (conceptually) task was to do horizontal and vertical edge detection on a picture. </p> <p>Here's what's happening (pseudocode):</p> <pre><code>for pixels in picture: apply sobel operator horizontal for pixels in picture: apply sobel operator vertical </code></pre> <p><a href="http://en.wikipedia.org/wiki/Sobel_operator" rel="nofollow">info on sobel operator</a>.</p> <p>These two loops can run completely independent of each other, and so would be prime candidates for multithreading. (running these two loops on any significantly large picture can take 10+ seconds). However, when I have tried to use the <code>threading</code> module in python, it takes twice as long because of the global lock. My question is should I abandon all hope of doing this in two threads in python and try in another language? If i can forge ahead, what module(s) should I use? If not, what language should I experiment in?</p>
2
2009-02-11T03:42:33Z
535,819
<p>I recommend using NumPy as well. Not only will it probably be faster, but if you use threads with it, there won't be a global lock.</p> <p>I'll also suggest using multiprocessing as Jay suggests.</p> <p>Anyways, if you really want to practice threading, I'd suggest playing around with PThreads in C. PThreads are insanely simple to use for basic cases and used all over the place.</p>
2
2009-02-11T07:50:58Z
[ "python", "multithreading", "image-manipulation" ]
practice with threads in python
535,331
<p>I know that Python has a <a href="http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock" rel="nofollow">global lock</a> and i've read Glyph's explaination of <a href="http://stackoverflow.com/questions/203912/does-python-support-multiprocessor-multicore-programming/204150#204150">python multithreading</a>. But I still want to try it out. What I decided to do as an easy (conceptually) task was to do horizontal and vertical edge detection on a picture. </p> <p>Here's what's happening (pseudocode):</p> <pre><code>for pixels in picture: apply sobel operator horizontal for pixels in picture: apply sobel operator vertical </code></pre> <p><a href="http://en.wikipedia.org/wiki/Sobel_operator" rel="nofollow">info on sobel operator</a>.</p> <p>These two loops can run completely independent of each other, and so would be prime candidates for multithreading. (running these two loops on any significantly large picture can take 10+ seconds). However, when I have tried to use the <code>threading</code> module in python, it takes twice as long because of the global lock. My question is should I abandon all hope of doing this in two threads in python and try in another language? If i can forge ahead, what module(s) should I use? If not, what language should I experiment in?</p>
2
2009-02-11T03:42:33Z
545,887
<p>Python mutliprocessing is the right choice if you want to practice parallel programming with Python. If you don't have Python 2.6 (which you don't if you're using Ubuntu for example), you can use the <a href="http://code.google.com/p/python-multiprocessing/" rel="nofollow">Google code backported</a> version of multiprocessing. It is part of PyPI, which means you can easily install it using EasyInstall (which is part of the python-setuptools package in Ubuntu).</p>
0
2009-02-13T13:18:03Z
[ "python", "multithreading", "image-manipulation" ]
Python libraries to construct classes from a relational database? (ORM in reverse)
535,426
<p>Are there any Python object-relational mapping libraries that, given a database schema, can generate a set of Python classes? I know that the major libraries such as <a href="http://www.sqlobject.org/" rel="nofollow">SQLObject</a>, <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>, and <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>'s internal SQL ORM library do a very good job of creating a DB schema given a set of classes, but I'm looking for a library that works in reverse.</p> <p>There is a <a href="http://stackoverflow.com/questions/362929/is-there-a-perl-orm-with-database-reverse-engineering">related question for Perl libraries</a> on Stack Overflow.</p>
3
2009-02-11T04:22:19Z
535,437
<p><a href="http://code.google.com/p/sqlautocode/" rel="nofollow">SQLAlchemy extension to create a python code model from an existing database</a></p>
11
2009-02-11T04:27:42Z
[ "python", "database", "orm" ]
Python libraries to construct classes from a relational database? (ORM in reverse)
535,426
<p>Are there any Python object-relational mapping libraries that, given a database schema, can generate a set of Python classes? I know that the major libraries such as <a href="http://www.sqlobject.org/" rel="nofollow">SQLObject</a>, <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>, and <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>'s internal SQL ORM library do a very good job of creating a DB schema given a set of classes, but I'm looking for a library that works in reverse.</p> <p>There is a <a href="http://stackoverflow.com/questions/362929/is-there-a-perl-orm-with-database-reverse-engineering">related question for Perl libraries</a> on Stack Overflow.</p>
3
2009-02-11T04:22:19Z
535,451
<p><a href="http://www.aminus.net/geniusql" rel="nofollow">Geniusql</a> (and <a href="http://www.aminus.net/dejavu" rel="nofollow">Dejavu</a>, its big federated brother) can do that quite well. See "<a href="http://www.aminus.net/geniusql/chrome/common/doc/trunk/modeling.html" rel="nofollow">Automatic Table Classes</a>" for the former and "<a href="http://www.aminus.net/dejavu/chrome/common/doc/trunk/modeling.html#autoclass" rel="nofollow">Automatic Unit Classes</a>" for the latter.</p>
3
2009-02-11T04:40:16Z
[ "python", "database", "orm" ]
Python libraries to construct classes from a relational database? (ORM in reverse)
535,426
<p>Are there any Python object-relational mapping libraries that, given a database schema, can generate a set of Python classes? I know that the major libraries such as <a href="http://www.sqlobject.org/" rel="nofollow">SQLObject</a>, <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>, and <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>'s internal SQL ORM library do a very good job of creating a DB schema given a set of classes, but I'm looking for a library that works in reverse.</p> <p>There is a <a href="http://stackoverflow.com/questions/362929/is-there-a-perl-orm-with-database-reverse-engineering">related question for Perl libraries</a> on Stack Overflow.</p>
3
2009-02-11T04:22:19Z
535,498
<p>Django had an <a href="http://docs.djangoproject.com/en/dev/ref/django-admin/#inspectdb" rel="nofollow">inspectdb</a> command that creates models.py files out of your database.</p>
6
2009-02-11T05:07:00Z
[ "python", "database", "orm" ]
Python libraries to construct classes from a relational database? (ORM in reverse)
535,426
<p>Are there any Python object-relational mapping libraries that, given a database schema, can generate a set of Python classes? I know that the major libraries such as <a href="http://www.sqlobject.org/" rel="nofollow">SQLObject</a>, <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a>, and <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>'s internal SQL ORM library do a very good job of creating a DB schema given a set of classes, but I'm looking for a library that works in reverse.</p> <p>There is a <a href="http://stackoverflow.com/questions/362929/is-there-a-perl-orm-with-database-reverse-engineering">related question for Perl libraries</a> on Stack Overflow.</p>
3
2009-02-11T04:22:19Z
535,536
<p>SQLAlchemy can actually do what you want. You can either define the mappings yourself manually using the mapper facility, or auto-generate them using <a href="http://www.sqlalchemy.org/docs/05/metadata.html#reflecting-tables">reflection</a>.</p> <p>It's not absolutely necessary to build the database using the metadata facility, you can always use an existing one instead.</p>
5
2009-02-11T05:31:21Z
[ "python", "database", "orm" ]
How can I create a tag in Jinja that contains values from later in the template?
535,743
<p>I'm using Jinja2, and I'm trying to create a couple tags that work together, such that if I have a template that looks something like this:</p> <pre><code>{{ my_summary() }} ... arbitrary HTML ... {{ my_values('Tom', 'Dick', 'Harry') }} ... arbitrary HTML ... {{ my_values('Fred', 'Barney') }} </code></pre> <p>I'd end up with the following:</p> <pre><code>This page includes information about &lt;b&gt;Tom&lt;/b&gt;, &lt;b&gt;Dick&lt;/b&gt;, &lt;b&gt;Harry&lt;/b&gt;, &lt;b&gt;Fred&lt;/b&gt;, and &lt;b&gt;Barney&lt;/b&gt;. ... arbitrary HTML ... &lt;h1&gt;Tom, Dick, and Harry&lt;/h1&gt; ... arbitrary HTML ... &lt;h1&gt;Fred and Barney&lt;/h1&gt; </code></pre> <p>In other words, the my_summary() at the start of the page includes information provided later on in the page. It should be smart enough to take into account expressions which occur in <code>include</code> and <code>import</code> statements, as well.</p> <p>What's the best way to do this?</p>
3
2009-02-11T07:12:34Z
536,315
<p>Disclaimer: I do not know Jinja.</p> <p>My guess is that you cannot (easily) accomplish this.</p> <p>I would suggest the following alternative:</p> <ul> <li>Pass the Tom, Dick, etc. values as variables to the template from the outside.</li> <li>Let your custom tags take the values as arguments.</li> <li>I do not know what "the outside" would be in your case. If the template is used in a web app framework, "the outside" is probably a controller method.</li> <li>For instance:</li> </ul> <p>Template:</p> <pre> {{ my_summary(list1 + list2) }} ... arbitrary HTML ... {{ my_values(list1) }} ... arbitrary HTML ... {{ my_values(list2) }} </pre> <p>Controller:</p> <pre> def a_controller_method(request): return render_template('templatefilename', { 'list1': ['Dick', 'Tom', 'Harry'], 'list2': ['Fred', 'Barney']}) </pre> <ul> <li>If passing the values from the outside is not feasible, I suggest you define them at the top of your template, like this:</li> </ul> <pre> {% set list1 = ['Dick', ...] %} {% set list2 = ['Fred', ...] %} {{ my_summary(list1 + list2) }} ... arbitrary HTML ... {{ my_values(list1) }} ... arbitrary HTML ... {{ my_values(list2) }} </pre>
4
2009-02-11T10:55:22Z
[ "python", "templating", "jinja2" ]
python sleep == IDE lock up
535,973
<p>When my script sleeps for 50sec my IDE locks up which is very annoying. I cant switch tabs, look through my source, type code, etc. It happens in pylde and pyscripter, i havent tried other IDEs. What can i do to fix this? i'm actually doing </p> <pre><code>for i in range(0, timeInSeconds): time.sleep(1) </code></pre> <p>hoping the IDE will update once per second but it doesnt look that way. What can i do to fix this?</p>
1
2009-02-11T08:57:38Z
536,024
<p>I'm assuming you are running your code from within the IDE?</p> <p>Your IDE is probably blocking while running your code. Look for a setting of some sort which might control that behaviour, otherwise I think your only choice would be to change IDE. (Or, run your code from outside the IDE)</p>
2
2009-02-11T09:10:55Z
[ "python", "ide", "lockup" ]
python sleep == IDE lock up
535,973
<p>When my script sleeps for 50sec my IDE locks up which is very annoying. I cant switch tabs, look through my source, type code, etc. It happens in pylde and pyscripter, i havent tried other IDEs. What can i do to fix this? i'm actually doing </p> <pre><code>for i in range(0, timeInSeconds): time.sleep(1) </code></pre> <p>hoping the IDE will update once per second but it doesnt look that way. What can i do to fix this?</p>
1
2009-02-11T08:57:38Z
536,041
<p>Can you configure to run your script externally? I don't know about the specific IDEs, but I would try to spawn a different process for the debugged script and not run them under the IDE. If that doesn't help, then it is a problem of the IDEs.</p>
0
2009-02-11T09:16:57Z
[ "python", "ide", "lockup" ]
python sleep == IDE lock up
535,973
<p>When my script sleeps for 50sec my IDE locks up which is very annoying. I cant switch tabs, look through my source, type code, etc. It happens in pylde and pyscripter, i havent tried other IDEs. What can i do to fix this? i'm actually doing </p> <pre><code>for i in range(0, timeInSeconds): time.sleep(1) </code></pre> <p>hoping the IDE will update once per second but it doesnt look that way. What can i do to fix this?</p>
1
2009-02-11T08:57:38Z
536,054
<p>The problem is your IDE not python. I don't use sleep that often, I've just tried it on the <a href="http://eric-ide.python-projects.org/" rel="nofollow">Eric IDE</a> and you can <em>use</em> your IDE while your code is running, and sleeping. If can't set your IDE to do so and you need it then consider to change IDE or to run your code from console.</p>
0
2009-02-11T09:19:59Z
[ "python", "ide", "lockup" ]
python sleep == IDE lock up
535,973
<p>When my script sleeps for 50sec my IDE locks up which is very annoying. I cant switch tabs, look through my source, type code, etc. It happens in pylde and pyscripter, i havent tried other IDEs. What can i do to fix this? i'm actually doing </p> <pre><code>for i in range(0, timeInSeconds): time.sleep(1) </code></pre> <p>hoping the IDE will update once per second but it doesnt look that way. What can i do to fix this?</p>
1
2009-02-11T08:57:38Z
536,924
<p>Personally, I think you should never ever ever execute code in the same loop as your IDE. Since most IDEs run a GUI mainloop, blocking this will cause complete freeze of the user interface. It is just asking for trouble, and I would take out bug reports against both those IDEs.</p>
0
2009-02-11T14:05:59Z
[ "python", "ide", "lockup" ]
python sleep == IDE lock up
535,973
<p>When my script sleeps for 50sec my IDE locks up which is very annoying. I cant switch tabs, look through my source, type code, etc. It happens in pylde and pyscripter, i havent tried other IDEs. What can i do to fix this? i'm actually doing </p> <pre><code>for i in range(0, timeInSeconds): time.sleep(1) </code></pre> <p>hoping the IDE will update once per second but it doesnt look that way. What can i do to fix this?</p>
1
2009-02-11T08:57:38Z
544,395
<p>I suspect the problem the IDE is sitting in a loop waiting for the script to finish. </p> <p>That in itself is not a problem, provided any user generated messages are still processed while the IDE is in this loop. </p> <p>But what I suspect is going wrong in this case is the IDE is just running the loop without processing and messages and hence the user interface appears to be locked.</p> <p>The IDE would need to be changed to either process GUI messages while in the loop or alternatively it needs to create a thread to run the the script. The thread would then run in the background and the GUI would remain responsive.</p> <p>For example the <a href="http://www.zeusedit.com" rel="nofollow">Zeus for Windows</a> IDE uses the background thread approach and it does not have this problem.</p>
0
2009-02-13T01:38:46Z
[ "python", "ide", "lockup" ]