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 |
|---|---|---|---|---|---|---|---|---|---|
SQLite in Python 2.2.3
| 737,511
|
<p>I've written a web-app in python using SQLite and it runs fine on my server at home (with apache and python 2.5.2). I'm now trying to upload it to my web host and there servers use python 2.2.3 without SQLite.<br/>
Anyone know of a way to use SQLite in python 2.2.3 e.g. a module that I can upload and import? I've tried butchering the module from newer versions of python, but they don't seem to be compatible.<br/>
Thanks,<br/>
Mike</p>
| 1
|
2009-04-10T12:40:39Z
| 739,257
|
<p>If you have shell access to your web server, you can probably build you're own version of Python and SQLite. This will let you use the latest version. Download the source code, then when you configure it, do something like "./configure --prefix=$HOME/packages".</p>
<p>Next, fiddle around with your .profile, or .bashrc or whatever it is to make sure $HOME/packages/bin comes first in your path. This will cause your private Python to override the one installed by your web server.</p>
<p>This page might give you a little more information for how to do this on a server like Dreamhost: <a href="http://wiki.dreamhost.com/Python" rel="nofollow">http://wiki.dreamhost.com/Python</a></p>
| 0
|
2009-04-11T00:40:31Z
|
[
"python",
"sql",
"linux",
"sqlite",
"hosting"
] |
SQLite in Python 2.2.3
| 737,511
|
<p>I've written a web-app in python using SQLite and it runs fine on my server at home (with apache and python 2.5.2). I'm now trying to upload it to my web host and there servers use python 2.2.3 without SQLite.<br/>
Anyone know of a way to use SQLite in python 2.2.3 e.g. a module that I can upload and import? I've tried butchering the module from newer versions of python, but they don't seem to be compatible.<br/>
Thanks,<br/>
Mike</p>
| 1
|
2009-04-10T12:40:39Z
| 4,066,757
|
<p>In case anyone comes across this question, the reason why neither pysqlite nor APSW are available for Python 2.2 is because Python 2.3 added the simplified GIL API. Prior to Python 2.3 it required a lot of code to keep track of the GIL. (The GIL is the lock used by Python to ensure correct behaviour while multi-threading.)</p>
<p>Doing a backport to 2.2 would require ripping out all the threading code. Trying to make it also be thread safe under 2.2 would be a nightmare. There was a reason they introduced the simplified GIL API!</p>
<p>I am still astonished at just how popular older Python versions are. APSW for Python 2.3 is still regularly downloaded.</p>
| 0
|
2010-11-01T05:06:17Z
|
[
"python",
"sql",
"linux",
"sqlite",
"hosting"
] |
Returning default members when accessing to objects in python
| 737,512
|
<p>I'm writing an "envirorment" where each variable is composed by a value and a description:</p>
<pre><code>class my_var:
def __init__(self, value, description):
self.value = value
self.description = description
</code></pre>
<p>Variables are created and put inside a dictionary:</p>
<pre><code>my_dict["foo"] = my_var(0.5, "A foo var")
</code></pre>
<p>This is cool but 99% of operations with variable are with the "value" member. So I have to write like this:</p>
<pre><code>print my_dict["foo"].value + 15 # Prints 15.5
</code></pre>
<p>or</p>
<pre><code>my_dict["foo"].value = 17
</code></pre>
<p>I'd like that all operation on the object my_dict["foo"] could default to the "value" member. In other words I'd like to write:</p>
<pre><code>print my_dict["foo"] + 15 # Prints 5.5
</code></pre>
<p>and stuff like that.</p>
<p>The only way I found is to reimplement <strong>all</strong> underscore-members (eq, add, str, etc) but I feel like this is the wrong way somehow. Is there a magic method I could use?</p>
<p>A workaround would be to have more dictionaries, like this:</p>
<pre><code>my_dict_value["foo"] = 0.5
my_dict_description["foo"] = "A foo var"
</code></pre>
<p>but I don't like this solution. Do you have any suggestions?</p>
| 1
|
2009-04-10T12:41:35Z
| 737,549
|
<p>I think the fact that you have to do so much work to make a fancy shortcut is an indication that you're going against the grain. What you're doing violates LSP; it's counter-intuitive. </p>
<pre><code>my_dict[k] = v;
print my_dict[k] == v # should be True
</code></pre>
<p>Even two separate dicts would be preferable to changing the meaning of dict.</p>
| 1
|
2009-04-10T12:58:38Z
|
[
"python",
"dynamic-data"
] |
Returning default members when accessing to objects in python
| 737,512
|
<p>I'm writing an "envirorment" where each variable is composed by a value and a description:</p>
<pre><code>class my_var:
def __init__(self, value, description):
self.value = value
self.description = description
</code></pre>
<p>Variables are created and put inside a dictionary:</p>
<pre><code>my_dict["foo"] = my_var(0.5, "A foo var")
</code></pre>
<p>This is cool but 99% of operations with variable are with the "value" member. So I have to write like this:</p>
<pre><code>print my_dict["foo"].value + 15 # Prints 15.5
</code></pre>
<p>or</p>
<pre><code>my_dict["foo"].value = 17
</code></pre>
<p>I'd like that all operation on the object my_dict["foo"] could default to the "value" member. In other words I'd like to write:</p>
<pre><code>print my_dict["foo"] + 15 # Prints 5.5
</code></pre>
<p>and stuff like that.</p>
<p>The only way I found is to reimplement <strong>all</strong> underscore-members (eq, add, str, etc) but I feel like this is the wrong way somehow. Is there a magic method I could use?</p>
<p>A workaround would be to have more dictionaries, like this:</p>
<pre><code>my_dict_value["foo"] = 0.5
my_dict_description["foo"] = "A foo var"
</code></pre>
<p>but I don't like this solution. Do you have any suggestions?</p>
| 1
|
2009-04-10T12:41:35Z
| 737,551
|
<p>Two general notes.</p>
<ol>
<li><p>Please use Upper Case for Class Names.</p></li>
<li><p>Please (unless using Python 3.0) subclass object. <code>class My_Var(object):</code>, for example.</p></li>
</ol>
<p>Now to your question.</p>
<p>Let's say you do</p>
<pre><code>x= My_Var(0.5, "A foo var")
</code></pre>
<p>How does python distinguish between <code>x</code>, the composite object and x's value (<code>x.value</code>)?</p>
<p>Do you want the following behavior?</p>
<ul>
<li><p>Sometimes <code>x</code> means the whole composite object. </p></li>
<li><p>Sometimes <code>x</code> means <code>x.value</code>.</p></li>
</ul>
<p>How do you distinguish between the two? How will you tell Python which you mean?</p>
| 3
|
2009-04-10T12:59:31Z
|
[
"python",
"dynamic-data"
] |
Returning default members when accessing to objects in python
| 737,512
|
<p>I'm writing an "envirorment" where each variable is composed by a value and a description:</p>
<pre><code>class my_var:
def __init__(self, value, description):
self.value = value
self.description = description
</code></pre>
<p>Variables are created and put inside a dictionary:</p>
<pre><code>my_dict["foo"] = my_var(0.5, "A foo var")
</code></pre>
<p>This is cool but 99% of operations with variable are with the "value" member. So I have to write like this:</p>
<pre><code>print my_dict["foo"].value + 15 # Prints 15.5
</code></pre>
<p>or</p>
<pre><code>my_dict["foo"].value = 17
</code></pre>
<p>I'd like that all operation on the object my_dict["foo"] could default to the "value" member. In other words I'd like to write:</p>
<pre><code>print my_dict["foo"] + 15 # Prints 5.5
</code></pre>
<p>and stuff like that.</p>
<p>The only way I found is to reimplement <strong>all</strong> underscore-members (eq, add, str, etc) but I feel like this is the wrong way somehow. Is there a magic method I could use?</p>
<p>A workaround would be to have more dictionaries, like this:</p>
<pre><code>my_dict_value["foo"] = 0.5
my_dict_description["foo"] = "A foo var"
</code></pre>
<p>but I don't like this solution. Do you have any suggestions?</p>
| 1
|
2009-04-10T12:41:35Z
| 737,559
|
<p>You could create an object that mostly acts like "value" but has an additional attribute "description, by implementing the operators in section "Emulating numeric types" of <a href="http://docs.python.org/reference/datamodel.html" rel="nofollow">http://docs.python.org/reference/datamodel.html</a></p>
<pre><code>class Fooness(object):
def __init__(self,val, description):
self._val = val
self.description = description
def __add__(self,other):
return self._val + other
def __sub__(self,other):
return self._val - other
def __mul__(self,other):
return self._val * other
# etc
def __str__(self):
return str(self._val)
f = Fooness(10,"my f'd up fooness")
b = f + 10
print 'b=',b
d = f - 7
print 'd=',d
print 'f.description=',f.description
</code></pre>
<p>Produces:</p>
<pre><code>b= 20
d= 3
f.description= my f'd up fooness
</code></pre>
| 2
|
2009-04-10T13:03:45Z
|
[
"python",
"dynamic-data"
] |
Returning default members when accessing to objects in python
| 737,512
|
<p>I'm writing an "envirorment" where each variable is composed by a value and a description:</p>
<pre><code>class my_var:
def __init__(self, value, description):
self.value = value
self.description = description
</code></pre>
<p>Variables are created and put inside a dictionary:</p>
<pre><code>my_dict["foo"] = my_var(0.5, "A foo var")
</code></pre>
<p>This is cool but 99% of operations with variable are with the "value" member. So I have to write like this:</p>
<pre><code>print my_dict["foo"].value + 15 # Prints 15.5
</code></pre>
<p>or</p>
<pre><code>my_dict["foo"].value = 17
</code></pre>
<p>I'd like that all operation on the object my_dict["foo"] could default to the "value" member. In other words I'd like to write:</p>
<pre><code>print my_dict["foo"] + 15 # Prints 5.5
</code></pre>
<p>and stuff like that.</p>
<p>The only way I found is to reimplement <strong>all</strong> underscore-members (eq, add, str, etc) but I feel like this is the wrong way somehow. Is there a magic method I could use?</p>
<p>A workaround would be to have more dictionaries, like this:</p>
<pre><code>my_dict_value["foo"] = 0.5
my_dict_description["foo"] = "A foo var"
</code></pre>
<p>but I don't like this solution. Do you have any suggestions?</p>
| 1
|
2009-04-10T12:41:35Z
| 737,564
|
<p>I would personally just use two dictionaries, one for values and one for descriptions. Your desire for magic behavior is not very Pythonic.</p>
<p>With that being said, you could implement your own dict class:</p>
<pre><code>class DescDict(dict):
def __init__(self, *args, **kwargs):
self.descs = {}
dict.__init__(self)
def __getitem__(self, name):
return dict.__getitem__(self, name)
def __setitem__(self, name, tup):
value, description = tup
self.descs[name] = description
dict.__setitem__(self, name, value)
def get_desc(self, name):
return self.descs[name]
</code></pre>
<p>You'd use this class as follows:</p>
<pre><code>my_dict = DescDict()
my_dict["foo"] = (0.5, "A foo var") # just use a tuple if you only have 2 vals
print my_dict["foo"] + 15 # prints 15.5
print my_dict.get_desc("foo") # prints 'A foo var'
</code></pre>
<p>If you decide to go the magic behavior route, then this should be a good starting point.</p>
| 2
|
2009-04-10T13:06:11Z
|
[
"python",
"dynamic-data"
] |
Followup: Multiprocessing or Multithreading for Python simulation software
| 737,826
|
<p>this is a follow up to <a href="http://stackoverflow.com/questions/731993/multiprocessing-or-multithreading">this</a>. (You don't have to read all the answers, just the question)</p>
<p>People explained to me the difference between processes and threads. On the one hand, I wanted processes so I could fully exploit all core of the CPU, on the other hand, passing information between processes was less than ideal, and I didn't want to have two copies of the huge object I was dealing with.</p>
<p>So I've been thinking about a way to do this, combining processes and threads; tell me if this makes sense. The main process in my program is the GUI process. I will have it spawn a "rendering-manager" thread. The rendering-manager thread will be responsible for rendering the simulation, however, it will not render them by itself, but spawn other processes to do the work for it.</p>
<p>These are the goals:</p>
<ol>
<li>Rendering should take advantage of all the cores available.</li>
<li>The GUI should never become sluggish.</li>
</ol>
<p>The reason I want the rendering-manager to be a thread is because it has to share a lot of information with the GUI: Namely, the simulation-timeline.</p>
<p>So do you think this is a good design? Do you have any suggestions for improvement?</p>
<p><strong>Update:</strong></p>
<p>Sorry for my confusing use of the word "render". By render I mean calculate the simulation, not render it on screen.</p>
| 0
|
2009-04-10T14:41:10Z
| 738,032
|
<blockquote>
<p>The main process in my program is the GUI process. I will have it spawn a "rendering-manager" thread. The rendering-manager thread will be responsible for rendering the simulation, however, it will not render them by itself, but spawn other processes to do the work for it.</p>
</blockquote>
<p>I'm no expert on graphics technologies, but this sounds a lot like what GPUs are intended for. Perhaps <a href="http://www.pygame.org/news.html" rel="nofollow">pygame</a> is more what you're looking for?</p>
| 0
|
2009-04-10T15:41:59Z
|
[
"python",
"multithreading",
"multicore",
"simulation",
"multiprocessing"
] |
Followup: Multiprocessing or Multithreading for Python simulation software
| 737,826
|
<p>this is a follow up to <a href="http://stackoverflow.com/questions/731993/multiprocessing-or-multithreading">this</a>. (You don't have to read all the answers, just the question)</p>
<p>People explained to me the difference between processes and threads. On the one hand, I wanted processes so I could fully exploit all core of the CPU, on the other hand, passing information between processes was less than ideal, and I didn't want to have two copies of the huge object I was dealing with.</p>
<p>So I've been thinking about a way to do this, combining processes and threads; tell me if this makes sense. The main process in my program is the GUI process. I will have it spawn a "rendering-manager" thread. The rendering-manager thread will be responsible for rendering the simulation, however, it will not render them by itself, but spawn other processes to do the work for it.</p>
<p>These are the goals:</p>
<ol>
<li>Rendering should take advantage of all the cores available.</li>
<li>The GUI should never become sluggish.</li>
</ol>
<p>The reason I want the rendering-manager to be a thread is because it has to share a lot of information with the GUI: Namely, the simulation-timeline.</p>
<p>So do you think this is a good design? Do you have any suggestions for improvement?</p>
<p><strong>Update:</strong></p>
<p>Sorry for my confusing use of the word "render". By render I mean calculate the simulation, not render it on screen.</p>
| 0
|
2009-04-10T14:41:10Z
| 738,960
|
<p>Before using processes, make sure that:</p>
<ul>
<li>Your algorithm can be parallelized between all the processors.</li>
<li>You need this parallelism.</li>
</ul>
<p>In my opinion a good rule of thumb is:</p>
<ol>
<li>Make it work.</li>
<li>Make it right.</li>
<li>Make it fast.</li>
</ol>
<p>So I'd suggest to âsimplyâ use threads first. Maybe you will realize that even with one thread computing the simulation it's fast enough.</p>
| 2
|
2009-04-10T21:40:26Z
|
[
"python",
"multithreading",
"multicore",
"simulation",
"multiprocessing"
] |
Scratch disks in Python?
| 737,947
|
<p>I understood that in certain Windows XP programs, like Photoshop, there is something called "scratch disks". What I understood that this means, and please correct me if I'm wrong, is that Photoshop manages its own virtual memory on the hard-drive, instead of letting Windows manage it. I understood that the reason for this is some limitation by Windows XP on how much total memory a process can take, regardless of HD space. I think it's around 3 GB. Did I get it right so far?</p>
<p>I am making an application in Python for running simulations. It will take a lot of memory, and will run on Windows XP. Is it possible for it to use scratch disks? How?</p>
| 2
|
2009-04-10T15:11:33Z
| 737,963
|
<p>Scratch disks will benefit your application in the case that it works with very big files, </p>
<p>Is that the case? </p>
<p>If not, then i don't think you may find something that will benefit your application in scratch disks.</p>
| 1
|
2009-04-10T15:18:21Z
|
[
"python",
"windows",
"memory-management"
] |
Scratch disks in Python?
| 737,947
|
<p>I understood that in certain Windows XP programs, like Photoshop, there is something called "scratch disks". What I understood that this means, and please correct me if I'm wrong, is that Photoshop manages its own virtual memory on the hard-drive, instead of letting Windows manage it. I understood that the reason for this is some limitation by Windows XP on how much total memory a process can take, regardless of HD space. I think it's around 3 GB. Did I get it right so far?</p>
<p>I am making an application in Python for running simulations. It will take a lot of memory, and will run on Windows XP. Is it possible for it to use scratch disks? How?</p>
| 2
|
2009-04-10T15:11:33Z
| 737,966
|
<p>Until you ACTUALLY run out of memory, thinking about this is a waste of time.</p>
<p>When you finally do run out of memory, you'll need to use a temporary file to store objects that your process needs, but can't fit into memory.</p>
<p>Use pickle or shelve (see <a href="http://docs.python.org/library/persistence.html" rel="nofollow">Data Persistence</a>) your objects in a file. If that file happens to be on a disk named "scratch", well that's nice.</p>
<p>Sometimes you want your temporary files to be on a separate disk from your other working files for performance reasons. In some environments (SAN, NAS, storage arrays) your disks are virtual and looking for a "scratch" disk doesn't have any performance benefit. In other environments (i.e., you own all the hardware) you can put temporary files on some other drive, making that drive a "scratch" disk.</p>
| 4
|
2009-04-10T15:20:11Z
|
[
"python",
"windows",
"memory-management"
] |
Scratch disks in Python?
| 737,947
|
<p>I understood that in certain Windows XP programs, like Photoshop, there is something called "scratch disks". What I understood that this means, and please correct me if I'm wrong, is that Photoshop manages its own virtual memory on the hard-drive, instead of letting Windows manage it. I understood that the reason for this is some limitation by Windows XP on how much total memory a process can take, regardless of HD space. I think it's around 3 GB. Did I get it right so far?</p>
<p>I am making an application in Python for running simulations. It will take a lot of memory, and will run on Windows XP. Is it possible for it to use scratch disks? How?</p>
| 2
|
2009-04-10T15:11:33Z
| 737,992
|
<p><a href="http://docs.python.org/library/mmap.html" rel="nofollow">Memory mapped files</a> might be what you are looking for. Python's implementation lets you use a file like a mutable string in memory.</p>
| 1
|
2009-04-10T15:31:20Z
|
[
"python",
"windows",
"memory-management"
] |
Scratch disks in Python?
| 737,947
|
<p>I understood that in certain Windows XP programs, like Photoshop, there is something called "scratch disks". What I understood that this means, and please correct me if I'm wrong, is that Photoshop manages its own virtual memory on the hard-drive, instead of letting Windows manage it. I understood that the reason for this is some limitation by Windows XP on how much total memory a process can take, regardless of HD space. I think it's around 3 GB. Did I get it right so far?</p>
<p>I am making an application in Python for running simulations. It will take a lot of memory, and will run on Windows XP. Is it possible for it to use scratch disks? How?</p>
| 2
|
2009-04-10T15:11:33Z
| 738,001
|
<blockquote>
<p>I understood that the reason for this is some limitation by Windows XP on how much total memory a process can take, regardless of HD space. I think it's around 3 GB.</p>
</blockquote>
<p>Just an FYI, this is more a limitation of a 32-bit OS rather than being a Windows XP problem. You'll have the same problem in 32-bit Vista, linux, bsd... you get the idea. If you go the 64-bit route, you don't have these problems.</p>
<p>For example, Windows XP x64 allows up to <a href="http://en.wikipedia.org/wiki/Windows%5Fxp%5Ftablet%5Fpc%5Fedition#Advantages" rel="nofollow">8 terabytes of memory per process</a>.</p>
| 2
|
2009-04-10T15:32:49Z
|
[
"python",
"windows",
"memory-management"
] |
Scratch disks in Python?
| 737,947
|
<p>I understood that in certain Windows XP programs, like Photoshop, there is something called "scratch disks". What I understood that this means, and please correct me if I'm wrong, is that Photoshop manages its own virtual memory on the hard-drive, instead of letting Windows manage it. I understood that the reason for this is some limitation by Windows XP on how much total memory a process can take, regardless of HD space. I think it's around 3 GB. Did I get it right so far?</p>
<p>I am making an application in Python for running simulations. It will take a lot of memory, and will run on Windows XP. Is it possible for it to use scratch disks? How?</p>
| 2
|
2009-04-10T15:11:33Z
| 738,112
|
<p>The Win32 API provides this: <a href="http://msdn.microsoft.com/en-us/library/aa366527%28VS.85%29.aspx" rel="nofollow">link text</a>.
You may be able to use these functions through PyWin32.</p>
| 1
|
2009-04-10T16:04:59Z
|
[
"python",
"windows",
"memory-management"
] |
Scratch disks in Python?
| 737,947
|
<p>I understood that in certain Windows XP programs, like Photoshop, there is something called "scratch disks". What I understood that this means, and please correct me if I'm wrong, is that Photoshop manages its own virtual memory on the hard-drive, instead of letting Windows manage it. I understood that the reason for this is some limitation by Windows XP on how much total memory a process can take, regardless of HD space. I think it's around 3 GB. Did I get it right so far?</p>
<p>I am making an application in Python for running simulations. It will take a lot of memory, and will run on Windows XP. Is it possible for it to use scratch disks? How?</p>
| 2
|
2009-04-10T15:11:33Z
| 738,317
|
<p>You could combine S.Lott's answer about using pickle (you should use cPickle though for better performance) with SqlLite.</p>
<p>sqlite is built into python 2.5 and up, so all you'll need to do is import :), then just store the pickled objects as strings in there and you'll have a nice fast method of accessing the data (compared to building your own method) that will help keep you organized as well.</p>
<p>note: cPickle is almost identical to pickle in use. Only difference is that it is written in C</p>
<p>Useful Python Docs: </p>
<ul>
<li><a href="http://docs.python.org/library/sqlite3.html" rel="nofollow">sqlite3 module</a></li>
<li><a href="http://docs.python.org/library/pickle.html" rel="nofollow">pickle module</a></li>
</ul>
<p><strong>edit</strong>: It may be a good idea to have a user controlled memory usage limit. It would be a shame to be storing a bunch a data on disk and waiting on slow-ass disk I/O when the user has 8GB of RAM ;)</p>
| 1
|
2009-04-10T17:40:44Z
|
[
"python",
"windows",
"memory-management"
] |
Scratch disks in Python?
| 737,947
|
<p>I understood that in certain Windows XP programs, like Photoshop, there is something called "scratch disks". What I understood that this means, and please correct me if I'm wrong, is that Photoshop manages its own virtual memory on the hard-drive, instead of letting Windows manage it. I understood that the reason for this is some limitation by Windows XP on how much total memory a process can take, regardless of HD space. I think it's around 3 GB. Did I get it right so far?</p>
<p>I am making an application in Python for running simulations. It will take a lot of memory, and will run on Windows XP. Is it possible for it to use scratch disks? How?</p>
| 2
|
2009-04-10T15:11:33Z
| 4,207,006
|
<p>You are probably looking for something like ZODB. However, though ZODB tries hard to be transparent, no solution is going to be 100% free of artifacts. You have to write your code with an awareness that your objects primarily live in a database, but that there are multiple representations of your objects, there are caching/syncing issues, etc. Nothing is going to make this very difficult problem completely trivial for you.</p>
| 0
|
2010-11-17T16:59:51Z
|
[
"python",
"windows",
"memory-management"
] |
How to Modify Choices of ModelMultipleChoiceField
| 738,301
|
<p>Let's say I have some contrived models:</p>
<pre><code>class Author(Model):
name = CharField()
class Book(Model):
title = CharField()
author = ForeignKey(Author)
</code></pre>
<p>And let's say I want to use a ModelForm for Book:</p>
<pre><code> class BookForm(ModelForm):
class Meta:
model = Book
</code></pre>
<p>Simple so far. But let's also say that I have a ton of Authors in my database, and I don't want to have such a long multiple choice field. So, I'd like is to restrict the queryset on the BookForm's ModelMultipleChoiceField author field. Let's also say that the queryset I want can't be chosen until <code>__init__</code>, because it relies on an argument to be passed.</p>
<p>This seems like it might do the trick:</p>
<pre><code>class BookForm(ModelForm):
class Meta:
model = Book
def __init__(self, letter):
# returns the queryset based on the letter
choices = getChoices(letter)
self.author.queryset = choices
</code></pre>
<p>Of course, if that just worked I wouldn't be here. That gets me an AttributeError. 'BookForm' object has no attribute 'author'. So, I also tried something like this, where I try to override the ModelForm's default field and then set it later:</p>
<pre><code>class BookForm(ModelForm):
author = ModelMultipleChoiceField(queryset=Author.objects.all())
class Meta:
model = Book
def __init__(self, letter):
choices = getChoices(letter)
self.author.queryset = choices
</code></pre>
<p>Which produces the same result.</p>
<p>Anyone know how this is intended to be done?</p>
| 5
|
2009-04-10T17:34:26Z
| 738,463
|
<p>Form objects don't have their fields as attributes, you need to look in the "fields" attribute, which is a dictionary:</p>
<pre><code>self.fields['author'].queryset = choices
</code></pre>
<p>If you want to fully understand what's going on here, you might be interested in <a href="http://stackoverflow.com/questions/500650/django-model-question-newbie/501362#501362">this answer</a> - it's about Models, but Forms work similarly.</p>
| 8
|
2009-04-10T18:30:45Z
|
[
"python",
"django",
"django-forms"
] |
How to Modify Choices of ModelMultipleChoiceField
| 738,301
|
<p>Let's say I have some contrived models:</p>
<pre><code>class Author(Model):
name = CharField()
class Book(Model):
title = CharField()
author = ForeignKey(Author)
</code></pre>
<p>And let's say I want to use a ModelForm for Book:</p>
<pre><code> class BookForm(ModelForm):
class Meta:
model = Book
</code></pre>
<p>Simple so far. But let's also say that I have a ton of Authors in my database, and I don't want to have such a long multiple choice field. So, I'd like is to restrict the queryset on the BookForm's ModelMultipleChoiceField author field. Let's also say that the queryset I want can't be chosen until <code>__init__</code>, because it relies on an argument to be passed.</p>
<p>This seems like it might do the trick:</p>
<pre><code>class BookForm(ModelForm):
class Meta:
model = Book
def __init__(self, letter):
# returns the queryset based on the letter
choices = getChoices(letter)
self.author.queryset = choices
</code></pre>
<p>Of course, if that just worked I wouldn't be here. That gets me an AttributeError. 'BookForm' object has no attribute 'author'. So, I also tried something like this, where I try to override the ModelForm's default field and then set it later:</p>
<pre><code>class BookForm(ModelForm):
author = ModelMultipleChoiceField(queryset=Author.objects.all())
class Meta:
model = Book
def __init__(self, letter):
choices = getChoices(letter)
self.author.queryset = choices
</code></pre>
<p>Which produces the same result.</p>
<p>Anyone know how this is intended to be done?</p>
| 5
|
2009-04-10T17:34:26Z
| 738,483
|
<p>Although <a href="#738463">Carl</a> is correct about the fields, you're also missing a super class call. This is how I do it:</p>
<pre><code>class BookForm(ModelForm):
author = ModelMultipleChoiceField(queryset=Author.objects.all())
class Meta:
model = Book
def __init__(self, *args, **kwargs):
letter = kwargs.pop('letter')
super(BookForm, self).__init__(*args, **kwargs)
choices = getChoices(letter)
self.fields['author'].queryset = choices
</code></pre>
| 6
|
2009-04-10T18:36:19Z
|
[
"python",
"django",
"django-forms"
] |
Getting started with Django-Instant Django
| 738,433
|
<p>I've been trying to get Django running and when going through the intro to projects it seems that I keep having trouble when I get to the 'sync database' section. When using InstantDjango this doesn't seem to be as much of a problem. My question is, can one just do Django development with the InstantDjango program or do you really need to run it the normal way?</p>
| 0
|
2009-04-10T18:22:34Z
| 3,727,548
|
<p>InstantDjango uses sqlite by default. What database did you set your normal django to use? and you did you create that database before you ran the syncdb?</p>
<p>InstantDjango uses different packaging for all the django required libraries (portable versions) which might be less stable but they should work for your development needs.</p>
| 2
|
2010-09-16T14:16:27Z
|
[
"python",
"django"
] |
In Python, how do I reference a class generically in a static way, like PHP's "self" keyword?
| 738,467
|
<p>PHP classes can use the keyword "self" in a static context, like this:</p>
<pre><code><?php
class Test {
public static $myvar = 'a';
public static function t() {
echo self::$myvar; // Generically reference the current class.
echo Test::$myvar; // Same thing, but not generic.
}
}
?>
</code></pre>
<p>Obviously I can't use "self" in this way in Python because "self" refers not to a class but to an instance. So is there a way I can reference the current class in a static context in Python, similar to PHP's "self"?</p>
<p>I guess what I'm trying to do is rather un-pythonic. Not sure though, I'm new to Python. Here is my code (using the Django framework):</p>
<pre><code>class Friendship(models.Model):
def addfriend(self, friend):
"""does some stuff"""
@staticmethod # declared "staticmethod", not "classmethod"
def user_addfriend(user, friend): # static version of above method
userf = Friendship(user=user) # creating instance of the current class
userf.addfriend(friend) # calls above method
# later ....
Friendship.user_addfriend(u, f) # works
</code></pre>
<p>My code works as expected. I just wanted to know: is there a keyword I could use on the first line of the static method instead of "Friendship"?</p>
<p>This way if the class name changes, the static method won't have to be edited. As it stands the static method would have to be edited if the class name changes.</p>
| 18
|
2009-04-10T18:31:50Z
| 738,480
|
<p>In all cases, <code>self.__class__</code> is an object's class.</p>
<p><a href="http://docs.python.org/library/stdtypes.html#special-attributes">http://docs.python.org/library/stdtypes.html#special-attributes</a></p>
<p>In the (very) rare case where you are trying to mess with static methods, you actually need <a href="http://docs.python.org/library/functions.html#classmethod">classmethod</a> for this.</p>
<pre><code>class AllStatic( object ):
@classmethod
def aMethod( cls, arg ):
# cls is the owning class for this method
x = AllStatic()
x.aMethod( 3.14 )
</code></pre>
| 21
|
2009-04-10T18:35:45Z
|
[
"python",
"class"
] |
In Python, how do I reference a class generically in a static way, like PHP's "self" keyword?
| 738,467
|
<p>PHP classes can use the keyword "self" in a static context, like this:</p>
<pre><code><?php
class Test {
public static $myvar = 'a';
public static function t() {
echo self::$myvar; // Generically reference the current class.
echo Test::$myvar; // Same thing, but not generic.
}
}
?>
</code></pre>
<p>Obviously I can't use "self" in this way in Python because "self" refers not to a class but to an instance. So is there a way I can reference the current class in a static context in Python, similar to PHP's "self"?</p>
<p>I guess what I'm trying to do is rather un-pythonic. Not sure though, I'm new to Python. Here is my code (using the Django framework):</p>
<pre><code>class Friendship(models.Model):
def addfriend(self, friend):
"""does some stuff"""
@staticmethod # declared "staticmethod", not "classmethod"
def user_addfriend(user, friend): # static version of above method
userf = Friendship(user=user) # creating instance of the current class
userf.addfriend(friend) # calls above method
# later ....
Friendship.user_addfriend(u, f) # works
</code></pre>
<p>My code works as expected. I just wanted to know: is there a keyword I could use on the first line of the static method instead of "Friendship"?</p>
<p>This way if the class name changes, the static method won't have to be edited. As it stands the static method would have to be edited if the class name changes.</p>
| 18
|
2009-04-10T18:31:50Z
| 738,552
|
<p>This should do the trick:</p>
<pre><code>class C(object):
my_var = 'a'
@classmethod
def t(cls):
print cls.my_var
C.t()
</code></pre>
| 19
|
2009-04-10T19:04:47Z
|
[
"python",
"class"
] |
How do you automate the launching/debugging of large scale projects?
| 739,090
|
<p><strong>Scenario:</strong></p>
<p>There is a complex piece of software that is annoying to launch by hand. What I've done is to create a python script to launch the executable and attach <em>gdb</em> for debugging.</p>
<p>The process launching script:</p>
<ul>
<li>ensures an environment variable is set.</li>
<li>ensures a local build directory gets added to the environment's <code>LD_LIBRARY_PATH</code> variable.</li>
<li>changes the current working directory to where the executable expects to be (not my design)</li>
<li>launches the executable with a config file the only command line option </li>
<li>pipes the output from the executable to a second logging process</li>
<li>remembers PID of executable, then launches & attaches gdb to running executable.</li>
</ul>
<p>The script works, with one caveat. <strong>ctrl-c doesn't interrupt the debugee and return control to gdb.</strong> So if I "continue" with no active breakpoints I can never stop the process again, it has to be killed/interrupted from another shell. BTW, running "kill -s SIGINT <pid>" where <pid> is the debuggee's pid does get me back to gdb's prompt... but it is really annoying to have to do things this way</p>
<p>At first I thought Python was grabbing the SIGINT signal, but this doesn't seem to be the case as I set up signal handlers forward the signal to the debugee and that doesn't fix the problem.</p>
<p>I've tried various configurations to the python script (calling os.spawn* instead of subprocess, etc.) It seems that any way I go about it, if python launched the child process, SIGINT (ctrl-c) signals DO NOT to get routed to gdb or the child process. </p>
<p><strong>Current line of thinking</strong></p>
<ul>
<li>This might be related to needing a
separate process group id for the debugee & gdb...any credence to this? </li>
<li>Possible bug with SELinux?</li>
</ul>
<p><strong>Info:</strong> </p>
<ul>
<li>gdb 6.8</li>
<li>Python 2.5.2 (problem present with Python 2.6.1 as well)</li>
<li>SELinux Environment (bug delivering signals to processes?)</li>
</ul>
<p><strong>Alternatives I've considered:</strong></p>
<ul>
<li>Setting up a .gdbinit file to do as much of what the script does, environment variables and current working directory are a problem with this approach. </li>
<li>Launching executable and attaching gdb manually (yuck)</li>
</ul>
<p><strong>Question:</strong>
How do you automate the launching/debugging of large scale projects?</p>
<p><strong>Update:</strong>
I've tried Nicholas Riley's examples below, on my Macintosh at home they all allow cntl-c to work to varrying degrees, on the production boxen (which I now to believe may be running SELinux) they don't... </p>
| 4
|
2009-04-10T22:43:55Z
| 739,347
|
<p>Instead of forwarding the signal to the debuggee from Python, you could try just ignoring it. The following worked for me:</p>
<pre><code>import signal
signal.signal(signal.SIGINT, signal.SIG_IGN)
import subprocess
cat = subprocess.Popen(['cat'])
subprocess.call(['gdb', '--pid=%d' % cat.pid])
</code></pre>
<p>With this I was able to ^C repeatedly inside GDB and interrupt the debuggee without a problem, however I did see some weird behavior. </p>
<p>Incidentally, I also had no problem when forwarding the signal to the target process.</p>
<pre><code>import subprocess
cat = subprocess.Popen(['cat'])
import signal, os
signal.signal(signal.SIGINT,
lambda signum, frame: os.kill(cat.pid, signum))
subprocess.call(['gdb', '--pid=%d' % cat.pid])
</code></pre>
<p>So, maybe something else is going on in your case? It might help if you posted some code that breaks.</p>
| 3
|
2009-04-11T01:41:29Z
|
[
"python",
"debugging",
"gdb",
"subprocess",
"selinux"
] |
How do you automate the launching/debugging of large scale projects?
| 739,090
|
<p><strong>Scenario:</strong></p>
<p>There is a complex piece of software that is annoying to launch by hand. What I've done is to create a python script to launch the executable and attach <em>gdb</em> for debugging.</p>
<p>The process launching script:</p>
<ul>
<li>ensures an environment variable is set.</li>
<li>ensures a local build directory gets added to the environment's <code>LD_LIBRARY_PATH</code> variable.</li>
<li>changes the current working directory to where the executable expects to be (not my design)</li>
<li>launches the executable with a config file the only command line option </li>
<li>pipes the output from the executable to a second logging process</li>
<li>remembers PID of executable, then launches & attaches gdb to running executable.</li>
</ul>
<p>The script works, with one caveat. <strong>ctrl-c doesn't interrupt the debugee and return control to gdb.</strong> So if I "continue" with no active breakpoints I can never stop the process again, it has to be killed/interrupted from another shell. BTW, running "kill -s SIGINT <pid>" where <pid> is the debuggee's pid does get me back to gdb's prompt... but it is really annoying to have to do things this way</p>
<p>At first I thought Python was grabbing the SIGINT signal, but this doesn't seem to be the case as I set up signal handlers forward the signal to the debugee and that doesn't fix the problem.</p>
<p>I've tried various configurations to the python script (calling os.spawn* instead of subprocess, etc.) It seems that any way I go about it, if python launched the child process, SIGINT (ctrl-c) signals DO NOT to get routed to gdb or the child process. </p>
<p><strong>Current line of thinking</strong></p>
<ul>
<li>This might be related to needing a
separate process group id for the debugee & gdb...any credence to this? </li>
<li>Possible bug with SELinux?</li>
</ul>
<p><strong>Info:</strong> </p>
<ul>
<li>gdb 6.8</li>
<li>Python 2.5.2 (problem present with Python 2.6.1 as well)</li>
<li>SELinux Environment (bug delivering signals to processes?)</li>
</ul>
<p><strong>Alternatives I've considered:</strong></p>
<ul>
<li>Setting up a .gdbinit file to do as much of what the script does, environment variables and current working directory are a problem with this approach. </li>
<li>Launching executable and attaching gdb manually (yuck)</li>
</ul>
<p><strong>Question:</strong>
How do you automate the launching/debugging of large scale projects?</p>
<p><strong>Update:</strong>
I've tried Nicholas Riley's examples below, on my Macintosh at home they all allow cntl-c to work to varrying degrees, on the production boxen (which I now to believe may be running SELinux) they don't... </p>
| 4
|
2009-04-10T22:43:55Z
| 750,128
|
<p>Your comment notes that you're sshing in with putty... do you have a controlling tty? With openssh you would want to add the -T option, I don't know how/if putty will do this the way you're using it.</p>
<p>Also: you might try using cygwin's ssh instead of putty.</p>
| 0
|
2009-04-15T02:52:24Z
|
[
"python",
"debugging",
"gdb",
"subprocess",
"selinux"
] |
How do you automate the launching/debugging of large scale projects?
| 739,090
|
<p><strong>Scenario:</strong></p>
<p>There is a complex piece of software that is annoying to launch by hand. What I've done is to create a python script to launch the executable and attach <em>gdb</em> for debugging.</p>
<p>The process launching script:</p>
<ul>
<li>ensures an environment variable is set.</li>
<li>ensures a local build directory gets added to the environment's <code>LD_LIBRARY_PATH</code> variable.</li>
<li>changes the current working directory to where the executable expects to be (not my design)</li>
<li>launches the executable with a config file the only command line option </li>
<li>pipes the output from the executable to a second logging process</li>
<li>remembers PID of executable, then launches & attaches gdb to running executable.</li>
</ul>
<p>The script works, with one caveat. <strong>ctrl-c doesn't interrupt the debugee and return control to gdb.</strong> So if I "continue" with no active breakpoints I can never stop the process again, it has to be killed/interrupted from another shell. BTW, running "kill -s SIGINT <pid>" where <pid> is the debuggee's pid does get me back to gdb's prompt... but it is really annoying to have to do things this way</p>
<p>At first I thought Python was grabbing the SIGINT signal, but this doesn't seem to be the case as I set up signal handlers forward the signal to the debugee and that doesn't fix the problem.</p>
<p>I've tried various configurations to the python script (calling os.spawn* instead of subprocess, etc.) It seems that any way I go about it, if python launched the child process, SIGINT (ctrl-c) signals DO NOT to get routed to gdb or the child process. </p>
<p><strong>Current line of thinking</strong></p>
<ul>
<li>This might be related to needing a
separate process group id for the debugee & gdb...any credence to this? </li>
<li>Possible bug with SELinux?</li>
</ul>
<p><strong>Info:</strong> </p>
<ul>
<li>gdb 6.8</li>
<li>Python 2.5.2 (problem present with Python 2.6.1 as well)</li>
<li>SELinux Environment (bug delivering signals to processes?)</li>
</ul>
<p><strong>Alternatives I've considered:</strong></p>
<ul>
<li>Setting up a .gdbinit file to do as much of what the script does, environment variables and current working directory are a problem with this approach. </li>
<li>Launching executable and attaching gdb manually (yuck)</li>
</ul>
<p><strong>Question:</strong>
How do you automate the launching/debugging of large scale projects?</p>
<p><strong>Update:</strong>
I've tried Nicholas Riley's examples below, on my Macintosh at home they all allow cntl-c to work to varrying degrees, on the production boxen (which I now to believe may be running SELinux) they don't... </p>
| 4
|
2009-04-10T22:43:55Z
| 753,721
|
<p>if you already have a current script set up to do this, but are having problems automating part of it, maybe you can just grab expect and use it to provide the setup, then drop back into interactive mode in expect to launch the process. Then you can still have your ctrl-c available to interrupt.</p>
| 0
|
2009-04-15T21:05:18Z
|
[
"python",
"debugging",
"gdb",
"subprocess",
"selinux"
] |
"ImportError: No module named dummy" on fresh Django project
| 739,191
|
<p>I've got the following installed through MacPorts on MacOS X 10.5.6:</p>
<pre><code>py25-sqlite3 @2.5.4_0 (active)
python25 @2.5.4_1+darwin_9+macosx (active)
sqlite3 @3.6.12_0 (active)
</code></pre>
<p><code>python25</code> is correctly set as my system's default Python.</p>
<p>I downloaded a fresh copy of Django 1.1 beta (I have the same problem with 1.0 and trunk, though) and installed it with "<code>sudo python setup.py install</code>".</p>
<p>Things seem to load correctly through the interactive interpreter:</p>
<pre><code>$ python
Python 2.5.4 (r254:67916, Apr 10 2009, 16:02:52)
[GCC 4.0.1 (Apple Inc. build 5490)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> import sqlite3
>>> ^D
</code></pre>
<p>But:</p>
<pre><code>$ django-admin.py startproject foo
$ cd foo/
$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_run at 0x6c1e70>
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate
num_errors = get_validation_errors(s, app)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
from django.db import models, connection
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module>
backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
ImportError: No module named dummy.base
</code></pre>
<p>If I change <code>DATABASE_ENGINE</code> in <code>settings.py</code> to "<code>sqlite3</code>", I get the following, seemingly related problem:</p>
<pre><code>$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_run at 0x6c1e70>
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate
num_errors = get_validation_errors(s, app)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
from django.db import models, connection
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module>
backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
ImportError: No module named base
^C$
</code></pre>
<p>I swear this all worked a few days ago and I don't recall changing anything related to Django or Python, installation-wise.</p>
<p>My various Google adventures have turned up nothing useful. So... Any ideas?</p>
<p>Edit: '<code>syncdb</code>' raises the same exceptions.</p>
| 0
|
2009-04-10T23:53:37Z
| 739,262
|
<p>did you try the intro doc? <a href="http://docs.djangoproject.com/en/dev/intro/tutorial01" rel="nofollow">doc link</a></p>
<p>If you follow this doc, you can at least say, "at step XXXX it got error YYY". Then someone with some experience (no me) should be able to find a good answer. This link is for the trunk, there's a link for 1.0 docs at the top.</p>
| 0
|
2009-04-11T00:46:36Z
|
[
"python",
"database",
"django",
"sqlite"
] |
"ImportError: No module named dummy" on fresh Django project
| 739,191
|
<p>I've got the following installed through MacPorts on MacOS X 10.5.6:</p>
<pre><code>py25-sqlite3 @2.5.4_0 (active)
python25 @2.5.4_1+darwin_9+macosx (active)
sqlite3 @3.6.12_0 (active)
</code></pre>
<p><code>python25</code> is correctly set as my system's default Python.</p>
<p>I downloaded a fresh copy of Django 1.1 beta (I have the same problem with 1.0 and trunk, though) and installed it with "<code>sudo python setup.py install</code>".</p>
<p>Things seem to load correctly through the interactive interpreter:</p>
<pre><code>$ python
Python 2.5.4 (r254:67916, Apr 10 2009, 16:02:52)
[GCC 4.0.1 (Apple Inc. build 5490)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> import sqlite3
>>> ^D
</code></pre>
<p>But:</p>
<pre><code>$ django-admin.py startproject foo
$ cd foo/
$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_run at 0x6c1e70>
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate
num_errors = get_validation_errors(s, app)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
from django.db import models, connection
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module>
backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
ImportError: No module named dummy.base
</code></pre>
<p>If I change <code>DATABASE_ENGINE</code> in <code>settings.py</code> to "<code>sqlite3</code>", I get the following, seemingly related problem:</p>
<pre><code>$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_run at 0x6c1e70>
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate
num_errors = get_validation_errors(s, app)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
from django.db import models, connection
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module>
backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
ImportError: No module named base
^C$
</code></pre>
<p>I swear this all worked a few days ago and I don't recall changing anything related to Django or Python, installation-wise.</p>
<p>My various Google adventures have turned up nothing useful. So... Any ideas?</p>
<p>Edit: '<code>syncdb</code>' raises the same exceptions.</p>
| 0
|
2009-04-10T23:53:37Z
| 739,271
|
<p>duh, i'm not thinking. Just run</p>
<pre><code>python manage.py syncdb
</code></pre>
<p>this will build you db so you can then run the server.</p>
| 0
|
2009-04-11T00:50:52Z
|
[
"python",
"database",
"django",
"sqlite"
] |
"ImportError: No module named dummy" on fresh Django project
| 739,191
|
<p>I've got the following installed through MacPorts on MacOS X 10.5.6:</p>
<pre><code>py25-sqlite3 @2.5.4_0 (active)
python25 @2.5.4_1+darwin_9+macosx (active)
sqlite3 @3.6.12_0 (active)
</code></pre>
<p><code>python25</code> is correctly set as my system's default Python.</p>
<p>I downloaded a fresh copy of Django 1.1 beta (I have the same problem with 1.0 and trunk, though) and installed it with "<code>sudo python setup.py install</code>".</p>
<p>Things seem to load correctly through the interactive interpreter:</p>
<pre><code>$ python
Python 2.5.4 (r254:67916, Apr 10 2009, 16:02:52)
[GCC 4.0.1 (Apple Inc. build 5490)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> import sqlite3
>>> ^D
</code></pre>
<p>But:</p>
<pre><code>$ django-admin.py startproject foo
$ cd foo/
$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_run at 0x6c1e70>
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate
num_errors = get_validation_errors(s, app)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
from django.db import models, connection
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module>
backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
ImportError: No module named dummy.base
</code></pre>
<p>If I change <code>DATABASE_ENGINE</code> in <code>settings.py</code> to "<code>sqlite3</code>", I get the following, seemingly related problem:</p>
<pre><code>$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_run at 0x6c1e70>
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate
num_errors = get_validation_errors(s, app)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
from django.db import models, connection
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module>
backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
ImportError: No module named base
^C$
</code></pre>
<p>I swear this all worked a few days ago and I don't recall changing anything related to Django or Python, installation-wise.</p>
<p>My various Google adventures have turned up nothing useful. So... Any ideas?</p>
<p>Edit: '<code>syncdb</code>' raises the same exceptions.</p>
| 0
|
2009-04-10T23:53:37Z
| 739,986
|
<p>Re-check your settings.py. In the second case, it looks like your DATABASE_ENGINE is set to the empty string, not 'sqlite3'.</p>
| 0
|
2009-04-11T12:31:40Z
|
[
"python",
"database",
"django",
"sqlite"
] |
"ImportError: No module named dummy" on fresh Django project
| 739,191
|
<p>I've got the following installed through MacPorts on MacOS X 10.5.6:</p>
<pre><code>py25-sqlite3 @2.5.4_0 (active)
python25 @2.5.4_1+darwin_9+macosx (active)
sqlite3 @3.6.12_0 (active)
</code></pre>
<p><code>python25</code> is correctly set as my system's default Python.</p>
<p>I downloaded a fresh copy of Django 1.1 beta (I have the same problem with 1.0 and trunk, though) and installed it with "<code>sudo python setup.py install</code>".</p>
<p>Things seem to load correctly through the interactive interpreter:</p>
<pre><code>$ python
Python 2.5.4 (r254:67916, Apr 10 2009, 16:02:52)
[GCC 4.0.1 (Apple Inc. build 5490)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> import sqlite3
>>> ^D
</code></pre>
<p>But:</p>
<pre><code>$ django-admin.py startproject foo
$ cd foo/
$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_run at 0x6c1e70>
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate
num_errors = get_validation_errors(s, app)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
from django.db import models, connection
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module>
backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
ImportError: No module named dummy.base
</code></pre>
<p>If I change <code>DATABASE_ENGINE</code> in <code>settings.py</code> to "<code>sqlite3</code>", I get the following, seemingly related problem:</p>
<pre><code>$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_run at 0x6c1e70>
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate
num_errors = get_validation_errors(s, app)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
from django.db import models, connection
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module>
backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
ImportError: No module named base
^C$
</code></pre>
<p>I swear this all worked a few days ago and I don't recall changing anything related to Django or Python, installation-wise.</p>
<p>My various Google adventures have turned up nothing useful. So... Any ideas?</p>
<p>Edit: '<code>syncdb</code>' raises the same exceptions.</p>
| 0
|
2009-04-10T23:53:37Z
| 749,985
|
<p>I found this <a href="http://groups.google.com/group/django-users/browse%5Fthread/thread/ea60854ad2e00b98" rel="nofollow">thread</a> on the Django Users group:</p>
<p>They suggest that it has something to do with the way MacPorts installs Python. I wish I had more details to help you with, but as a workaround, I recommend you use MacPorts to uninstall this copy of Python and try to use alternate method of install it. If you're looking for an quick and easy install, you might want to try <a href="http://wiki.python.org/moin/MacPython/Leopard" rel="nofollow">MacPython</a>. Hope this helps!</p>
| 1
|
2009-04-15T01:39:36Z
|
[
"python",
"database",
"django",
"sqlite"
] |
"ImportError: No module named dummy" on fresh Django project
| 739,191
|
<p>I've got the following installed through MacPorts on MacOS X 10.5.6:</p>
<pre><code>py25-sqlite3 @2.5.4_0 (active)
python25 @2.5.4_1+darwin_9+macosx (active)
sqlite3 @3.6.12_0 (active)
</code></pre>
<p><code>python25</code> is correctly set as my system's default Python.</p>
<p>I downloaded a fresh copy of Django 1.1 beta (I have the same problem with 1.0 and trunk, though) and installed it with "<code>sudo python setup.py install</code>".</p>
<p>Things seem to load correctly through the interactive interpreter:</p>
<pre><code>$ python
Python 2.5.4 (r254:67916, Apr 10 2009, 16:02:52)
[GCC 4.0.1 (Apple Inc. build 5490)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> import sqlite3
>>> ^D
</code></pre>
<p>But:</p>
<pre><code>$ django-admin.py startproject foo
$ cd foo/
$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_run at 0x6c1e70>
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate
num_errors = get_validation_errors(s, app)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
from django.db import models, connection
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module>
backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
ImportError: No module named dummy.base
</code></pre>
<p>If I change <code>DATABASE_ENGINE</code> in <code>settings.py</code> to "<code>sqlite3</code>", I get the following, seemingly related problem:</p>
<pre><code>$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_run at 0x6c1e70>
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate
num_errors = get_validation_errors(s, app)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
from django.db import models, connection
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module>
backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
ImportError: No module named base
^C$
</code></pre>
<p>I swear this all worked a few days ago and I don't recall changing anything related to Django or Python, installation-wise.</p>
<p>My various Google adventures have turned up nothing useful. So... Any ideas?</p>
<p>Edit: '<code>syncdb</code>' raises the same exceptions.</p>
| 0
|
2009-04-10T23:53:37Z
| 751,630
|
<p>This isn't an answer, exactly, but I would try removing the MacPorts install of Django and start over. Then try adding <a href="http://peak.telecommunity.com/DevCenter/EasyInstall" rel="nofollow">easy_install</a> and using that to install everything. To make things cleaner and easier to start over, you might also want to add <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a>, which lets you set up multiple self-contained Python environments.</p>
| 0
|
2009-04-15T13:12:08Z
|
[
"python",
"database",
"django",
"sqlite"
] |
"ImportError: No module named dummy" on fresh Django project
| 739,191
|
<p>I've got the following installed through MacPorts on MacOS X 10.5.6:</p>
<pre><code>py25-sqlite3 @2.5.4_0 (active)
python25 @2.5.4_1+darwin_9+macosx (active)
sqlite3 @3.6.12_0 (active)
</code></pre>
<p><code>python25</code> is correctly set as my system's default Python.</p>
<p>I downloaded a fresh copy of Django 1.1 beta (I have the same problem with 1.0 and trunk, though) and installed it with "<code>sudo python setup.py install</code>".</p>
<p>Things seem to load correctly through the interactive interpreter:</p>
<pre><code>$ python
Python 2.5.4 (r254:67916, Apr 10 2009, 16:02:52)
[GCC 4.0.1 (Apple Inc. build 5490)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> import sqlite3
>>> ^D
</code></pre>
<p>But:</p>
<pre><code>$ django-admin.py startproject foo
$ cd foo/
$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_run at 0x6c1e70>
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate
num_errors = get_validation_errors(s, app)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
from django.db import models, connection
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module>
backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
ImportError: No module named dummy.base
</code></pre>
<p>If I change <code>DATABASE_ENGINE</code> in <code>settings.py</code> to "<code>sqlite3</code>", I get the following, seemingly related problem:</p>
<pre><code>$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_run at 0x6c1e70>
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate
num_errors = get_validation_errors(s, app)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
from django.db import models, connection
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module>
backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
ImportError: No module named base
^C$
</code></pre>
<p>I swear this all worked a few days ago and I don't recall changing anything related to Django or Python, installation-wise.</p>
<p>My various Google adventures have turned up nothing useful. So... Any ideas?</p>
<p>Edit: '<code>syncdb</code>' raises the same exceptions.</p>
| 0
|
2009-04-10T23:53:37Z
| 756,828
|
<p>You can also try installing the py25-hashlib package if you don't have it already. I found this described on the <a href="http://code.djangoproject.com/ticket/8489" rel="nofollow">django bug tracking site</a>.</p>
<p>Normally, this package is part of python, but it's either missing or wrong in the macports version, from what I've read.</p>
<p>I found more info on the macports version of py25-hashlib <a href="http://py25-hashlib.darwinports.com/" rel="nofollow">here</a>.</p>
| 0
|
2009-04-16T16:01:10Z
|
[
"python",
"database",
"django",
"sqlite"
] |
"ImportError: No module named dummy" on fresh Django project
| 739,191
|
<p>I've got the following installed through MacPorts on MacOS X 10.5.6:</p>
<pre><code>py25-sqlite3 @2.5.4_0 (active)
python25 @2.5.4_1+darwin_9+macosx (active)
sqlite3 @3.6.12_0 (active)
</code></pre>
<p><code>python25</code> is correctly set as my system's default Python.</p>
<p>I downloaded a fresh copy of Django 1.1 beta (I have the same problem with 1.0 and trunk, though) and installed it with "<code>sudo python setup.py install</code>".</p>
<p>Things seem to load correctly through the interactive interpreter:</p>
<pre><code>$ python
Python 2.5.4 (r254:67916, Apr 10 2009, 16:02:52)
[GCC 4.0.1 (Apple Inc. build 5490)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> import sqlite3
>>> ^D
</code></pre>
<p>But:</p>
<pre><code>$ django-admin.py startproject foo
$ cd foo/
$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_run at 0x6c1e70>
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate
num_errors = get_validation_errors(s, app)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
from django.db import models, connection
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module>
backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
ImportError: No module named dummy.base
</code></pre>
<p>If I change <code>DATABASE_ENGINE</code> in <code>settings.py</code> to "<code>sqlite3</code>", I get the following, seemingly related problem:</p>
<pre><code>$ python manage.py runserver
Validating models...
Unhandled exception in thread started by <function inner_run at 0x6c1e70>
Traceback (most recent call last):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/base.py", line 246, in validate
num_errors = get_validation_errors(s, app)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/core/management/validation.py", line 22, in get_validation_errors
from django.db import models, connection
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/django/db/__init__.py", line 22, in <module>
backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
ImportError: No module named base
^C$
</code></pre>
<p>I swear this all worked a few days ago and I don't recall changing anything related to Django or Python, installation-wise.</p>
<p>My various Google adventures have turned up nothing useful. So... Any ideas?</p>
<p>Edit: '<code>syncdb</code>' raises the same exceptions.</p>
| 0
|
2009-04-10T23:53:37Z
| 757,829
|
<p>Try using the full path to python as well as checking the module path</p>
| 0
|
2009-04-16T20:04:13Z
|
[
"python",
"database",
"django",
"sqlite"
] |
Date Ordinal Output?
| 739,241
|
<p>I'm wondering if there is a quick and easy way to output ordinals given a number in python.</p>
<p>For example, given the number <code>1</code>, I'd like to output <code>"1st"</code>, the number <code>2</code>, <code>"2nd"</code>, et cetera, et cetera.</p>
<p>This is for working with dates in a breadcrumb trail</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 01
</code></pre>
<p>is what is currently shown</p>
<p>I'd like to have something along the lines of</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 1st
</code></pre>
| 18
|
2009-04-11T00:22:31Z
| 739,256
|
<p>Except for 1st, 2nd, and 3rd, I think they all just add th... 4th, 5th, 6th, 11th, 21st ... oh, oops ;-)</p>
<p>I think this might work:</p>
<pre><code>def ordinal(num):
ldig = num % 10
l2dig = (num // 10) % 10
if l2dig == 1:
suffix = 'th'
elif ldig == 1:
suffix = 'st'
elif ldig == 2:
suffix = 'nd'
elif ldig == 3:
suffix = 'rd'
else:
suffix = 'th'
return '%d%s' % (num, suffix)
</code></pre>
| 1
|
2009-04-11T00:40:24Z
|
[
"python"
] |
Date Ordinal Output?
| 739,241
|
<p>I'm wondering if there is a quick and easy way to output ordinals given a number in python.</p>
<p>For example, given the number <code>1</code>, I'd like to output <code>"1st"</code>, the number <code>2</code>, <code>"2nd"</code>, et cetera, et cetera.</p>
<p>This is for working with dates in a breadcrumb trail</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 01
</code></pre>
<p>is what is currently shown</p>
<p>I'd like to have something along the lines of</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 1st
</code></pre>
| 18
|
2009-04-11T00:22:31Z
| 739,266
|
<p>Or shorten David's answer with:</p>
<pre><code>if 4 <= day <= 20 or 24 <= day <= 30:
suffix = "th"
else:
suffix = ["st", "nd", "rd"][day % 10 - 1]
</code></pre>
| 29
|
2009-04-11T00:48:09Z
|
[
"python"
] |
Date Ordinal Output?
| 739,241
|
<p>I'm wondering if there is a quick and easy way to output ordinals given a number in python.</p>
<p>For example, given the number <code>1</code>, I'd like to output <code>"1st"</code>, the number <code>2</code>, <code>"2nd"</code>, et cetera, et cetera.</p>
<p>This is for working with dates in a breadcrumb trail</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 01
</code></pre>
<p>is what is currently shown</p>
<p>I'd like to have something along the lines of</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 1st
</code></pre>
| 18
|
2009-04-11T00:22:31Z
| 739,301
|
<p>Here's a more general solution:</p>
<pre><code>def ordinal(n):
if 10 <= n % 100 < 20:
return str(n) + 'th'
else:
return str(n) + {1 : 'st', 2 : 'nd', 3 : 'rd'}.get(n % 10, "th")
</code></pre>
| 26
|
2009-04-11T01:11:30Z
|
[
"python"
] |
Date Ordinal Output?
| 739,241
|
<p>I'm wondering if there is a quick and easy way to output ordinals given a number in python.</p>
<p>For example, given the number <code>1</code>, I'd like to output <code>"1st"</code>, the number <code>2</code>, <code>"2nd"</code>, et cetera, et cetera.</p>
<p>This is for working with dates in a breadcrumb trail</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 01
</code></pre>
<p>is what is currently shown</p>
<p>I'd like to have something along the lines of</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 1st
</code></pre>
| 18
|
2009-04-11T00:22:31Z
| 2,232,619
|
<p>Here it is using dictionaries as either a function or as a lambda...</p>
<p>If you look at the dictionaries backwards you can read it as...</p>
<p>Everything ends in 'th'</p>
<p>...unless it ends in 1, 2, or 3 then it ends in 'st', 'nd', or 'rd'</p>
<p>...unless it ends in 11, 12, or 13 then it ends in 'th, 'th', or 'th'</p>
<pre><code># as a function
def ordinal(num):
return '%d%s' % (num, { 11: 'th', 12: 'th', 13: 'th' }.get(num % 100, { 1: 'st',2: 'nd',3: 'rd',}.get(num % 10, 'th')))
# as a lambda
ordinal = lambda num : '%d%s' % (num, { 11: 'th', 12: 'th', 13: 'th' }.get(num % 100, { 1: 'st',2: 'nd',3: 'rd',}.get(num % 10, 'th')))
</code></pre>
| 1
|
2010-02-09T21:20:51Z
|
[
"python"
] |
Date Ordinal Output?
| 739,241
|
<p>I'm wondering if there is a quick and easy way to output ordinals given a number in python.</p>
<p>For example, given the number <code>1</code>, I'd like to output <code>"1st"</code>, the number <code>2</code>, <code>"2nd"</code>, et cetera, et cetera.</p>
<p>This is for working with dates in a breadcrumb trail</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 01
</code></pre>
<p>is what is currently shown</p>
<p>I'd like to have something along the lines of</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 1st
</code></pre>
| 18
|
2009-04-11T00:22:31Z
| 2,276,874
|
<p>Here is an even shorter general solution:</p>
<pre><code>def foo(n):
return str(n) + {1: 'st', 2: 'nd', 3: 'rd'}.get(4 if 10 <= n % 100 < 20 else n % 10, "th")
</code></pre>
<p>Although the other solutions above are probably easier to understand at first glance, this works just as well while using a bit less code.</p>
| 0
|
2010-02-16T22:28:19Z
|
[
"python"
] |
Date Ordinal Output?
| 739,241
|
<p>I'm wondering if there is a quick and easy way to output ordinals given a number in python.</p>
<p>For example, given the number <code>1</code>, I'd like to output <code>"1st"</code>, the number <code>2</code>, <code>"2nd"</code>, et cetera, et cetera.</p>
<p>This is for working with dates in a breadcrumb trail</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 01
</code></pre>
<p>is what is currently shown</p>
<p>I'd like to have something along the lines of</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 1st
</code></pre>
| 18
|
2009-04-11T00:22:31Z
| 8,954,390
|
<p>Fixed for negative-inputs, based on eric.frederich's nice sol'n (just added <code>abs</code> when using <code>%</code>):</p>
<pre><code>def ordinal(num):
return '%d%s' % (num, { 11: 'th', 12: 'th', 13: 'th'}.get(abs(num) % 100, { 1: 'st',2: 'nd',3: 'rd',}.get(abs(num) % 10, 'th')))
</code></pre>
| 0
|
2012-01-21T16:00:04Z
|
[
"python"
] |
Date Ordinal Output?
| 739,241
|
<p>I'm wondering if there is a quick and easy way to output ordinals given a number in python.</p>
<p>For example, given the number <code>1</code>, I'd like to output <code>"1st"</code>, the number <code>2</code>, <code>"2nd"</code>, et cetera, et cetera.</p>
<p>This is for working with dates in a breadcrumb trail</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 01
</code></pre>
<p>is what is currently shown</p>
<p>I'd like to have something along the lines of</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 1st
</code></pre>
| 18
|
2009-04-11T00:22:31Z
| 14,257,232
|
<p>A more general and shorter solution (as a function):</p>
<pre><code>def get_ordinal(num)
ldig = num % 10
l2dig = (num // 10) % 10
if (l2dig == 1) or (ldig > 3):
return '%d%s' % (num, 'th')
else:
return '%d%s' % (num, {1: 'st', 2: 'nd', 3: 'rd'}.get(ldig))
</code></pre>
<p>I just combined David's solutions and libraries (as deegeedubs did). You can even replace the variables (ldig, l2dig) for the real math (since l2dig is used only once), then you get four lines of code.</p>
| 2
|
2013-01-10T11:47:26Z
|
[
"python"
] |
Date Ordinal Output?
| 739,241
|
<p>I'm wondering if there is a quick and easy way to output ordinals given a number in python.</p>
<p>For example, given the number <code>1</code>, I'd like to output <code>"1st"</code>, the number <code>2</code>, <code>"2nd"</code>, et cetera, et cetera.</p>
<p>This is for working with dates in a breadcrumb trail</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 01
</code></pre>
<p>is what is currently shown</p>
<p>I'd like to have something along the lines of</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 1st
</code></pre>
| 18
|
2009-04-11T00:22:31Z
| 16,671,215
|
<p>I had to convert a script over from javascript where I had a useful fn that replicated phps date obj. Very similar</p>
<pre><code>def ord(n):
return str(n)+("th" if 4<=n%100<=20 else {1:"st",2:"nd",3:"rd"}.get(n%10, "th"))
</code></pre>
<p>this tied in with my date styler:</p>
<pre><code>def dtStylish(dt,f):
return dt.strftime(f).replace("{th}", ord(dt.day))
</code></pre>
<p>ps -I got here from another thread which was reported as a duplicate but it wasn't entirely since that thread also addressed the date issue</p>
| 0
|
2013-05-21T13:24:25Z
|
[
"python"
] |
Date Ordinal Output?
| 739,241
|
<p>I'm wondering if there is a quick and easy way to output ordinals given a number in python.</p>
<p>For example, given the number <code>1</code>, I'd like to output <code>"1st"</code>, the number <code>2</code>, <code>"2nd"</code>, et cetera, et cetera.</p>
<p>This is for working with dates in a breadcrumb trail</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 01
</code></pre>
<p>is what is currently shown</p>
<p>I'd like to have something along the lines of</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 1st
</code></pre>
| 18
|
2009-04-11T00:22:31Z
| 18,670,856
|
<p>I wanted to use ordinals for a project of mine and after a few prototypes I think this method although not small will work for any positive integer, yes any integer.</p>
<p>It works by determiniting if the number is above or below 20, if the number is below 20 it will turn the int 1 into the string 1st , 2 , 2nd; 3, 3rd; and the rest will have "st" added to it.</p>
<p>For numbers over 20 it will take the last and second to last digits, which I have called the tens and unit respectively and test them to see what to add to the number.</p>
<p>This is in python by the way, so I'm not sure if other languages will be able to find the last or second to last digit on a string if they do it should translate pretty easily.</p>
<pre><code>def o(numb):
if numb < 20: #determining suffix for < 20
if numb == 1:
suffix = 'st'
elif numb == 2:
suffix = 'nd'
elif numb == 3:
suffix = 'rd'
else:
suffix = 'th'
else: #determining suffix for > 20
tens = str(numb)
tens = tens[-2]
unit = str(numb)
unit = unit[-1]
if tens == "1":
suffix = "th"
else:
if unit == "1":
suffix = 'st'
elif unit == "2":
suffix = 'nd'
elif unit == "3":
suffix = 'rd'
else:
suffix = 'th'
return str(numb)+ suffix
</code></pre>
<p>I called the function "o" for ease of use and can be called by importing the file name which I called "ordinal" by import ordinal then ordinal.o(number).</p>
<p>Let me know what you think :D</p>
<p>P.S. I've posted this answer on another ordinals question but realised this one is more applicable considering it's python.</p>
| 0
|
2013-09-07T07:20:57Z
|
[
"python"
] |
Date Ordinal Output?
| 739,241
|
<p>I'm wondering if there is a quick and easy way to output ordinals given a number in python.</p>
<p>For example, given the number <code>1</code>, I'd like to output <code>"1st"</code>, the number <code>2</code>, <code>"2nd"</code>, et cetera, et cetera.</p>
<p>This is for working with dates in a breadcrumb trail</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 01
</code></pre>
<p>is what is currently shown</p>
<p>I'd like to have something along the lines of</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 1st
</code></pre>
| 18
|
2009-04-11T00:22:31Z
| 21,143,552
|
<pre><code>def ordinal(n):
return ["th", "st", "nd", "rd"][n%10 if n%10<4 and not (10<n%100<14) else 0]
</code></pre>
| 1
|
2014-01-15T16:56:58Z
|
[
"python"
] |
Date Ordinal Output?
| 739,241
|
<p>I'm wondering if there is a quick and easy way to output ordinals given a number in python.</p>
<p>For example, given the number <code>1</code>, I'd like to output <code>"1st"</code>, the number <code>2</code>, <code>"2nd"</code>, et cetera, et cetera.</p>
<p>This is for working with dates in a breadcrumb trail</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 01
</code></pre>
<p>is what is currently shown</p>
<p>I'd like to have something along the lines of</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 1st
</code></pre>
| 18
|
2009-04-11T00:22:31Z
| 21,668,902
|
<p>Not sure if it existed 5 years ago when you asked this question, but the <a href="https://pypi.python.org/pypi/inflect">inflect</a> package has a function to do what you're looking for:</p>
<pre><code>>>> import inflect
>>> p = inflect.engine()
>>> for i in range(1,32):
... print p.ordinal(i)
...
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
10th
11th
12th
13th
14th
15th
16th
17th
18th
19th
20th
21st
22nd
23rd
24th
25th
26th
27th
28th
29th
30th
31st
</code></pre>
| 9
|
2014-02-10T04:04:22Z
|
[
"python"
] |
Date Ordinal Output?
| 739,241
|
<p>I'm wondering if there is a quick and easy way to output ordinals given a number in python.</p>
<p>For example, given the number <code>1</code>, I'd like to output <code>"1st"</code>, the number <code>2</code>, <code>"2nd"</code>, et cetera, et cetera.</p>
<p>This is for working with dates in a breadcrumb trail</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 01
</code></pre>
<p>is what is currently shown</p>
<p>I'd like to have something along the lines of</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 1st
</code></pre>
| 18
|
2009-04-11T00:22:31Z
| 29,554,088
|
<p>Here's a function I wrote as part of a calendar type of program I wrote (I'm not including the whole program). It adds on the correct ordinal for any number greater than 0. I included a loop to demo the output.</p>
<pre><code>def ordinals(num):
# st, nums ending in '1' except '11'
if num[-1] == '1' and num[-2:] != '11':
return num + 'st'
# nd, nums ending in '2' except '12'
elif num[-1] == '2' and num[-2:] != '12':
return num + 'nd'
# rd, nums ending in '3' except '13'
elif num[-1] == '3' and num[-2:] != '13':
return num + 'rd'
# th, all other nums
else:
return num + 'th'
data = ''
# print the first 366 ordinals (for leap year)
for i in range(1, 367):
data += ordinals(str(i)) + '\n'
# print results to file
with open('ordinals.txt', 'w') as wf:
wf.write(data)
</code></pre>
| 0
|
2015-04-10T05:34:12Z
|
[
"python"
] |
Date Ordinal Output?
| 739,241
|
<p>I'm wondering if there is a quick and easy way to output ordinals given a number in python.</p>
<p>For example, given the number <code>1</code>, I'd like to output <code>"1st"</code>, the number <code>2</code>, <code>"2nd"</code>, et cetera, et cetera.</p>
<p>This is for working with dates in a breadcrumb trail</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 01
</code></pre>
<p>is what is currently shown</p>
<p>I'd like to have something along the lines of</p>
<pre><code>Home > Venues > Bar Academy > 2009 > April > 1st
</code></pre>
| 18
|
2009-04-11T00:22:31Z
| 37,473,756
|
<p>These days I'd use Arrow <a href="http://arrow.readthedocs.io/en/latest/" rel="nofollow">http://arrow.readthedocs.io/en/latest/</a> (which definately wasn't around in '09)</p>
<pre><code>>>> import arrow
>>> from datetime import datetime
>>> arrow.get(datetime.utcnow()).format('Do')
'27th'
</code></pre>
| 0
|
2016-05-27T02:14:33Z
|
[
"python"
] |
Customize/remove Django select box blank option
| 739,260
|
<p>I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:</p>
<pre><code><option value="">---------</option>
</code></pre>
<p>What I'd like to know is:</p>
<ol>
<li>What is the cleanest way to remove this auto-generated option from the select box? </li>
<li><p>What is the cleanest way to customize it so that it shows as:</p>
<pre><code><option value="">Select Item</option>
</code></pre></li>
</ol>
<p>In searching for a solution I came across <a href="http://code.djangoproject.com/ticket/4653">Django ticket 4653</a> which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.</p>
<p>Thanks for any help,</p>
<p>Jeff</p>
<p>Edit: I've configured the ForeignKey field as such: </p>
<pre><code>verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)
</code></pre>
<p>This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.</p>
| 58
|
2009-04-11T00:43:58Z
| 739,286
|
<p>from the docs</p>
<blockquote>
<p>The blank choice will not be included
if the model field has blank=False and
an explicit default value (the default
value will be initially selected
instead).</p>
</blockquote>
<p>so set the default and you're ok</p>
| 30
|
2009-04-11T00:58:57Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
Customize/remove Django select box blank option
| 739,260
|
<p>I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:</p>
<pre><code><option value="">---------</option>
</code></pre>
<p>What I'd like to know is:</p>
<ol>
<li>What is the cleanest way to remove this auto-generated option from the select box? </li>
<li><p>What is the cleanest way to customize it so that it shows as:</p>
<pre><code><option value="">Select Item</option>
</code></pre></li>
</ol>
<p>In searching for a solution I came across <a href="http://code.djangoproject.com/ticket/4653">Django ticket 4653</a> which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.</p>
<p>Thanks for any help,</p>
<p>Jeff</p>
<p>Edit: I've configured the ForeignKey field as such: </p>
<pre><code>verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)
</code></pre>
<p>This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.</p>
| 58
|
2009-04-11T00:43:58Z
| 739,925
|
<p>If all else fails there's always JQuery*.</p>
<p>It's dirty but it works.</p>
<p>(*choose your JS poison)</p>
<p>Edit - I'd like to see some justifications for the downvote - it's arguable that a JS solution is cleaner than the accepted answer and it's certainly quicker to implement. I'd say that this is a reasonable case for 'progressive enhancement'.</p>
| -2
|
2009-04-11T11:46:28Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
Customize/remove Django select box blank option
| 739,260
|
<p>I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:</p>
<pre><code><option value="">---------</option>
</code></pre>
<p>What I'd like to know is:</p>
<ol>
<li>What is the cleanest way to remove this auto-generated option from the select box? </li>
<li><p>What is the cleanest way to customize it so that it shows as:</p>
<pre><code><option value="">Select Item</option>
</code></pre></li>
</ol>
<p>In searching for a solution I came across <a href="http://code.djangoproject.com/ticket/4653">Django ticket 4653</a> which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.</p>
<p>Thanks for any help,</p>
<p>Jeff</p>
<p>Edit: I've configured the ForeignKey field as such: </p>
<pre><code>verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)
</code></pre>
<p>This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.</p>
| 58
|
2009-04-11T00:43:58Z
| 740,011
|
<p>Haven't tested this, but based on reading Django's code <a href="http://code.djangoproject.com/browser/django/trunk/django/forms/models.py#L680">here</a> and <a href="http://code.djangoproject.com/browser/django/trunk/django/forms/models.py#L710">here</a> I believe it should work:</p>
<pre><code>class ThingForm(models.ModelForm):
class Meta:
model = Thing
def __init__(self, *args, **kwargs):
super(ThingForm, self).__init__(*args, **kwargs)
self.fields['verb'].empty_label = None
</code></pre>
<p><strong>EDIT</strong>: This is <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield">documented</a>, though you wouldn't necessarily know to look for ModelChoiceField if you're working with an auto-generated ModelForm.</p>
<p><strong>EDIT</strong>: As jlpp notes in his answer, this isn't complete - you have to re-assign the choices to the widgets after changing the empty_label attribute. Since that's a bit hacky, the other option that might be easier to understand is just overriding the entire ModelChoiceField:</p>
<pre><code>class ThingForm(models.ModelForm):
verb = ModelChoiceField(Verb.objects.all(), empty_label=None)
class Meta:
model = Thing
</code></pre>
| 65
|
2009-04-11T12:40:43Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
Customize/remove Django select box blank option
| 739,260
|
<p>I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:</p>
<pre><code><option value="">---------</option>
</code></pre>
<p>What I'd like to know is:</p>
<ol>
<li>What is the cleanest way to remove this auto-generated option from the select box? </li>
<li><p>What is the cleanest way to customize it so that it shows as:</p>
<pre><code><option value="">Select Item</option>
</code></pre></li>
</ol>
<p>In searching for a solution I came across <a href="http://code.djangoproject.com/ticket/4653">Django ticket 4653</a> which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.</p>
<p>Thanks for any help,</p>
<p>Jeff</p>
<p>Edit: I've configured the ForeignKey field as such: </p>
<pre><code>verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)
</code></pre>
<p>This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.</p>
| 58
|
2009-04-11T00:43:58Z
| 741,297
|
<p>With Carl's answer as a guide and after rooting around the Django source for a couple hours I think this is the complete solution:</p>
<ol>
<li><p>To remove the empty option (extending Carl's example):</p>
<pre><code>class ThingForm(models.ModelForm):
class Meta:
model = Thing
def __init__(self, *args, **kwargs):
super(ThingForm, self).__init__(*args, **kwargs)
self.fields['verb'].empty_label = None
# following line needed to refresh widget copy of choice list
self.fields['verb'].widget.choices =
self.fields['verb'].choices
</code></pre></li>
<li><p>To customize the empty option label is essentially the same:</p>
<pre><code>class ThingForm(models.ModelForm):
class Meta:
model = Thing
def __init__(self, *args, **kwargs):
super(ThingForm, self).__init__(*args, **kwargs)
self.fields['verb'].empty_label = "Select a Verb"
# following line needed to refresh widget copy of choice list
self.fields['verb'].widget.choices =
self.fields['verb'].choices
</code></pre></li>
</ol>
<p>I think this approach applies to all scenarios where ModelChoiceFields are rendered as HTML but I'm not positive. I found that when these fields are initialized, their choices are passed to the Select widget (see django.forms.fields.ChoiceField._set_choices). Setting the empty_label after initialization does not refresh the Select widget's list of choices. I'm not familiar enough with Django to know if this should be considered a bug.</p>
| 15
|
2009-04-12T05:13:30Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
Customize/remove Django select box blank option
| 739,260
|
<p>I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:</p>
<pre><code><option value="">---------</option>
</code></pre>
<p>What I'd like to know is:</p>
<ol>
<li>What is the cleanest way to remove this auto-generated option from the select box? </li>
<li><p>What is the cleanest way to customize it so that it shows as:</p>
<pre><code><option value="">Select Item</option>
</code></pre></li>
</ol>
<p>In searching for a solution I came across <a href="http://code.djangoproject.com/ticket/4653">Django ticket 4653</a> which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.</p>
<p>Thanks for any help,</p>
<p>Jeff</p>
<p>Edit: I've configured the ForeignKey field as such: </p>
<pre><code>verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)
</code></pre>
<p>This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.</p>
| 58
|
2009-04-11T00:43:58Z
| 1,363,109
|
<p>See <a href="http://code.djangoproject.com/ticket/4653" rel="nofollow">here</a> for the complete debate on and methods for resolution of this issue.</p>
| 4
|
2009-09-01T15:29:11Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
Customize/remove Django select box blank option
| 739,260
|
<p>I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:</p>
<pre><code><option value="">---------</option>
</code></pre>
<p>What I'd like to know is:</p>
<ol>
<li>What is the cleanest way to remove this auto-generated option from the select box? </li>
<li><p>What is the cleanest way to customize it so that it shows as:</p>
<pre><code><option value="">Select Item</option>
</code></pre></li>
</ol>
<p>In searching for a solution I came across <a href="http://code.djangoproject.com/ticket/4653">Django ticket 4653</a> which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.</p>
<p>Thanks for any help,</p>
<p>Jeff</p>
<p>Edit: I've configured the ForeignKey field as such: </p>
<pre><code>verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)
</code></pre>
<p>This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.</p>
| 58
|
2009-04-11T00:43:58Z
| 11,721,969
|
<p>As for the django 1.4 all you need is to set the "default" value and "blank=False" on the choices field</p>
<pre><code>class MyModel(models.Model):
CHOICES = (
(0, 'A'),
(1, 'B'),
)
choice_field = models.IntegerField(choices=CHOICES, blank=False, default=0)
</code></pre>
| 8
|
2012-07-30T12:50:51Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
Customize/remove Django select box blank option
| 739,260
|
<p>I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:</p>
<pre><code><option value="">---------</option>
</code></pre>
<p>What I'd like to know is:</p>
<ol>
<li>What is the cleanest way to remove this auto-generated option from the select box? </li>
<li><p>What is the cleanest way to customize it so that it shows as:</p>
<pre><code><option value="">Select Item</option>
</code></pre></li>
</ol>
<p>In searching for a solution I came across <a href="http://code.djangoproject.com/ticket/4653">Django ticket 4653</a> which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.</p>
<p>Thanks for any help,</p>
<p>Jeff</p>
<p>Edit: I've configured the ForeignKey field as such: </p>
<pre><code>verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)
</code></pre>
<p>This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.</p>
| 58
|
2009-04-11T00:43:58Z
| 16,251,228
|
<p>you can do this in admin:</p>
<pre><code>formfield_overrides = {
models.ForeignKey: {'empty_label': None},
}
</code></pre>
| 5
|
2013-04-27T10:52:25Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
Customize/remove Django select box blank option
| 739,260
|
<p>I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:</p>
<pre><code><option value="">---------</option>
</code></pre>
<p>What I'd like to know is:</p>
<ol>
<li>What is the cleanest way to remove this auto-generated option from the select box? </li>
<li><p>What is the cleanest way to customize it so that it shows as:</p>
<pre><code><option value="">Select Item</option>
</code></pre></li>
</ol>
<p>In searching for a solution I came across <a href="http://code.djangoproject.com/ticket/4653">Django ticket 4653</a> which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.</p>
<p>Thanks for any help,</p>
<p>Jeff</p>
<p>Edit: I've configured the ForeignKey field as such: </p>
<pre><code>verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)
</code></pre>
<p>This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.</p>
| 58
|
2009-04-11T00:43:58Z
| 21,071,876
|
<p>I was messing around with this today and just came up with a <s>coward hack</s> nifty solution:</p>
<pre><code># Cowardly handle ModelChoiceField empty label
# we all hate that '-----' thing
class ModelChoiceField_init_hack(object):
@property
def empty_label(self):
return self._empty_label
@empty_label.setter
def empty_label(self, value):
self._empty_label = value
if value and value.startswith('-'):
self._empty_label = 'Select an option'
ModelChoiceField.__bases__ += (ModelChoiceField_init_hack,)
</code></pre>
<p>Now you can tweak the default <code>ModelChoiceField</code> empty label to anything you'd like. :-)</p>
<p>PS: No need for downvotes, non-harmful monkey patches are always handy.</p>
| 2
|
2014-01-12T06:13:41Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
Customize/remove Django select box blank option
| 739,260
|
<p>I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:</p>
<pre><code><option value="">---------</option>
</code></pre>
<p>What I'd like to know is:</p>
<ol>
<li>What is the cleanest way to remove this auto-generated option from the select box? </li>
<li><p>What is the cleanest way to customize it so that it shows as:</p>
<pre><code><option value="">Select Item</option>
</code></pre></li>
</ol>
<p>In searching for a solution I came across <a href="http://code.djangoproject.com/ticket/4653">Django ticket 4653</a> which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.</p>
<p>Thanks for any help,</p>
<p>Jeff</p>
<p>Edit: I've configured the ForeignKey field as such: </p>
<pre><code>verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)
</code></pre>
<p>This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.</p>
| 58
|
2009-04-11T00:43:58Z
| 21,785,041
|
<p>I find SOLUTION!!</p>
<p>But not for ForeignKey :-)</p>
<p>Maybe I can help you.
I looked in Django source code and discovered that in django.forms.extras.widgets.SelecteDateWidget() is a property called none_value that equals (0, '-----') so I did in my code this</p>
<pre><code>class StudentForm(ModelForm):
class Meta:
this_year = int(datetime.datetime.today().strftime('%Y'))
birth_years = []
years = []
for year in range(this_year - 2, this_year + 3 ):
years.append(year)
for year in range(this_year - 60, this_year+2):
birth_years.append(year)
model = Student
exclude = ['user', 'fullname']
date_widget = SelectDateWidget(years=years)
date_widget.__setattr__('none_value', (0, 'THERE WAS THAT "-----" NO THERES THIS:-)'))
widgets = {
'beginning': date_widget,
'birth': SelectDateWidget(years=birth_years),
}
</code></pre>
| 1
|
2014-02-14T16:52:00Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
Customize/remove Django select box blank option
| 739,260
|
<p>I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:</p>
<pre><code><option value="">---------</option>
</code></pre>
<p>What I'd like to know is:</p>
<ol>
<li>What is the cleanest way to remove this auto-generated option from the select box? </li>
<li><p>What is the cleanest way to customize it so that it shows as:</p>
<pre><code><option value="">Select Item</option>
</code></pre></li>
</ol>
<p>In searching for a solution I came across <a href="http://code.djangoproject.com/ticket/4653">Django ticket 4653</a> which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.</p>
<p>Thanks for any help,</p>
<p>Jeff</p>
<p>Edit: I've configured the ForeignKey field as such: </p>
<pre><code>verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)
</code></pre>
<p>This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.</p>
| 58
|
2009-04-11T00:43:58Z
| 24,868,776
|
<p>You can use this on your model:</p>
<pre><code>class MyModel(models.Model):
name = CharField('fieldname', max_length=10, default=None)
</code></pre>
<p><strong>default=None</strong> is the answer :D</p>
<p>NOTE: I tried this on Django 1.7</p>
| 12
|
2014-07-21T15:22:22Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
Customize/remove Django select box blank option
| 739,260
|
<p>I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:</p>
<pre><code><option value="">---------</option>
</code></pre>
<p>What I'd like to know is:</p>
<ol>
<li>What is the cleanest way to remove this auto-generated option from the select box? </li>
<li><p>What is the cleanest way to customize it so that it shows as:</p>
<pre><code><option value="">Select Item</option>
</code></pre></li>
</ol>
<p>In searching for a solution I came across <a href="http://code.djangoproject.com/ticket/4653">Django ticket 4653</a> which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.</p>
<p>Thanks for any help,</p>
<p>Jeff</p>
<p>Edit: I've configured the ForeignKey field as such: </p>
<pre><code>verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)
</code></pre>
<p>This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.</p>
| 58
|
2009-04-11T00:43:58Z
| 29,303,202
|
<p>For the latest version of django
the first answer should be like this</p>
<pre><code>class ThingForm(models.ModelForm):
class Meta:
model = Thing
def __init__(self, *args, **kwargs):
self.base_fields['cargo'].empty_label = None
super(ThingForm, self).__init__(*args, **kwargs)`
</code></pre>
| 2
|
2015-03-27T14:33:39Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
Customize/remove Django select box blank option
| 739,260
|
<p>I'm using Django 1.0.2. I've written a ModelForm backed by a Model. This model has a ForeignKey where blank=False. When Django generates HTML for this form it creates a select box with one option for each row in the table referenced by the ForeignKey. It also creates an option at the top of the list that has no value and displays as a series of dashes:</p>
<pre><code><option value="">---------</option>
</code></pre>
<p>What I'd like to know is:</p>
<ol>
<li>What is the cleanest way to remove this auto-generated option from the select box? </li>
<li><p>What is the cleanest way to customize it so that it shows as:</p>
<pre><code><option value="">Select Item</option>
</code></pre></li>
</ol>
<p>In searching for a solution I came across <a href="http://code.djangoproject.com/ticket/4653">Django ticket 4653</a> which gave me the impression that others had the same question and that the default behavior of Django may have been modified. This ticket is over a year old so I was hoping there might be a cleaner way to accomplish these things.</p>
<p>Thanks for any help,</p>
<p>Jeff</p>
<p>Edit: I've configured the ForeignKey field as such: </p>
<pre><code>verb = models.ForeignKey(Verb, blank=False, default=get_default_verb)
</code></pre>
<p>This does set the default so that it's no longer the empty/dashes option but unfortunately it doesn't seem to resolve either of my questions. That is, the empty/dashes option still appears in the list.</p>
| 58
|
2009-04-11T00:43:58Z
| 30,421,758
|
<p><code>self.fields['xxx'].empty_value = None</code> would not work If you field type is <code>TypedChoiceField</code> which do not have <code>empty_label</code> property.</p>
<p>What we should do is to remove first choice:</p>
<p>1 . If you want to build a <code>BaseForm</code> auto detect <code>TypedChoiceField</code></p>
<pre><code>class BaseForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(BaseForm, self).__init__(*args, **kwargs)
for field_name in self.fields:
field = self.fields.get(field_name)
if field and isinstance(field , forms.TypedChoiceField):
field.choices = field.choices[1:]
# code to process other Field
# ....
class AddClientForm(BaseForm):
pass
</code></pre>
<p>2.only a few form, you can use:</p>
<pre><code>class AddClientForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(AddClientForm, self).__init__(*args, **kwargs)
self.fields['xxx'].choices = self.fields['xxx'].choices[1:]
</code></pre>
| 3
|
2015-05-24T09:03:09Z
|
[
"python",
"django",
"django-models",
"django-forms"
] |
QFileDialog passing directory to python script
| 739,288
|
<p>Im writing a little python program that goes through an XML file and does some replacement of tags. It takes three arguments, a path from whcih it creates a directory tree, the XML file its reading and the xml file its outputting to. It works fine from the command line just passing in arguments. As its not just for me, i thought id put a Qt front on it. Below is the majority of the Qt front. MOVtoMXF is the class that does all the replacement. So you can see that im basically just grabbing strings and feeding them into the class that ive already made and tested.</p>
<pre><code>class Form(QDialog):
def ConnectButtons(self):
self.connect(self.pathBrowseB, SIGNAL("clicked()"), self.pathFileBrowse)
self.connect(self.xmlFileBrowseB, SIGNAL("clicked()"), self.xmlFileBrowse)
self.connect(self.outputFileBrowseB, SIGNAL("clicked()"), self.outputFileBrowse)
def accept(self):
path = self.pathBox.displayText()
xmlFile = self.xmlFileBox.displayText()
outFileName = self.outfileNameBox.displayText()
print path + " " + xmlFile + " " + outFileName
mov1 = MOVtoMXF.MOVtoMXF(path, xmlFile, outFileName)
mov1.ScanFile()
self.done()
def pathFileBrowse(self):
file = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
self.pathBox.setText(file)
def xmlFileBrowse(self):
file = str(QFileDialog.getOpenFileName(self, "Save File"))
self.xmlFileBox.setText(file)
def outputFileBrowse(self):
file = str(QFileDialog.getSaveFileName(self, "Save File"))
self.outfileNameBox.setText(file)
</code></pre>
<p>the probelm is that when i feed in a Path, it now comes back with an error, either the directory doesnt exist, or if I have a trailing slash on the end that </p>
<p>File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.py", line 62, in join
elif path == '' or path.endswith('/'):</p>
<p>I think its probably some mismatch between the QFileDialog, the QString its passing back and the string the my python expects. but im not sure how to go about fixing it.</p>
<p>Im running on Max OS X 10.5.6
pyQt 4.4.4
QT 4.4.0</p>
<p>thanks for any help you can give.</p>
<p>Mark</p>
| 1
|
2009-04-11T01:00:10Z
| 739,332
|
<p>Two potential solutions.</p>
<p>Method 1:</p>
<p>If you must use the displayText() method, I suggest you wrap the call to displayText() with an explicit string cast:</p>
<pre><code>path = str(self.pathBox.displayText())
xmlFile = str(self.xmlFileBox.displayText())
outFileName = str(self.outfileNameBox.displayText())
</code></pre>
<p>The reason is that displayText() returns what I believe is a constant memory reference at the C++ level, meaning that you are not being returned a copy of the QString, but actually whatever QString is available at the memory reference. </p>
<p>When you call the displayText() function, it is the string you expected, but eventually it is something else when the contents at the memory reference are changed. I have noticed this peculiarity with several methods on different controls, most notably QDateEdit/QDateTimeEdit/QTimeEdit controls, where I typically have to make an explicit copy of, say, the QDate returned by the date() function of QDateEdit by wrapping it in a QDate constructor. </p>
<p>Method 2:</p>
<p>Otherwise, use the text() method instead. The QString returned is a constant value, instead of a constant memory reference. See this doc:</p>
<p><a href="http://doc.trolltech.com/4.4/qlineedit.html#text-prop" rel="nofollow">http://doc.trolltech.com/4.4/qlineedit.html#text-prop</a></p>
<pre><code>displayText : const QString
text : QString
</code></pre>
<p><strong>Update:</strong></p>
<p>It looks like Riverbank will be addressing this problem in future versions of PyQt in case anybody is still having this problem:</p>
<p><a href="http://www.riverbankcomputing.co.uk/software/pyqt/roadmap/index.html#implicit-copying-of-const" rel="nofollow">PyQt4 Roadmap</a></p>
<blockquote>
<p>Implicit Copying of const&</p>
<p>Implemented in current snapshots.</p>
<p>When PyQt wraps a const& value
returned by a C++ function it wraps
the address of the value itself. Also,
it does not enforce the const
attribute. This can cause unexpected
behavour (and program crashes) either
by the underlying value disappearing
or the value being unexpectedly
modified.</p>
<p>The correct way to handle this is to
explicitly make a copy of the value
using its type's copy constructor.
However, that is not Pythonic and
knowing that it needs to be done
requires knowledge of the C++ API.</p>
<p>PyQt will be changed so that it will
automatically invoke the copy
constructor and will wrap the copy.</p>
</blockquote>
| 1
|
2009-04-11T01:30:27Z
|
[
"python",
"qt",
"parsing",
"pyqt",
"qfile"
] |
Why is my send_mail() command not working in Django?
| 739,289
|
<p>I put the following in my settings.py file. The email address there is a test one. I found the email settings from <a href="https://help.webfaction.com/index.php?%5Fm=knowledgebase&%5Fa=viewarticle&kbarticleid=128&nav=0,3" rel="nofollow">Webfaction</a>'s site: </p>
<pre><code>EMAIL_HOST = 'smtp.webfaction.com'
EMAIL_HOST_USER = 'hekevintran_test'
EMAIL_HOST_PASSWORD = 'testpass'
EMAIL_PORT = 465
EMAIL_USE_TLS = True
</code></pre>
<p>This is what my file looks like:</p>
<pre><code>from django.core.mail import send_mail
send_mail(subject='subject',
message='message',
from_email='hekevintran_test@webfaction.com',
recipient_list=['recipient@yahoo.com'],
fail_silently=False)
</code></pre>
<p>When I run the above it stalls a long time and then gives me this error:</p>
<pre><code>SMTPServerDisconnected: Connection unexpectedly closed
</code></pre>
<p>What am I doing wrong?</p>
| 4
|
2009-04-11T01:00:40Z
| 739,291
|
<p>I have a Django project on Webfaction right now that is properly sending emails. The only difference between your settings and mine is that I did not specify <code>EMAIL_PORT</code> or <code>EMAIL_USE_TLS</code>. Try it out without those settings and let Django use the default it has and see if it works.</p>
<p>For reference's sake, <a href="http://docs.djangoproject.com/en/dev/ref/settings/#email-port">the default settings</a> are:</p>
<pre><code>EMAIL_PORT = 25
EMAIL_USE_TLS = False
</code></pre>
| 11
|
2009-04-11T01:04:03Z
|
[
"python",
"django",
"email"
] |
Why is my send_mail() command not working in Django?
| 739,289
|
<p>I put the following in my settings.py file. The email address there is a test one. I found the email settings from <a href="https://help.webfaction.com/index.php?%5Fm=knowledgebase&%5Fa=viewarticle&kbarticleid=128&nav=0,3" rel="nofollow">Webfaction</a>'s site: </p>
<pre><code>EMAIL_HOST = 'smtp.webfaction.com'
EMAIL_HOST_USER = 'hekevintran_test'
EMAIL_HOST_PASSWORD = 'testpass'
EMAIL_PORT = 465
EMAIL_USE_TLS = True
</code></pre>
<p>This is what my file looks like:</p>
<pre><code>from django.core.mail import send_mail
send_mail(subject='subject',
message='message',
from_email='hekevintran_test@webfaction.com',
recipient_list=['recipient@yahoo.com'],
fail_silently=False)
</code></pre>
<p>When I run the above it stalls a long time and then gives me this error:</p>
<pre><code>SMTPServerDisconnected: Connection unexpectedly closed
</code></pre>
<p>What am I doing wrong?</p>
| 4
|
2009-04-11T01:00:40Z
| 4,707,876
|
<p>I had this problem with my hosted account at asmallorange.com. There, it was a firewall problem. I would suggest contacting support and ensuring port 465 can get through the firewall. </p>
| 1
|
2011-01-16T20:35:30Z
|
[
"python",
"django",
"email"
] |
Why is my send_mail() command not working in Django?
| 739,289
|
<p>I put the following in my settings.py file. The email address there is a test one. I found the email settings from <a href="https://help.webfaction.com/index.php?%5Fm=knowledgebase&%5Fa=viewarticle&kbarticleid=128&nav=0,3" rel="nofollow">Webfaction</a>'s site: </p>
<pre><code>EMAIL_HOST = 'smtp.webfaction.com'
EMAIL_HOST_USER = 'hekevintran_test'
EMAIL_HOST_PASSWORD = 'testpass'
EMAIL_PORT = 465
EMAIL_USE_TLS = True
</code></pre>
<p>This is what my file looks like:</p>
<pre><code>from django.core.mail import send_mail
send_mail(subject='subject',
message='message',
from_email='hekevintran_test@webfaction.com',
recipient_list=['recipient@yahoo.com'],
fail_silently=False)
</code></pre>
<p>When I run the above it stalls a long time and then gives me this error:</p>
<pre><code>SMTPServerDisconnected: Connection unexpectedly closed
</code></pre>
<p>What am I doing wrong?</p>
| 4
|
2009-04-11T01:00:40Z
| 31,158,592
|
<p>I had this problem too. I deleted EMAIL_PORT and set EMAIL_USE_TLS = True. Now it is work.</p>
| 0
|
2015-07-01T10:18:57Z
|
[
"python",
"django",
"email"
] |
Organizing a large Python project that must share an internal state?
| 739,311
|
<p>I'm currently in the middle of porting a fairly large Perl The problem is that it uses little Perl tricks to make its code available for <code>use</code>ing. I've done about the same with Python, making the codebase one big module for <code>import</code>ing. I've had a firm grasp of Python for a long time, but I have no experience with large projects written in Python that need to access other parts of itself while maintaining an internal state.</p>
<p>I haven't yet tried simply importing the entire thing in one line (<code>import core</code>), but I know I'm currently not doing things in the best of ways. Here's an example from the master script that sets everything in motion:</p>
<pre><code>self.Benchmark = Benchmark(self)
self.Exceptions = Exceptions
self.Settings = Settings(self)
self.Cache = Cache(self)
self.Deal = Deal(self)
self.Utils = Utils(self)
self.FileParsers = FileParsers(self)
self.Network = Network(self)
self.Plugins = Plugins(self)
self.Misc = Misc(self)
</code></pre>
<p>It <em>works</em>, but I'm not happy with it. Right now, the master class script imports each piece of the <code>core</code> module and creates an instance of the contained classes, passing itself as an argument to <code>__init__</code> in those classes. Like so:</p>
<pre><code>class FileParsers:
def __init__(self, parent):
self.parent = parent
</code></pre>
<p>Now the code in that class can access the entire rest of the codebase through the parent class.</p>
<pre><code>self.parent.Settings.loadSysConfig()
</code></pre>
<p>So my question is this: considering the above, what would be the best way to reorganize the project and refactor the code so that it retains its current ability to access everything else? The code is very noncritical, so I'm not <em>that</em> worried about internal data integrity, I just don't like having to go through the parent class in such an ugly way. And those long chains slow the code down as well.</p>
<p>EDIT: Whoops, forgot these: links to the SVN repos for both project. Mine is <a href="http://erok.svn.sf.net/viewvc/erok/trunk/" rel="nofollow">here</a>, and the project I'm porting is <a href="http://openkore.svn.sf.net/viewvc/openkore/openkore/trunk/" rel="nofollow">here</a>.</p>
| 1
|
2009-04-11T01:14:52Z
| 739,320
|
<p>It's really hard to tell without actually being able to see the code, but you should probably just consider importing the items that each module uses, in that module. It's not unusual to have a long list of imports - here's an example from my own website:</p>
<pre><code># standard
import inspect
import linecache
import neo_cgi
import neo_cs
import neo_util
import os
import random
import sys
import time
from _apache import SERVER_RETURN
from mod_python import apache
from mod_python import util
from mod_python.util import FieldStorage
from os.path import dirname, isfile, join, splitext
# set up path
pydir = dirname(__file__)
if pydir not in sys.path:
sys.path.append(pydir)
# things I wrote
import auth
import handlers.accounts, handlers.publish, handlers.standard
import logger
import markup
import programs
import summarize
from auth import check_auth
from common import hdf_iterate, load_hdf_cgi_vars, load_hdf_common_vars
from common import hdf_insert_value, hdf_insert_list, hdf_insert_dict
from handlers import chain, farm, opt
from handlers import URIPrefixFilter
from handlers.standard import TabBarHandler
</code></pre>
<p>and I'm sure a lot of larger modules have even longer lists.</p>
<p>In your case, maybe have a <code>Settings</code> module with a singleton object (or with the settings as module properties) and do</p>
<pre><code>import Settings
</code></pre>
<p>or whatever.</p>
| 1
|
2009-04-11T01:23:40Z
|
[
"python",
"project-management",
"code-organization"
] |
Organizing a large Python project that must share an internal state?
| 739,311
|
<p>I'm currently in the middle of porting a fairly large Perl The problem is that it uses little Perl tricks to make its code available for <code>use</code>ing. I've done about the same with Python, making the codebase one big module for <code>import</code>ing. I've had a firm grasp of Python for a long time, but I have no experience with large projects written in Python that need to access other parts of itself while maintaining an internal state.</p>
<p>I haven't yet tried simply importing the entire thing in one line (<code>import core</code>), but I know I'm currently not doing things in the best of ways. Here's an example from the master script that sets everything in motion:</p>
<pre><code>self.Benchmark = Benchmark(self)
self.Exceptions = Exceptions
self.Settings = Settings(self)
self.Cache = Cache(self)
self.Deal = Deal(self)
self.Utils = Utils(self)
self.FileParsers = FileParsers(self)
self.Network = Network(self)
self.Plugins = Plugins(self)
self.Misc = Misc(self)
</code></pre>
<p>It <em>works</em>, but I'm not happy with it. Right now, the master class script imports each piece of the <code>core</code> module and creates an instance of the contained classes, passing itself as an argument to <code>__init__</code> in those classes. Like so:</p>
<pre><code>class FileParsers:
def __init__(self, parent):
self.parent = parent
</code></pre>
<p>Now the code in that class can access the entire rest of the codebase through the parent class.</p>
<pre><code>self.parent.Settings.loadSysConfig()
</code></pre>
<p>So my question is this: considering the above, what would be the best way to reorganize the project and refactor the code so that it retains its current ability to access everything else? The code is very noncritical, so I'm not <em>that</em> worried about internal data integrity, I just don't like having to go through the parent class in such an ugly way. And those long chains slow the code down as well.</p>
<p>EDIT: Whoops, forgot these: links to the SVN repos for both project. Mine is <a href="http://erok.svn.sf.net/viewvc/erok/trunk/" rel="nofollow">here</a>, and the project I'm porting is <a href="http://openkore.svn.sf.net/viewvc/openkore/openkore/trunk/" rel="nofollow">here</a>.</p>
| 1
|
2009-04-11T01:14:52Z
| 740,312
|
<blockquote>
<p>what would be the best way to reorganize the project and refactor the code so that it retains its current ability to access everything else?</p>
</blockquote>
<p>I think you're actually quite close already, and probably better than many Python projects where they just assume that there is only one instance of the application, and store application-specific values in a module global or singleton.</p>
<p>(This is OK for many simple applications, but really it's nicest to be able to bundle everything up into one Application object that owns all inner classes and methods that need to know the application's state.)</p>
<p>The first thing I would do from the looks of the code above would be to factor out any of those modules and classes that aren't a core competency of your application, things that don't necessarily need access to the application's state. Names like âUtilsâ and âMiscâ sound suspiciously like much of their contents aren't really specific to your app; they could perhaps be refactored out into separate standalone modules, or submodules of your package that only have static functions, stuff not relying on application state.</p>
<p>Next, I would put the main owner Application class in the package's __init__.py rather than a âmaster scriptâ. Then from your run-script or just the interpreter, you can get a complete instance of the application as simply as:</p>
<pre><code>import myapplication
a= myapplication.Application()
</code></pre>
<p>You could also consider moving any basic deployment settings from the Settings class into the initialiser:</p>
<pre><code>a= myapplication.Application(basedir= '/opt/myapp', site= 'www.example.com', debug= False)
</code></pre>
<p>(If you only have one possible set of settings and every time you instantiate Application() you get the same one, there's little use in having all this ability to encapsulate your whole application; you might as well simply be using module globals.)</p>
<p>What I'm doing with some of my apps is making the owned classes monkey-patch themselves into actual members of the owner application object:</p>
<pre><code># myapplication/__init__.py
class Application(object):
def __init__(self, dbfactory, debug):
# ...
self.mailer= self.Mailer(self)
self.webservice= self.Webservice(self)
# ...
import myapplication.mailer, myapplication.webservice
# myapplication/mailer.py
import myapplication
class Mailer(object):
def __init__(self, owner):
self.owner= owner
def send(self, message, recipients):
# ...
myapplication.Application.Mailer= Mailer
</code></pre>
<p>Then it's possible to extend, change or configure the Application from outside it by replacing/subclassing the inner classes:</p>
<pre><code>import myapplication
class MockApplication(myapplication.Application):
class Mailer(myapplication.Application.Mailer):
def send(self, message, recipients):
self.owner.log('Mail send called (not actually sent)')
return True
</code></pre>
<blockquote>
<p>I'm not that worried about internal data integrity</p>
</blockquote>
<p>Well no, this is Python not Java: we don't worry too much about Evil Programmers using properties and methods they shouldn't, we just put â_â at the start of the name and let that be a suitable warning to all.</p>
<blockquote>
<p>And those long chains slow the code down as well.</p>
</blockquote>
<p>Not really noticeably. Readability is the important factor; anything else is premature optimisation.</p>
| 1
|
2009-04-11T15:35:41Z
|
[
"python",
"project-management",
"code-organization"
] |
Easiest way to generate localization files
| 739,314
|
<p>I'm currently writing an app in Python and need to provide localization for it. </p>
<p>I can use gettext and the utilities that come with it to generate .po and .mo files. But editing the .po files for each language, one-by-one, seems a bit tedious. Then, creating directories for each language and generating the .mo files, one-by-one, seems like overkill. The end result being something like: </p>
<pre><code>/en_US/LC_MESSAGES/en_US.mo
/en_CA/LC_MESSAGES/en_CA.mo
etc.
</code></pre>
<p>I could be wrong, but it seems like there's got to be a better way to do this. Does anyone have any tools, tricks or general knowledge that I haven't found yet?</p>
<p>Thanks in advance!</p>
<p>EDIT: To be a little more clear, I'm looking for something that speeds up the process. since it's already pretty easy. For example, in .NET, I can generate all of the strings that need to be translated into an excel file. Then, translators can fill out the excel file and add columns for each language. Then, I can use xls2resx to generate the language resource files. Is there anything like that for gettext? I realize I could write a script to create and read from a csv and generate the files -- I was just hoping there is something already made.</p>
| 19
|
2009-04-11T01:16:14Z
| 739,415
|
<p>It eludes me how you want to achieve a real translation without editing the .po files for each language? Magic?</p>
<p>Edit (after comment) - how to automate the generation of the <strong>.po</strong> files:</p>
<p>I don't use Gettext, but from the <a href="http://en.wikipedia.org/wiki/Gettext" rel="nofollow">wiki page</a> it looks like you only have to call</p>
<blockquote>
<p>msginit --locale=xx --input=name.pot</p>
</blockquote>
<p>for every language you want to support. I would generate a script that generates all the language files, give them to the translators, and when you get them back run <strong>msgfmt</strong> on them.</p>
| 4
|
2009-04-11T02:49:57Z
|
[
"python",
"localization",
"internationalization",
"translation"
] |
Easiest way to generate localization files
| 739,314
|
<p>I'm currently writing an app in Python and need to provide localization for it. </p>
<p>I can use gettext and the utilities that come with it to generate .po and .mo files. But editing the .po files for each language, one-by-one, seems a bit tedious. Then, creating directories for each language and generating the .mo files, one-by-one, seems like overkill. The end result being something like: </p>
<pre><code>/en_US/LC_MESSAGES/en_US.mo
/en_CA/LC_MESSAGES/en_CA.mo
etc.
</code></pre>
<p>I could be wrong, but it seems like there's got to be a better way to do this. Does anyone have any tools, tricks or general knowledge that I haven't found yet?</p>
<p>Thanks in advance!</p>
<p>EDIT: To be a little more clear, I'm looking for something that speeds up the process. since it's already pretty easy. For example, in .NET, I can generate all of the strings that need to be translated into an excel file. Then, translators can fill out the excel file and add columns for each language. Then, I can use xls2resx to generate the language resource files. Is there anything like that for gettext? I realize I could write a script to create and read from a csv and generate the files -- I was just hoping there is something already made.</p>
| 19
|
2009-04-11T01:16:14Z
| 739,522
|
<p>I'm using <a href="http://www.poedit.net/" rel="nofollow">poEdit</a> for translations.</p>
| 1
|
2009-04-11T04:28:23Z
|
[
"python",
"localization",
"internationalization",
"translation"
] |
Easiest way to generate localization files
| 739,314
|
<p>I'm currently writing an app in Python and need to provide localization for it. </p>
<p>I can use gettext and the utilities that come with it to generate .po and .mo files. But editing the .po files for each language, one-by-one, seems a bit tedious. Then, creating directories for each language and generating the .mo files, one-by-one, seems like overkill. The end result being something like: </p>
<pre><code>/en_US/LC_MESSAGES/en_US.mo
/en_CA/LC_MESSAGES/en_CA.mo
etc.
</code></pre>
<p>I could be wrong, but it seems like there's got to be a better way to do this. Does anyone have any tools, tricks or general knowledge that I haven't found yet?</p>
<p>Thanks in advance!</p>
<p>EDIT: To be a little more clear, I'm looking for something that speeds up the process. since it's already pretty easy. For example, in .NET, I can generate all of the strings that need to be translated into an excel file. Then, translators can fill out the excel file and add columns for each language. Then, I can use xls2resx to generate the language resource files. Is there anything like that for gettext? I realize I could write a script to create and read from a csv and generate the files -- I was just hoping there is something already made.</p>
| 19
|
2009-04-11T01:16:14Z
| 740,425
|
<p>Use scripts. Assume your source code is in the directory $SRC, so create directory $SRC/po for i18n files (pot, po, mo etc). Then create file $SRC/po/POTFILES.in where specify path to source code files with gettext function calls. It may look like:</p>
<pre><code>[encoding: UTF-8]
./main.cpp
./plugins/list.cpp
</code></pre>
<p>Now you can use the following commands (inside directory $SRC):</p>
<p>For updating master-file messages.pot:</p>
<pre><code>intltool-update --pot --gettext-package=messages --verbose
</code></pre>
<p>For merging changes from messages.pot to fr.po file, for example:</p>
<pre><code>msgmerge -U fr.po messages.pot
</code></pre>
<p>To generate mo file use command:</p>
<pre><code>msgmerge -o - fr.po messages.pot | msgfmt -c -o fr/LC_MESSAGES/programname.mo -
</code></pre>
<p>Of course directory fr/LC_MESSAGES/ must be created before that call, you can also delete existing fr/LC_MESSAGES/programname.mo before execution</p>
<p>In order to speed up process place all such commands into the corresponding .sh-files for example.</p>
| 3
|
2009-04-11T17:01:27Z
|
[
"python",
"localization",
"internationalization",
"translation"
] |
Easiest way to generate localization files
| 739,314
|
<p>I'm currently writing an app in Python and need to provide localization for it. </p>
<p>I can use gettext and the utilities that come with it to generate .po and .mo files. But editing the .po files for each language, one-by-one, seems a bit tedious. Then, creating directories for each language and generating the .mo files, one-by-one, seems like overkill. The end result being something like: </p>
<pre><code>/en_US/LC_MESSAGES/en_US.mo
/en_CA/LC_MESSAGES/en_CA.mo
etc.
</code></pre>
<p>I could be wrong, but it seems like there's got to be a better way to do this. Does anyone have any tools, tricks or general knowledge that I haven't found yet?</p>
<p>Thanks in advance!</p>
<p>EDIT: To be a little more clear, I'm looking for something that speeds up the process. since it's already pretty easy. For example, in .NET, I can generate all of the strings that need to be translated into an excel file. Then, translators can fill out the excel file and add columns for each language. Then, I can use xls2resx to generate the language resource files. Is there anything like that for gettext? I realize I could write a script to create and read from a csv and generate the files -- I was just hoping there is something already made.</p>
| 19
|
2009-04-11T01:16:14Z
| 930,620
|
<p>You can try <a href="http://toolkit.translatehouse.org/" rel="nofollow">Translate Toolkit</a> for various po file conversions(po2csv for example). Child projects <a href="http://pootle.translatehouse.org/" rel="nofollow">Pootle</a> allows to manage translations over the web.</p>
| 3
|
2009-05-30T21:05:20Z
|
[
"python",
"localization",
"internationalization",
"translation"
] |
Easiest way to generate localization files
| 739,314
|
<p>I'm currently writing an app in Python and need to provide localization for it. </p>
<p>I can use gettext and the utilities that come with it to generate .po and .mo files. But editing the .po files for each language, one-by-one, seems a bit tedious. Then, creating directories for each language and generating the .mo files, one-by-one, seems like overkill. The end result being something like: </p>
<pre><code>/en_US/LC_MESSAGES/en_US.mo
/en_CA/LC_MESSAGES/en_CA.mo
etc.
</code></pre>
<p>I could be wrong, but it seems like there's got to be a better way to do this. Does anyone have any tools, tricks or general knowledge that I haven't found yet?</p>
<p>Thanks in advance!</p>
<p>EDIT: To be a little more clear, I'm looking for something that speeds up the process. since it's already pretty easy. For example, in .NET, I can generate all of the strings that need to be translated into an excel file. Then, translators can fill out the excel file and add columns for each language. Then, I can use xls2resx to generate the language resource files. Is there anything like that for gettext? I realize I could write a script to create and read from a csv and generate the files -- I was just hoping there is something already made.</p>
| 19
|
2009-04-11T01:16:14Z
| 931,287
|
<p>My suggestion is <a href="http://code.google.com/p/django-rosetta/" rel="nofollow">django-rosetta</a>, which gives you a web based interface to editing your translations. Django doesn't need to be involved at all with your app, you're just using it for an online .PO edit facility.</p>
<p>Another interesting new translation site, which I believe was built using Django/Pinax is <a href="http://www.transifex.net/" rel="nofollow">Transifex</a>, although I'm not sure if it allows direct editing of the .PO files.</p>
| 1
|
2009-05-31T04:43:41Z
|
[
"python",
"localization",
"internationalization",
"translation"
] |
Easiest way to generate localization files
| 739,314
|
<p>I'm currently writing an app in Python and need to provide localization for it. </p>
<p>I can use gettext and the utilities that come with it to generate .po and .mo files. But editing the .po files for each language, one-by-one, seems a bit tedious. Then, creating directories for each language and generating the .mo files, one-by-one, seems like overkill. The end result being something like: </p>
<pre><code>/en_US/LC_MESSAGES/en_US.mo
/en_CA/LC_MESSAGES/en_CA.mo
etc.
</code></pre>
<p>I could be wrong, but it seems like there's got to be a better way to do this. Does anyone have any tools, tricks or general knowledge that I haven't found yet?</p>
<p>Thanks in advance!</p>
<p>EDIT: To be a little more clear, I'm looking for something that speeds up the process. since it's already pretty easy. For example, in .NET, I can generate all of the strings that need to be translated into an excel file. Then, translators can fill out the excel file and add columns for each language. Then, I can use xls2resx to generate the language resource files. Is there anything like that for gettext? I realize I could write a script to create and read from a csv and generate the files -- I was just hoping there is something already made.</p>
| 19
|
2009-04-11T01:16:14Z
| 1,079,473
|
<p>I've just done this for a project I'm working on, for us the process is like this:</p>
<p>First, I have a POTFILES.in file which contains a list of source files needing translation. We actually have two files (e.g. admin.in and user.in), as the admin interface doesn't always need translating. So we can send translators only the file containing strings the users see.</p>
<p>Running the following command will create a .pot template from the POTFILES.in:</p>
<pre><code>xgettext --files-from=POTFILES.in --directory=.. --output=messages.pot
</code></pre>
<p>Run the above command from the po/ directory, which should be a subdirectory of your project and contain the POTFILES.in file. The .pot file has the exact same format as a .po file, but it is a template containing no translations. You create a new template whenever new translatable strings have been added to your source files.</p>
<p>To update the already translated .po files and add new strings to them, run:</p>
<pre><code>msgmerge --update --no-fuzzy-matching --backup=off da.po messages.pot
</code></pre>
<p>In the above example I disable fuzzy matching, as our strings are a mess and it did more harm than good. I also disabled backup files, as everything is in subversion here. Run the above command for each language, in this case I updated the danish translation.</p>
<p>Finally run msgfmt to create the .mo files from the .po files:</p>
<pre><code>msgfmt nl.po --output-file nl.mo
</code></pre>
<p>Ofcourse, you wouldn't want to run this manually everytime, so create some scripts (or preferably one or more Makefiles) to do this for you.</p>
<p>Note that your directory layout is slightly different from my situation, so you will have to adjust output filenames/paths a bit, but the steps should be the same.</p>
| 20
|
2009-07-03T13:55:24Z
|
[
"python",
"localization",
"internationalization",
"translation"
] |
Easiest way to generate localization files
| 739,314
|
<p>I'm currently writing an app in Python and need to provide localization for it. </p>
<p>I can use gettext and the utilities that come with it to generate .po and .mo files. But editing the .po files for each language, one-by-one, seems a bit tedious. Then, creating directories for each language and generating the .mo files, one-by-one, seems like overkill. The end result being something like: </p>
<pre><code>/en_US/LC_MESSAGES/en_US.mo
/en_CA/LC_MESSAGES/en_CA.mo
etc.
</code></pre>
<p>I could be wrong, but it seems like there's got to be a better way to do this. Does anyone have any tools, tricks or general knowledge that I haven't found yet?</p>
<p>Thanks in advance!</p>
<p>EDIT: To be a little more clear, I'm looking for something that speeds up the process. since it's already pretty easy. For example, in .NET, I can generate all of the strings that need to be translated into an excel file. Then, translators can fill out the excel file and add columns for each language. Then, I can use xls2resx to generate the language resource files. Is there anything like that for gettext? I realize I could write a script to create and read from a csv and generate the files -- I was just hoping there is something already made.</p>
| 19
|
2009-04-11T01:16:14Z
| 9,442,227
|
<p>You can use <a href="https://www.transifex.net/">Transifex</a>, used by quite a few Python projects (Django, Mercurial). It has a web-based editor and command-line client for automation and also supports .NET, if that can be of help.</p>
<p>Disclaimer: I'm the Transifex project lead.</p>
| 6
|
2012-02-25T07:34:13Z
|
[
"python",
"localization",
"internationalization",
"translation"
] |
Parsing specific elements out of a very large HTML file
| 739,325
|
<p>I have a very large HTML file (several megabytes). I know the data I want is under something like <code><div class=someName>here</div></code></p>
<p>What is a good library to parse through the HTML page so I can loop through elements and grab each <code>someName</code>? I want to do this in either C#, Python or C++.</p>
| 1
|
2009-04-11T01:26:22Z
| 739,329
|
<p>Xerces is well documented, supported and tested. (C++)</p>
<p><a href="http://xerces.apache.org/xerces-c/" rel="nofollow">http://xerces.apache.org/xerces-c/</a></p>
<p>(yes, it's an XML parser but it should do the trick)</p>
| 1
|
2009-04-11T01:29:01Z
|
[
"c#",
"c++",
"python",
"html",
"parsing"
] |
Parsing specific elements out of a very large HTML file
| 739,325
|
<p>I have a very large HTML file (several megabytes). I know the data I want is under something like <code><div class=someName>here</div></code></p>
<p>What is a good library to parse through the HTML page so I can loop through elements and grab each <code>someName</code>? I want to do this in either C#, Python or C++.</p>
| 1
|
2009-04-11T01:26:22Z
| 739,330
|
<p>I would use Python and <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> for the job. It is very solid at handling this kind of stuff.</p>
<p>For your case, you can use <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Improving%20Performance%20by%20Parsing%20Only%20Part%20of%20the%20Document" rel="nofollow">SoupStrainer</a> to make BeautifulSoup only parse DIVs in the document that have the class you want, so it doesn't have to have the whole thing in memory.</p>
<p>For example, say your document looks like this:</p>
<pre><code><div class="test">Hello World</div>
<div class="hello">Aloha World</div>
<div>Hey There</div>
</code></pre>
<p>You can write this:</p>
<pre><code>>>> from BeautifulSoup import BeautifulSoup, SoupStrainer
>>> doc = '''
... <div class="test">Hello World</div>
... <div class="hello">Aloha World</div>
... <div>Hey There</div>
... '''
>>> findDivs = SoupStrainer('div', {'class':'hello'})
>>> [tag for tag in BeautifulSoup(doc, parseOnlyThese=findDivs)]
[<div class="hello">Aloha World</div>]
</code></pre>
| 13
|
2009-04-11T01:29:21Z
|
[
"c#",
"c++",
"python",
"html",
"parsing"
] |
Parsing specific elements out of a very large HTML file
| 739,325
|
<p>I have a very large HTML file (several megabytes). I know the data I want is under something like <code><div class=someName>here</div></code></p>
<p>What is a good library to parse through the HTML page so I can loop through elements and grab each <code>someName</code>? I want to do this in either C#, Python or C++.</p>
| 1
|
2009-04-11T01:26:22Z
| 739,340
|
<p>The <a href="http://www.codeplex.com/htmlagilitypack" rel="nofollow">Html Agility Pack</a> is a stellar option if you want to use C#</p>
| 3
|
2009-04-11T01:37:30Z
|
[
"c#",
"c++",
"python",
"html",
"parsing"
] |
Parsing specific elements out of a very large HTML file
| 739,325
|
<p>I have a very large HTML file (several megabytes). I know the data I want is under something like <code><div class=someName>here</div></code></p>
<p>What is a good library to parse through the HTML page so I can loop through elements and grab each <code>someName</code>? I want to do this in either C#, Python or C++.</p>
| 1
|
2009-04-11T01:26:22Z
| 739,851
|
<p>Sounds like a case for good old regular expressions.</p>
<p>Input:</p>
<pre><code><div class="test">Hello World</div>
<div class="somename">Aloha World</div>
<div>Hey There</div>
</code></pre>
<p>RegEx:</p>
<pre><code>\<div\sclass\=\"somename\"\>(?<Text>.*?)\<\/div\>
</code></pre>
<p>Yields:</p>
<pre><code>Aloha World (note: In a single group named Text)
</code></pre>
<p>Probably need to account for enclosing quotes missing etc...</p>
<p>Although with regular expressions now you have <a href="http://www.codinghorror.com/blog/archives/001016.html" rel="nofollow">two problems</a>.</p>
| 1
|
2009-04-11T10:42:33Z
|
[
"c#",
"c++",
"python",
"html",
"parsing"
] |
Parsing specific elements out of a very large HTML file
| 739,325
|
<p>I have a very large HTML file (several megabytes). I know the data I want is under something like <code><div class=someName>here</div></code></p>
<p>What is a good library to parse through the HTML page so I can loop through elements and grab each <code>someName</code>? I want to do this in either C#, Python or C++.</p>
| 1
|
2009-04-11T01:26:22Z
| 741,919
|
<p>Give <a href="http://www.grinninglizard.com/tinyxml/" rel="nofollow">TinyXML</a> a try. (C++ XML parser)</p>
| 0
|
2009-04-12T15:07:07Z
|
[
"c#",
"c++",
"python",
"html",
"parsing"
] |
Google App Engine: Intro to their Data Store API for people with SQL Background?
| 739,490
|
<p>Does anyone have any good information aside from the Google App Engine docs provided by Google that gives a good overview for people with MS SQL background to porting their knowledge and using Google App Engine Data Store API effectively.</p>
<p>For Example, if you have a self created Users Table and a Message Table</p>
<p>Where there is a relationship between Users and Message (connected by the UserID), how would this structure be represented in Google App Engine?</p>
<pre><code>SELECT * FROM Users INNER JOIN Message ON Users.ID = Message.UserID
</code></pre>
| 7
|
2009-04-11T04:00:13Z
| 739,501
|
<p>Here is a good link: One to Many Join using Google App Engine.</p>
<p><a href="http://blog.arbingersys.com/2008/04/google-app-engine-one-to-many-join.html" rel="nofollow">http://blog.arbingersys.com/2008/04/google-app-engine-one-to-many-join.html</a></p>
<p>Here is another good link: Many to Many Join using Google App Engine:</p>
<p><a href="http://blog.arbingersys.com/2008/04/google-app-engine-many-to-many-join.html" rel="nofollow">http://blog.arbingersys.com/2008/04/google-app-engine-many-to-many-join.html</a></p>
<p>Here is a good discussion regarding the above two links:</p>
<p><a href="http://groups.google.com/group/google-appengine/browse_thread/thread/e9464ceb131c726f/6aeae1e390038592?pli=1" rel="nofollow">http://groups.google.com/group/google-appengine/browse_thread/thread/e9464ceb131c726f/6aeae1e390038592?pli=1</a></p>
<p>Personally I find this comment in the discussion very informative about the Google App Engine Data Store:</p>
<p><a href="http://groups.google.com/group/google-appengine/msg/ee3bd373bd31e2c7" rel="nofollow">http://groups.google.com/group/google-appengine/msg/ee3bd373bd31e2c7</a></p>
<blockquote>
<p>At scale you wind up doing a bunch of
things that seem wrong, but that are
required by the numbers we are
running. Go watch the EBay talks. Or
read the posts about how many database
instances FaceBook is running.</p>
<p>The simple truth is, what we learned
about in uni was great for the
business automation apps of small to
medium enterprise applications, where
the load was predictable, and there
was money enough to buy the server
required to handle the load of 50
people doing data entry into an
accounts or business planning and
control app....</p>
</blockquote>
<p>Searched around a bit more and came across this Google Doc Article:</p>
<p><a href="http://code.google.com/appengine/articles/modeling.html" rel="nofollow">http://code.google.com/appengine/articles/modeling.html</a></p>
<blockquote>
<p>App Engine allows the creation of easy
to use relationships between datastore
entities which can represent
real-world things and ideas. Use
ReferenceProperty when you need to
associate an arbitrary number of
repeated types of information with a
single entity. Use key-lists when you
need to allow lots of different
objects to share other instances
between each other. You will find that
these two approaches will provide you
with most of what you need to create
the model behind great applications.</p>
</blockquote>
| 13
|
2009-04-11T04:08:26Z
|
[
"python",
"sql",
"google-app-engine",
"gql"
] |
Google App Engine: Intro to their Data Store API for people with SQL Background?
| 739,490
|
<p>Does anyone have any good information aside from the Google App Engine docs provided by Google that gives a good overview for people with MS SQL background to porting their knowledge and using Google App Engine Data Store API effectively.</p>
<p>For Example, if you have a self created Users Table and a Message Table</p>
<p>Where there is a relationship between Users and Message (connected by the UserID), how would this structure be represented in Google App Engine?</p>
<pre><code>SELECT * FROM Users INNER JOIN Message ON Users.ID = Message.UserID
</code></pre>
| 7
|
2009-04-11T04:00:13Z
| 884,328
|
<p>I think this is the basics : Keys and Entity Groups
look for it in appengine docs. (I'm new here so can't post a link)</p>
| 1
|
2009-05-19T18:27:09Z
|
[
"python",
"sql",
"google-app-engine",
"gql"
] |
Google App Engine: Intro to their Data Store API for people with SQL Background?
| 739,490
|
<p>Does anyone have any good information aside from the Google App Engine docs provided by Google that gives a good overview for people with MS SQL background to porting their knowledge and using Google App Engine Data Store API effectively.</p>
<p>For Example, if you have a self created Users Table and a Message Table</p>
<p>Where there is a relationship between Users and Message (connected by the UserID), how would this structure be represented in Google App Engine?</p>
<pre><code>SELECT * FROM Users INNER JOIN Message ON Users.ID = Message.UserID
</code></pre>
| 7
|
2009-04-11T04:00:13Z
| 885,244
|
<p>Can I supplement the excellent answer further above with a link to a video:</p>
<p><a href="http://sites.google.com/site/io/building-scalable-web-applications-with-google-app-engine" rel="nofollow">http://sites.google.com/site/io/building-scalable-web-applications-with-google-app-engine</a></p>
<p>It's a great talk by Google's Brett Slatkin who talks for an hour about the special way you need to think about your application before you can expect it to scale well. There are some genuine WTFs (such as no count() in db queries) that will cause you to struggle if you are coming from a relational background.</p>
| 2
|
2009-05-19T21:59:07Z
|
[
"python",
"sql",
"google-app-engine",
"gql"
] |
Google App Engine: Intro to their Data Store API for people with SQL Background?
| 739,490
|
<p>Does anyone have any good information aside from the Google App Engine docs provided by Google that gives a good overview for people with MS SQL background to porting their knowledge and using Google App Engine Data Store API effectively.</p>
<p>For Example, if you have a self created Users Table and a Message Table</p>
<p>Where there is a relationship between Users and Message (connected by the UserID), how would this structure be represented in Google App Engine?</p>
<pre><code>SELECT * FROM Users INNER JOIN Message ON Users.ID = Message.UserID
</code></pre>
| 7
|
2009-04-11T04:00:13Z
| 994,391
|
<p>I have worked on it but not a expert though Google app engine is very good thing and it is the future as it implements Platform as a Service and Software as a Service. Google app engine provides a non- relational database. So you cantreally write relationships here.</p>
<p>Regards,
Gaurav J</p>
| 0
|
2009-06-15T03:18:42Z
|
[
"python",
"sql",
"google-app-engine",
"gql"
] |
Google App Engine: Intro to their Data Store API for people with SQL Background?
| 739,490
|
<p>Does anyone have any good information aside from the Google App Engine docs provided by Google that gives a good overview for people with MS SQL background to porting their knowledge and using Google App Engine Data Store API effectively.</p>
<p>For Example, if you have a self created Users Table and a Message Table</p>
<p>Where there is a relationship between Users and Message (connected by the UserID), how would this structure be represented in Google App Engine?</p>
<pre><code>SELECT * FROM Users INNER JOIN Message ON Users.ID = Message.UserID
</code></pre>
| 7
|
2009-04-11T04:00:13Z
| 1,508,916
|
<p>These links are great, but are predominantly python biased, I am using GWT, and therefore have to use the java flavour of GAE, does anyone have any examples of how to achieve these "join" equivalencies in the java version of GAE?</p>
<p>Cheers,
John</p>
| 0
|
2009-10-02T11:07:57Z
|
[
"python",
"sql",
"google-app-engine",
"gql"
] |
Google App Engine: Intro to their Data Store API for people with SQL Background?
| 739,490
|
<p>Does anyone have any good information aside from the Google App Engine docs provided by Google that gives a good overview for people with MS SQL background to porting their knowledge and using Google App Engine Data Store API effectively.</p>
<p>For Example, if you have a self created Users Table and a Message Table</p>
<p>Where there is a relationship between Users and Message (connected by the UserID), how would this structure be represented in Google App Engine?</p>
<pre><code>SELECT * FROM Users INNER JOIN Message ON Users.ID = Message.UserID
</code></pre>
| 7
|
2009-04-11T04:00:13Z
| 4,263,208
|
<p>The standalone GAE SDK is pretty difficult to use for putting data into and retrieving data from the Google App Engine data store.</p>
<p>"Objectify" is a GAE extension that makes these operations much easier. The Objectify wiki and source code can be found here. I strongly recommend using Objectify in your GAE project.</p>
<p><a href="http://code.google.com/p/objectify-appengine/" rel="nofollow">http://code.google.com/p/objectify-appengine/</a></p>
<p>Here are a couple of tutorials on using Objectify with the app engine. Follow these tutorials and you will be storing and retrieving data in no time.</p>
<p><a href="http://www.fishbonecloud.com/2010/11/use-objectify-to-store-data-in-google.html" rel="nofollow">http://www.fishbonecloud.com/2010/11/use-objectify-to-store-data-in-google.html</a></p>
| 0
|
2010-11-24T03:23:05Z
|
[
"python",
"sql",
"google-app-engine",
"gql"
] |
setattr with kwargs, pythonic or not?
| 739,625
|
<p>I'm using <code>__init__()</code> like this in some SQLAlchemy ORM classes that have many parameters (upto 20).</p>
<pre><code>def __init__(self, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
</code></pre>
<p>Is it "pythonic" to set attributes like this?</p>
| 15
|
2009-04-11T06:31:19Z
| 739,643
|
<p>To me it seems pretty pythonic if you only need this in one place in your code. </p>
<p>The following link provides a more 'generic' approach to the same problem (e.g. with a decorator and some extra functionality), have a look at: <a href="http://code.activestate.com/recipes/551763/" rel="nofollow">http://code.activestate.com/recipes/551763/</a></p>
| 1
|
2009-04-11T06:49:43Z
|
[
"python",
"initialization"
] |
setattr with kwargs, pythonic or not?
| 739,625
|
<p>I'm using <code>__init__()</code> like this in some SQLAlchemy ORM classes that have many parameters (upto 20).</p>
<pre><code>def __init__(self, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
</code></pre>
<p>Is it "pythonic" to set attributes like this?</p>
| 15
|
2009-04-11T06:31:19Z
| 739,873
|
<p>Yes. Another way to do this is.</p>
<pre><code>def __init__(self, **kwargs):
self.__dict__.update( kwargs )
</code></pre>
| 18
|
2009-04-11T11:04:09Z
|
[
"python",
"initialization"
] |
setattr with kwargs, pythonic or not?
| 739,625
|
<p>I'm using <code>__init__()</code> like this in some SQLAlchemy ORM classes that have many parameters (upto 20).</p>
<pre><code>def __init__(self, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
</code></pre>
<p>Is it "pythonic" to set attributes like this?</p>
| 15
|
2009-04-11T06:31:19Z
| 744,161
|
<p>Yes, if there's not a "nicer" way of supplying the arguments.</p>
<p>For example, using your ORM classes you mention, perhaps it would be more Python'y to allow..</p>
<pre><code>col = Varchar()
col.index = True
col.length = 255
</code></pre>
<p>..rather than..</p>
<pre><code>col = Varchar(index = True, length = 255)
</code></pre>
<p>Okay that's not the best example, since the <code>**kwargs</code> method would actually be nicer.. but my point is you should always consider alternative methods of achieving something, before using sometimes-discouraged things like <code>**kwargs</code>..</p>
<p>Another thing to keep in mind is you might lose behaviour a user expects, such as raising a TypeError if the user supplies an invalid keyword arg, which could be worked around like..</p>
<pre><code>def __init__(self, **kwargs):
valid_kwargs = ['x', 'y', 'z']
for k, v in kwargs.iteritems():
if k not in valid_kwargs:
raise TypeError("Invalid keyword argument %s" % k)
setattr(self, k, v)
</code></pre>
<p>A final thing to consider:</p>
<pre><code>class Hmm:
def __init__(self, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
def mymethod(self):
print "mymethod should print this message.."
x = Hmm(mymethod = None)
x.mymethod() # raises TypeError: 'NoneType' object is not callable
</code></pre>
| 4
|
2009-04-13T14:58:48Z
|
[
"python",
"initialization"
] |
Apply multiple negative regex to expression in Python
| 739,651
|
<p>This question is similar to <a href="http://stackoverflow.com/questions/597476/how-to-concisely-cascade-through-multiple-regex-statements-in-python">"How to concisely cascade through multiple regex statements in Python"</a> except instead of matching one regular expression and doing something I need to make sure I do not match a bunch of regular expressions, and if no matches are found (aka I have valid data) then do something. I have found one way to do it but am thinking there must be a better way, especially if I end up with many regular expressions.</p>
<p>Basically I am filtering URL's for bad stuff ("", \\", etc.) that occurs when I yank what looks like a valid URL out of an HTML document but it turns out to be part of a JavaScript (and thus needs to be evaluated, and thus the escaping characters). I can't use Beautiful soup to process these pages since they are far to mangled (actually I use BeautifulSoup, then fall back to my ugly but workable parser). </p>
<p>So far I have found the following works relatively well: I compile a dict or regular expressions outside the main loop (so I only have to compile it once, but benefit from the speed increase every time I use it), I then loop a URL through this dict, if there is a match then the URL is bad, if not the url is good:</p>
<pre><code>regex_bad_url = {"1" : re.compile('\"\"'),
"2" : re.compile('\\\"')}
</code></pre>
<p>Followed by:</p>
<pre><code>url_state = "good"
for key, pattern in regex_bad_url_components.items():
match = re.search(pattern, url)
if (match):
url_state = "bad"
if (url_state == "good"):
# do stuff here ...
</code></pre>
<p>Now the obvious thought is to use regex "or" ("|"), i.e.:</p>
<pre><code>re.compile('(\"\"|\\\")')
</code></pre>
<p>Which reduces the number of compares and whatnot, but makes it much harder to trouble shoot (with one expression per compare I can easily add a print statement like:</p>
<pre><code>print "URL: ", url, " matched by key ", key
</code></pre>
<p>So is there someway to get the best of both worlds (i.e. minimal number of compares) yet still be able to print out which regex is matching the URL, or do I simply need to bite the bullet and have my slower but easier to troubleshoot code when debugging and then squoosh all the regex's together into one line for production? (which means one more step of programming and code maintenance and possible problems).</p>
<p>Update:</p>
<p>Good answer by Dave Webb, so the actual code for this would look like:</p>
<pre><code>match = re.search(r'(?P<double_quotes>\"\")|(?P<slash_quote>\\\")', fullurl)
if (match == None):
# do stuff here ...
else:
#optional for debugging
print "url matched by", match.lastgroup
</code></pre>
| 1
|
2009-04-11T06:58:44Z
| 739,657
|
<p>"Squoosh" all the regexes into one line but put each in a named group using <a href="http://docs.python.org/library/re.html#regular-expression-syntax" rel="nofollow"><code>(?P<name>...)</code></a> then use <a href="http://docs.python.org/library/re.html#match-objects" rel="nofollow"><code>MatchOjbect.lastgroup</code></a> to find which matched.</p>
| 2
|
2009-04-11T07:09:30Z
|
[
"python",
"regex",
"coding-style"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 739,665
|
<p>Check out <a href="http://docs.python.org/reference/compound_stmts.html#function">the documentation</a> to see how decorators work. Here is what you asked for:</p>
<pre><code>def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makebold
@makeitalic
def hello():
return "hello world"
print hello() ## returns "<b><i>hello world</i></b>"
</code></pre>
| 2,338
|
2009-04-11T07:16:18Z
|
[
"python",
"decorator",
"python-decorators"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 739,667
|
<p>Python decorators add extra functionality to another function</p>
<p>An italics decorator could be like</p>
<pre><code>def makeitalic(fn):
def newFunc():
return "<i>" + fn() + "</i>"
return newFunc
</code></pre>
<p>Note that a function is defined inside a function.
What it basically does is replace a function with the newly defined one. For example, I have this class</p>
<pre><code>class foo:
def bar(self):
print "hi"
def foobar(self):
print "hi again"
</code></pre>
<p>Now say, I want both functions to print "---" after and before they are done.
I could add a print "---" before and after each print statement.
But because I don't like repeating myself, I will make a decorator</p>
<pre><code>def addDashes(fn): # notice it takes a function as an argument
def newFunction(self): # define a new function
print "---"
fn(self) # call the original function
print "---"
return newFunction
# Return the newly defined function - it will "replace" the original
</code></pre>
<p>So now I can change my class to </p>
<pre><code>class foo:
@addDashes
def bar(self):
print "hi"
@addDashes
def foobar(self):
print "hi again"
</code></pre>
<p>For more on decorators, check
<a href="http://www.ibm.com/developerworks/linux/library/l-cpdecor.html">http://www.ibm.com/developerworks/linux/library/l-cpdecor.html</a></p>
| 48
|
2009-04-11T07:19:12Z
|
[
"python",
"decorator",
"python-decorators"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 739,679
|
<p>Alternatively, you could write a factory function which return a decorator which wraps the return value of the decorated function in a tag passed to the factory function. For example:</p>
<pre><code>from functools import wraps
def wrap_in_tag(tag):
def factory(func):
@wraps(func)
def decorator():
return '<%(tag)s>%(rv)s</%(tag)s>' % (
{'tag': tag, 'rv': func()})
return decorator
return factory
</code></pre>
<p>This enables you to write:</p>
<pre><code>@wrap_in_tag('b')
@wrap_in_tag('i')
def say():
return 'hello'
</code></pre>
<p>or</p>
<pre><code>makebold = wrap_in_tag('b')
makeitalic = wrap_in_tag('i')
@makebold
@makeitalic
def say():
return 'hello'
</code></pre>
<p>Personally I would have written the decorator somewhat differently:</p>
<pre><code>from functools import wraps
def wrap_in_tag(tag):
def factory(func):
@wraps(func)
def decorator(val):
return func('<%(tag)s>%(val)s</%(tag)s>' %
{'tag': tag, 'val': val})
return decorator
return factory
</code></pre>
<p>which would yield:</p>
<pre><code>@wrap_in_tag('b')
@wrap_in_tag('i')
def say(val):
return val
say('hello')
</code></pre>
<p>Don't forget the construction for which decorator syntax is a shorthand:</p>
<pre><code>say = wrap_in_tag('b')(wrap_in_tag('i')(say)))
</code></pre>
| 110
|
2009-04-11T07:32:15Z
|
[
"python",
"decorator",
"python-decorators"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 739,721
|
<p>It looks like the other people have already told you how to solve the problem. I hope this will help you understand what decorators are.</p>
<p>Decorators are just syntactical sugar.</p>
<p>This</p>
<pre><code>@decorator
def func():
...
</code></pre>
<p>expands to </p>
<pre><code>def func():
...
func = decorator(func)
</code></pre>
| 72
|
2009-04-11T08:00:42Z
|
[
"python",
"decorator",
"python-decorators"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 1,594,484
|
<p>If you are not into long explanations, see <a href="http://stackoverflow.com/questions/739654/understanding-python-decorators#answer-739665">Paolo Bergantinoâs answer</a>.</p>
<h1>Decorator Basics</h1>
<h2>Pythonâs functions are objects</h2>
<p>To understand decorators, you must first understand that functions are objects in Python. This has important consequences. Letâs see why with a simple example :</p>
<pre><code>def shout(word="yes"):
return word.capitalize()+"!"
print(shout())
# outputs : 'Yes!'
# As an object, you can assign the function to a variable like any other object
scream = shout
# Notice we don't use parentheses: we are not calling the function, we are putting the function "shout" into the variable "scream". It means you can then call "shout" from "scream":
print(scream())
# outputs : 'Yes!'
# More than that, it means you can remove the old name 'shout', and the function will still be accessible from 'scream'
del shout
try:
print(shout())
except NameError, e:
print(e)
#outputs: "name 'shout' is not defined"
print(scream())
# outputs: 'Yes!'
</code></pre>
<p>Keep this in mind. Weâll circle back to it shortly. </p>
<p>Another interesting property of Python functions is they can be defined inside another function!</p>
<pre><code>def talk():
# You can define a function on the fly in "talk" ...
def whisper(word="yes"):
return word.lower()+"..."
# ... and use it right away!
print(whisper())
# You call "talk", that defines "whisper" EVERY TIME you call it, then
# "whisper" is called in "talk".
talk()
# outputs:
# "yes..."
# But "whisper" DOES NOT EXIST outside "talk":
try:
print(whisper())
except NameError, e:
print(e)
#outputs : "name 'whisper' is not defined"*
#Python's functions are objects
</code></pre>
<h2>Functions references</h2>
<p>Okay, still here? Now the fun part...</p>
<p>Youâve seen that functions are objects. Therefore, functions:</p>
<ul>
<li>can be assigned to a variable</li>
<li>can be defined in another function</li>
</ul>
<p>That means that <strong>a function can <code>return</code> another function</strong>.</p>
<pre><code>def getTalk(kind="shout"):
# We define functions on the fly
def shout(word="yes"):
return word.capitalize()+"!"
def whisper(word="yes") :
return word.lower()+"...";
# Then we return one of them
if kind == "shout":
# We don't use "()", we are not calling the function, we are returning the function object
return shout
else:
return whisper
# How do you use this strange beast?
# Get the function and assign it to a variable
talk = getTalk()
# You can see that "talk" is here a function object:
print(talk)
#outputs : <function shout at 0xb7ea817c>
# The object is the one returned by the function:
print(talk())
#outputs : Yes!
# And you can even use it directly if you feel wild:
print(getTalk("whisper")())
#outputs : yes...
</code></pre>
<p>Thereâs more! </p>
<p>If you can <code>return</code> a function, you can pass one as a parameter:</p>
<pre><code>def doSomethingBefore(func):
print("I do something before then I call the function you gave me")
print(func())
doSomethingBefore(scream)
#outputs:
#I do something before then I call the function you gave me
#Yes!
</code></pre>
<p>Well, you just have everything needed to understand decorators. You see, decorators are âwrappersâ, which means that <strong>they let you execute code before and after the function they decorate</strong> without modifying the function itself.</p>
<h2>Handcrafted decorators</h2>
<p>How youâd do it manually:</p>
<pre><code># A decorator is a function that expects ANOTHER function as parameter
def my_shiny_new_decorator(a_function_to_decorate):
# Inside, the decorator defines a function on the fly: the wrapper.
# This function is going to be wrapped around the original function
# so it can execute code before and after it.
def the_wrapper_around_the_original_function():
# Put here the code you want to be executed BEFORE the original function is called
print("Before the function runs")
# Call the function here (using parentheses)
a_function_to_decorate()
# Put here the code you want to be executed AFTER the original function is called
print("After the function runs")
# At this point, "a_function_to_decorate" HAS NEVER BEEN EXECUTED.
# We return the wrapper function we have just created.
# The wrapper contains the function and the code to execute before and after. Itâs ready to use!
return the_wrapper_around_the_original_function
# Now imagine you create a function you don't want to ever touch again.
def a_stand_alone_function():
print("I am a stand alone function, don't you dare modify me")
a_stand_alone_function()
#outputs: I am a stand alone function, don't you dare modify me
# Well, you can decorate it to extend its behavior.
# Just pass it to the decorator, it will wrap it dynamically in
# any code you want and return you a new function ready to be used:
a_stand_alone_function_decorated = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function_decorated()
#outputs:
#Before the function runs
#I am a stand alone function, don't you dare modify me
#After the function runs
</code></pre>
<p>Now, you probably want that every time you call <code>a_stand_alone_function</code>, <code>a_stand_alone_function_decorated</code> is called instead. Thatâs easy, just overwrite <code>a_stand_alone_function</code> with the function returned by <code>my_shiny_new_decorator</code>:</p>
<pre><code>a_stand_alone_function = my_shiny_new_decorator(a_stand_alone_function)
a_stand_alone_function()
#outputs:
#Before the function runs
#I am a stand alone function, don't you dare modify me
#After the function runs
# Thatâs EXACTLY what decorators do!
</code></pre>
<h2>Decorators demystified</h2>
<p>The previous example, using the decorator syntax:</p>
<pre><code>@my_shiny_new_decorator
def another_stand_alone_function():
print("Leave me alone")
another_stand_alone_function()
#outputs:
#Before the function runs
#Leave me alone
#After the function runs
</code></pre>
<p>Yes, thatâs all, itâs that simple. <code>@decorator</code> is just a shortcut to:</p>
<pre><code>another_stand_alone_function = my_shiny_new_decorator(another_stand_alone_function)
</code></pre>
<p>Decorators are just a pythonic variant of the <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator design pattern</a>. There are several classic design patterns embedded in Python to ease development (like iterators).</p>
<p>Of course, you can accumulate decorators:</p>
<pre><code>def bread(func):
def wrapper():
print("</''''''\>")
func()
print("<\______/>")
return wrapper
def ingredients(func):
def wrapper():
print("#tomatoes#")
func()
print("~salad~")
return wrapper
def sandwich(food="--ham--"):
print(food)
sandwich()
#outputs: --ham--
sandwich = bread(ingredients(sandwich))
sandwich()
#outputs:
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>
</code></pre>
<p>Using the Python decorator syntax:</p>
<pre><code>@bread
@ingredients
def sandwich(food="--ham--"):
print(food)
sandwich()
#outputs:
#</''''''\>
# #tomatoes#
# --ham--
# ~salad~
#<\______/>
</code></pre>
<p>The order you set the decorators MATTERS:</p>
<pre><code>@ingredients
@bread
def strange_sandwich(food="--ham--"):
print(food)
strange_sandwich()
#outputs:
##tomatoes#
#</''''''\>
# --ham--
#<\______/>
# ~salad~
</code></pre>
<hr>
<h1>Now: to answer the question...</h1>
<p>As a conclusion, you can easily see how to answer the question:</p>
<pre><code># The decorator to make it bold
def makebold(fn):
# The new function the decorator returns
def wrapper():
# Insertion of some code before and after
return "<b>" + fn() + "</b>"
return wrapper
# The decorator to make it italic
def makeitalic(fn):
# The new function the decorator returns
def wrapper():
# Insertion of some code before and after
return "<i>" + fn() + "</i>"
return wrapper
@makebold
@makeitalic
def say():
return "hello"
print(say())
#outputs: <b><i>hello</i></b>
# This is the exact equivalent to
def say():
return "hello"
say = makebold(makeitalic(say))
print(say())
#outputs: <b><i>hello</i></b>
</code></pre>
<p>You can now just leave happy, or burn your brain a little bit more and see advanced uses of decorators.</p>
<hr>
<h1>Taking decorators to the next level</h1>
<h2>Passing arguments to the decorated function</h2>
<pre><code># Itâs not black magic, you just have to let the wrapper
# pass the argument:
def a_decorator_passing_arguments(function_to_decorate):
def a_wrapper_accepting_arguments(arg1, arg2):
print("I got args! Look: {0}, {1}".format(arg1, arg2))
function_to_decorate(arg1, arg2)
return a_wrapper_accepting_arguments
# Since when you are calling the function returned by the decorator, you are
# calling the wrapper, passing arguments to the wrapper will let it pass them to
# the decorated function
@a_decorator_passing_arguments
def print_full_name(first_name, last_name):
print("My name is {0} {1}".format(first_name, last_name))
print_full_name("Peter", "Venkman")
# outputs:
#I got args! Look: Peter Venkman
#My name is Peter Venkman
</code></pre>
<h2>Decorating methods</h2>
<p>One nifty thing about Python is that methods and functions are really the same. The only difference is that methods expect that their first argument is a reference to the current object (<code>self</code>). </p>
<p>That means you can build a decorator for methods the same way! Just remember to take <code>self</code> into consideration:</p>
<pre><code>def method_friendly_decorator(method_to_decorate):
def wrapper(self, lie):
lie = lie - 3 # very friendly, decrease age even more :-)
return method_to_decorate(self, lie)
return wrapper
class Lucy(object):
def __init__(self):
self.age = 32
@method_friendly_decorator
def sayYourAge(self, lie):
print("I am {0}, what did you think?".format(self.age + lie))
l = Lucy()
l.sayYourAge(-3)
#outputs: I am 26, what did you think?
</code></pre>
<p>If youâre making general-purpose decorator--one youâll apply to any function or method, no matter its arguments--then just use <code>*args, **kwargs</code>:</p>
<pre><code>def a_decorator_passing_arbitrary_arguments(function_to_decorate):
# The wrapper accepts any arguments
def a_wrapper_accepting_arbitrary_arguments(*args, **kwargs):
print("Do I have args?:")
print(args)
print(kwargs)
# Then you unpack the arguments, here *args, **kwargs
# If you are not familiar with unpacking, check:
# http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
function_to_decorate(*args, **kwargs)
return a_wrapper_accepting_arbitrary_arguments
@a_decorator_passing_arbitrary_arguments
def function_with_no_argument():
print("Python is cool, no argument here.")
function_with_no_argument()
#outputs
#Do I have args?:
#()
#{}
#Python is cool, no argument here.
@a_decorator_passing_arbitrary_arguments
def function_with_arguments(a, b, c):
print(a, b, c)
function_with_arguments(1,2,3)
#outputs
#Do I have args?:
#(1, 2, 3)
#{}
#1 2 3
@a_decorator_passing_arbitrary_arguments
def function_with_named_arguments(a, b, c, platypus="Why not ?"):
print("Do {0}, {1} and {2} like platypus? {3}".format(a, b, c, platypus))
function_with_named_arguments("Bill", "Linus", "Steve", platypus="Indeed!")
#outputs
#Do I have args ? :
#('Bill', 'Linus', 'Steve')
#{'platypus': 'Indeed!'}
#Do Bill, Linus and Steve like platypus? Indeed!
class Mary(object):
def __init__(self):
self.age = 31
@a_decorator_passing_arbitrary_arguments
def sayYourAge(self, lie=-3): # You can now add a default value
print("I am {0}, what did you think?".format(self.age + lie))
m = Mary()
m.sayYourAge()
#outputs
# Do I have args?:
#(<__main__.Mary object at 0xb7d303ac>,)
#{}
#I am 28, what did you think?
</code></pre>
<h2>Passing arguments to the decorator</h2>
<p>Great, now what would you say about passing arguments to the decorator itself? </p>
<p>This can get somewhat twisted, since a decorator must accept a function as an argument. Therefore, you cannot pass the decorated functionâs arguments directly to the decorator.</p>
<p>Before rushing to the solution, letâs write a little reminder: </p>
<pre><code># Decorators are ORDINARY functions
def my_decorator(func):
print("I am an ordinary function")
def wrapper():
print("I am function returned by the decorator")
func()
return wrapper
# Therefore, you can call it without any "@"
def lazy_function():
print("zzzzzzzz")
decorated_function = my_decorator(lazy_function)
#outputs: I am an ordinary function
# It outputs "I am an ordinary function", because thatâs just what you do:
# calling a function. Nothing magic.
@my_decorator
def lazy_function():
print("zzzzzzzz")
#outputs: I am an ordinary function
</code></pre>
<p>Itâs exactly the same. "<code>my_decorator</code>" is called. So when you <code>@my_decorator</code>, you are telling Python to call the function 'labelled by the variable "<code>my_decorator</code>"'. </p>
<p>This is important! The label you give can point directly to the decoratorâ<strong>or not</strong>. </p>
<p>Letâs get evil. âº</p>
<pre><code>def decorator_maker():
print("I make decorators! I am executed only once: "
"when you make me create a decorator.")
def my_decorator(func):
print("I am a decorator! I am executed only when you decorate a function.")
def wrapped():
print("I am the wrapper around the decorated function. "
"I am called when you call the decorated function. "
"As the wrapper, I return the RESULT of the decorated function.")
return func()
print("As the decorator, I return the wrapped function.")
return wrapped
print("As a decorator maker, I return a decorator")
return my_decorator
# Letâs create a decorator. Itâs just a new function after all.
new_decorator = decorator_maker()
#outputs:
#I make decorators! I am executed only once: when you make me create a decorator.
#As a decorator maker, I return a decorator
# Then we decorate the function
def decorated_function():
print("I am the decorated function.")
decorated_function = new_decorator(decorated_function)
#outputs:
#I am a decorator! I am executed only when you decorate a function.
#As the decorator, I return the wrapped function
# Letâs call the function:
decorated_function()
#outputs:
#I am the wrapper around the decorated function. I am called when you call the decorated function.
#As the wrapper, I return the RESULT of the decorated function.
#I am the decorated function.
</code></pre>
<p>No surprise here. </p>
<p>Letâs do EXACTLY the same thing, but skip all the pesky intermediate variables:</p>
<pre><code>def decorated_function():
print("I am the decorated function.")
decorated_function = decorator_maker()(decorated_function)
#outputs:
#I make decorators! I am executed only once: when you make me create a decorator.
#As a decorator maker, I return a decorator
#I am a decorator! I am executed only when you decorate a function.
#As the decorator, I return the wrapped function.
# Finally:
decorated_function()
#outputs:
#I am the wrapper around the decorated function. I am called when you call the decorated function.
#As the wrapper, I return the RESULT of the decorated function.
#I am the decorated function.
</code></pre>
<p>Letâs make it <em>even shorter</em>:</p>
<pre><code>@decorator_maker()
def decorated_function():
print("I am the decorated function.")
#outputs:
#I make decorators! I am executed only once: when you make me create a decorator.
#As a decorator maker, I return a decorator
#I am a decorator! I am executed only when you decorate a function.
#As the decorator, I return the wrapped function.
#Eventually:
decorated_function()
#outputs:
#I am the wrapper around the decorated function. I am called when you call the decorated function.
#As the wrapper, I return the RESULT of the decorated function.
#I am the decorated function.
</code></pre>
<p>Hey, did you see that? We used a function call with the "<code>@</code>" syntax! :-)</p>
<p>So, back to decorators with arguments. If we can use functions to generate the decorator on the fly, we can pass arguments to that function, right?</p>
<pre><code>def decorator_maker_with_arguments(decorator_arg1, decorator_arg2):
print("I make decorators! And I accept arguments: {0}, {1}".format(decorator_arg1, decorator_arg2))
def my_decorator(func):
# The ability to pass arguments here is a gift from closures.
# If you are not comfortable with closures, you can assume itâs ok,
# or read: http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python
print("I am the decorator. Somehow you passed me arguments: {0}, {1}".format(decorator_arg1, decorator_arg2))
# Don't confuse decorator arguments and function arguments!
def wrapped(function_arg1, function_arg2) :
print("I am the wrapper around the decorated function.\n"
"I can access all the variables\n"
"\t- from the decorator: {0} {1}\n"
"\t- from the function call: {2} {3}\n"
"Then I can pass them to the decorated function"
.format(decorator_arg1, decorator_arg2,
function_arg1, function_arg2))
return func(function_arg1, function_arg2)
return wrapped
return my_decorator
@decorator_maker_with_arguments("Leonard", "Sheldon")
def decorated_function_with_arguments(function_arg1, function_arg2):
print("I am the decorated function and only knows about my arguments: {0}"
" {1}".format(function_arg1, function_arg2))
decorated_function_with_arguments("Rajesh", "Howard")
#outputs:
#I make decorators! And I accept arguments: Leonard Sheldon
#I am the decorator. Somehow you passed me arguments: Leonard Sheldon
#I am the wrapper around the decorated function.
#I can access all the variables
# - from the decorator: Leonard Sheldon
# - from the function call: Rajesh Howard
#Then I can pass them to the decorated function
#I am the decorated function and only knows about my arguments: Rajesh Howard
</code></pre>
<p>Here it is: a decorator with arguments. Arguments can be set as variable:</p>
<pre><code>c1 = "Penny"
c2 = "Leslie"
@decorator_maker_with_arguments("Leonard", c1)
def decorated_function_with_arguments(function_arg1, function_arg2):
print("I am the decorated function and only knows about my arguments:"
" {0} {1}".format(function_arg1, function_arg2))
decorated_function_with_arguments(c2, "Howard")
#outputs:
#I make decorators! And I accept arguments: Leonard Penny
#I am the decorator. Somehow you passed me arguments: Leonard Penny
#I am the wrapper around the decorated function.
#I can access all the variables
# - from the decorator: Leonard Penny
# - from the function call: Leslie Howard
#Then I can pass them to the decorated function
#I am the decorated function and only knows about my arguments: Leslie Howard
</code></pre>
<p>As you can see, you can pass arguments to the decorator like any function using this trick. You can even use <code>*args, **kwargs</code> if you wish. But remember decorators are called <strong>only once</strong>. Just when Python imports the script. You can't dynamically set the arguments afterwards. When you do "import x", <strong>the function is already decorated</strong>, so you can't
change anything.</p>
<hr>
<h1>Letâs practice: decorating a decorator</h1>
<p>Okay, as a bonus, I'll give you a snippet to make any decorator accept generically any argument. After all, in order to accept arguments, we created our decorator using another function. </p>
<p>We wrapped the decorator.</p>
<p>Anything else we saw recently that wrapped function?</p>
<p>Oh yes, decorators!</p>
<p>Letâs have some fun and write a decorator for the decorators:</p>
<pre><code>def decorator_with_args(decorator_to_enhance):
"""
This function is supposed to be used as a decorator.
It must decorate an other function, that is intended to be used as a decorator.
Take a cup of coffee.
It will allow any decorator to accept an arbitrary number of arguments,
saving you the headache to remember how to do that every time.
"""
# We use the same trick we did to pass arguments
def decorator_maker(*args, **kwargs):
# We create on the fly a decorator that accepts only a function
# but keeps the passed arguments from the maker.
def decorator_wrapper(func):
# We return the result of the original decorator, which, after all,
# IS JUST AN ORDINARY FUNCTION (which returns a function).
# Only pitfall: the decorator must have this specific signature or it won't work:
return decorator_to_enhance(func, *args, **kwargs)
return decorator_wrapper
return decorator_maker
</code></pre>
<p>It can be used as follows:</p>
<pre><code># You create the function you will use as a decorator. And stick a decorator on it :-)
# Don't forget, the signature is "decorator(func, *args, **kwargs)"
@decorator_with_args
def decorated_decorator(func, *args, **kwargs):
def wrapper(function_arg1, function_arg2):
print("Decorated with {0} {1}".format(args, kwargs))
return func(function_arg1, function_arg2)
return wrapper
# Then you decorate the functions you wish with your brand new decorated decorator.
@decorated_decorator(42, 404, 1024)
def decorated_function(function_arg1, function_arg2):
print("Hello {0} {1}".format(function_arg1, function_arg2))
decorated_function("Universe and", "everything")
#outputs:
#Decorated with (42, 404, 1024) {}
#Hello Universe and everything
# Whoooot!
</code></pre>
<p>I know, the last time you had this feeling, it was after listening a guy saying: "before understanding recursion, you must first understand recursion". But now, don't you feel good about mastering this?</p>
<hr>
<h1>Best practices: decorators</h1>
<ul>
<li>Decorators were introduced in Python 2.4, so be sure your code will be run on >= 2.4. </li>
<li>Decorators slow down the function call. Keep that in mind.</li>
<li><strong>You cannot un-decorate a function.</strong> (There <em>are</em> hacks to create decorators that can be removed, but nobody uses them.) So once a function is decorated, itâs decorated <em>for all the code</em>.</li>
<li>Decorators wrap functions, which can make them hard to debug. (This gets better from Python >= 2.5; see below.)</li>
</ul>
<p>The <code>functools</code> module was introduced in Python 2.5. It includes the function <code>functools.wraps()</code>, which copies the name, module, and docstring of the decorated function to its wrapper. </p>
<p>(Fun fact: <code>functools.wraps()</code> is a decorator! âº)</p>
<pre><code># For debugging, the stacktrace prints you the function __name__
def foo():
print("foo")
print(foo.__name__)
#outputs: foo
# With a decorator, it gets messy
def bar(func):
def wrapper():
print("bar")
return func()
return wrapper
@bar
def foo():
print("foo")
print(foo.__name__)
#outputs: wrapper
# "functools" can help for that
import functools
def bar(func):
# We say that "wrapper", is wrapping "func"
# and the magic begins
@functools.wraps(func)
def wrapper():
print("bar")
return func()
return wrapper
@bar
def foo():
print("foo")
print(foo.__name__)
#outputs: foo
</code></pre>
<hr>
<h1>How can the decorators be useful?</h1>
<p><strong>Now the big question:</strong> What can I use decorators for? </p>
<p>Seem cool and powerful, but a practical example would be great. Well, there are 1000 possibilities. Classic uses are extending a function behavior from an external lib (you can't modify it), or for debugging (you don't want to modify it because itâs temporary). </p>
<p>You can use them to extend several functions in a DRYâs way, like so:</p>
<pre><code>def benchmark(func):
"""
A decorator that prints the time a function takes
to execute.
"""
import time
def wrapper(*args, **kwargs):
t = time.clock()
res = func(*args, **kwargs)
print("{0} {1}".format(func.__name__, time.clock()-t))
return res
return wrapper
def logging(func):
"""
A decorator that logs the activity of the script.
(it actually just prints it, but it could be logging!)
"""
def wrapper(*args, **kwargs):
res = func(*args, **kwargs)
print("{0} {1} {2}".format(func.__name__, args, kwargs))
return res
return wrapper
def counter(func):
"""
A decorator that counts and prints the number of times a function has been executed
"""
def wrapper(*args, **kwargs):
wrapper.count = wrapper.count + 1
res = func(*args, **kwargs)
print("{0} has been used: {1}x".format(func.__name__, wrapper.count))
return res
wrapper.count = 0
return wrapper
@counter
@benchmark
@logging
def reverse_string(string):
return str(reversed(string))
print(reverse_string("Able was I ere I saw Elba"))
print(reverse_string("A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!"))
#outputs:
#reverse_string ('Able was I ere I saw Elba',) {}
#wrapper 0.0
#wrapper has been used: 1x
#ablE was I ere I saw elbA
#reverse_string ('A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats, a peon, a canal: Panama!',) {}
#wrapper 0.0
#wrapper has been used: 2x
#!amanaP :lanac a ,noep a ,stah eros ,raj a ,hsac ,oloR a ,tur a ,mapS ,snip ,eperc a ,)lemac a ro( niaga gab ananab a ,gat a ,nat a ,gab ananab a ,gag a ,inoracam ,elacrep ,epins ,spam ,arutaroloc a ,shajar ,soreh ,atsap ,eonac a ,nalp a ,nam A
</code></pre>
<p>Of course the good thing with decorators is that you can use them right away on almost anything without rewriting. DRY, I said:</p>
<pre><code>@counter
@benchmark
@logging
def get_random_futurama_quote():
from urllib import urlopen
result = urlopen("http://subfusion.net/cgi-bin/quote.pl?quote=futurama").read()
try:
value = result.split("<br><b><hr><br>")[1].split("<br><br><hr>")[0]
return value.strip()
except:
return "No, I'm ... doesn't!"
print(get_random_futurama_quote())
print(get_random_futurama_quote())
#outputs:
#get_random_futurama_quote () {}
#wrapper 0.02
#wrapper has been used: 1x
#The laws of science be a harsh mistress.
#get_random_futurama_quote () {}
#wrapper 0.01
#wrapper has been used: 2x
#Curse you, merciful Poseidon!
</code></pre>
<p>Python itself provides several decorators: <code>property</code>, <code>staticmethod</code>, etc. </p>
<ul>
<li>Django uses decorators to manage caching and view permissions. </li>
<li>Twisted to fake inlining asynchronous functions calls.</li>
</ul>
<p>This really is a large playground.</p>
| 3,332
|
2009-10-20T13:05:46Z
|
[
"python",
"decorator",
"python-decorators"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 4,012,213
|
<p>And of course you can return lambdas as well from a decorator function:</p>
<pre><code>def makebold(f):
return lambda: "<b>" + f() + "</b>"
def makeitalic(f):
return lambda: "<i>" + f() + "</i>"
@makebold
@makeitalic
def say():
return "Hello"
print say()
</code></pre>
| 51
|
2010-10-25T06:18:12Z
|
[
"python",
"decorator",
"python-decorators"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 8,633,375
|
<p>Another way of doing the same thing:</p>
<pre><code>class bol(object):
def __init__(self, f):
self.f = f
def __call__(self):
return "<b>{}</b>".format(self.f())
class ita(object):
def __init__(self, f):
self.f = f
def __call__(self):
return "<i>{}</i>".format(self.f())
@bol
@ita
def sayhi():
return 'hi'
</code></pre>
<p>Or, more flexibly:</p>
<pre><code>class sty(object):
def __init__(self, tag):
self.tag = tag
def __call__(self, f):
def newf():
return "<{tag}>{res}</{tag}>".format(res=f(), tag=self.tag)
return newf
@sty('b')
@sty('i')
def sayhi():
return 'hi'
</code></pre>
| 14
|
2011-12-26T06:13:01Z
|
[
"python",
"decorator",
"python-decorators"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 9,540,819
|
<p>Speaking of the counter example - as given above, the counter will be shared between all functions that use the decorator:</p>
<pre><code>def counter(func):
def wrapped(*args, **kws):
print 'Called #%i' % wrapped.count
wrapped.count += 1
return func(*args, **kws)
wrapped.count = 0
return wrapped
</code></pre>
<p>That way, your decorator can be reused for different functions (or used to decorate the same function multiple times: <code>func_counter1 = counter(func); func_counter2 = counter(func)</code>), and the counter variable will remain private to each. </p>
| 1
|
2012-03-02T21:47:17Z
|
[
"python",
"decorator",
"python-decorators"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 11,673,539
|
<p>A decorator takes the function definition and creates a new function that executes this function and transforms the result.</p>
<pre><code>@deco
def do():
...
</code></pre>
<p>is eqivarent to:</p>
<pre><code>do = deco(do)
</code></pre>
<h2>Example:</h2>
<pre><code>def deco(func):
def inner(letter):
return func(letter).upper() #upper
return inner
</code></pre>
<p>This</p>
<pre><code>@deco
def do(number):
return chr(number) # number to letter
</code></pre>
<p>is eqivalent to this
def do2(number):
return chr(number)</p>
<pre><code>do2 = deco(do2)
</code></pre>
<p>65 <=> 'a'</p>
<pre><code>print(do(65))
print(do2(65))
>>> B
>>> B
</code></pre>
<p>To understand the decorator, it is important to notice, that decorator created a new function do which is inner that executes func and transforms the result.</p>
| 8
|
2012-07-26T16:11:42Z
|
[
"python",
"decorator",
"python-decorators"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 15,840,821
|
<h1>Decorate functions with different number of arguments:</h1>
<pre><code>def frame_tests(fn):
def wrapper(*args):
print "\nStart: %s" %(fn.__name__)
fn(*args)
print "End: %s\n" %(fn.__name__)
return wrapper
@frame_tests
def test_fn1():
print "This is only a test!"
@frame_tests
def test_fn2(s1):
print "This is only a test! %s" %(s1)
@frame_tests
def test_fn3(s1, s2):
print "This is only a test! %s %s" %(s1, s2)
if __name__ == "__main__":
test_fn1()
test_fn2('OK!')
test_fn3('OK!', 'Just a test!')
</code></pre>
<p>Result: </p>
<pre><code>Start: test_fn1
This is only a test!
End: test_fn1
Start: test_fn2
This is only a test! OK!
End: test_fn2
Start: test_fn3
This is only a test! OK! Just a test!
End: test_fn3
</code></pre>
| 0
|
2013-04-05T18:18:08Z
|
[
"python",
"decorator",
"python-decorators"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 17,140,530
|
<p>Here is a simple example of chaining decorators. Note the last line - it shows what is going on under the covers.</p>
<pre><code>############################################################
#
# decorators
#
############################################################
def bold(fn):
def decorate():
# surround with bold tags before calling original function
return "<b>" + fn() + "</b>"
return decorate
def uk(fn):
def decorate():
# swap month and day
fields = fn().split('/')
date = fields[1] + "/" + fields[0] + "/" + fields[2]
return date
return decorate
import datetime
def getDate():
now = datetime.datetime.now()
return "%d/%d/%d" % (now.day, now.month, now.year)
@bold
def getBoldDate():
return getDate()
@uk
def getUkDate():
return getDate()
@bold
@uk
def getBoldUkDate():
return getDate()
print getDate()
print getBoldDate()
print getUkDate()
print getBoldUkDate()
# what is happening under the covers
print bold(uk(getDate))()
</code></pre>
<p>The output looks like:</p>
<pre><code>17/6/2013
<b>17/6/2013</b>
6/17/2013
<b>6/17/2013</b>
<b>6/17/2013</b>
</code></pre>
| 2
|
2013-06-17T04:43:25Z
|
[
"python",
"decorator",
"python-decorators"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 22,833,714
|
<pre><code>#decorator.py
def makeHtmlTag(tag, *args, **kwds):
def real_decorator(fn):
css_class = " class='{0}'".format(kwds["css_class"]) \
if "css_class" in kwds else ""
def wrapped(*args, **kwds):
return "<"+tag+css_class+">" + fn(*args, **kwds) + "</"+tag+">"
return wrapped
# return decorator dont call it
return real_decorator
@makeHtmlTag(tag="b", css_class="bold_css")
@makeHtmlTag(tag="i", css_class="italic_css")
def hello():
return "hello world"
print hello()
</code></pre>
<p>You can also write decorator in Class</p>
<pre><code>#class.py
class makeHtmlTagClass(object):
def __init__(self, tag, css_class=""):
self._tag = tag
self._css_class = " class='{0}'".format(css_class) \
if css_class !="" else ""
def __call__(self, fn):
def wrapped(*args, **kwargs):
return "<" + self._tag + self._css_class+">" \
+ fn(*args, **kwargs) + "</" + self._tag + ">"
return wrapped
@makeHtmlTagClass(tag="b", css_class="bold_css")
@makeHtmlTagClass(tag="i", css_class="italic_css")
def hello(name):
return "Hello, {}".format(name)
print hello("Your name")
</code></pre>
| 1
|
2014-04-03T09:43:12Z
|
[
"python",
"decorator",
"python-decorators"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 29,163,633
|
<p>To explain decorator in a simpler way:</p>
<p>With:</p>
<pre><code>@decor1
@decor2
def func(*args, **kwargs):
pass
</code></pre>
<p>When do:</p>
<pre><code>func(*args, **kwargs)
</code></pre>
<p>You really do:</p>
<pre><code>decor1(decor2(func))(*args, **kwargs)
</code></pre>
| 3
|
2015-03-20T09:48:56Z
|
[
"python",
"decorator",
"python-decorators"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 30,283,056
|
<p>You <em>could</em> make two separate decorators that do what you want as illustrated directly below. Note the use of <code>*args, **kwargs</code> in the declaration of the <code>wrapped()</code> function which supports the decorated function having multiple arguments (which isn't really necessary for the example <code>say()</code> function, but is included for generality).</p>
<p>For similar reasons, the <code>functools.wraps</code> decorator is used to change the meta attributes of the wrapped function to be those of the one being decorated. This makes error messages and embedded function documentation (<code>func.__doc__</code>) be those of the decorated function instead of <code>wrapped()</code>'s.</p>
<pre><code>from functools import wraps
def makebold(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return "<b>" + fn(*args, **kwargs) + "</b>"
return wrapped
def makeitalic(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return "<i>" + fn(*args, **kwargs) + "</i>"
return wrapped
@makebold
@makeitalic
def say():
return 'Hello'
print(say()) # -> <b><i>Hello</i></b>
</code></pre>
<p>However it would be better in this case, since the two are so similar to one other, for you to instead make a generic one that was essentially a <em>decorator factory</em> — in other words, a decorator that makes other decorators. That way there would be less code repetition.</p>
<pre><code>def html_deco(tag):
def decorator(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return '<%s>' % tag + fn(*args, **kwargs) + '</%s>' % tag
return wrapped
return decorator
@html_deco('b')
@html_deco('i')
def greet(whom=''): # function that has a keyword argument
return 'Hello' + (' ' + whom) if whom else ''
print(greet('world')) # -> <b><i>Hello world</i></b>
</code></pre>
<p>To make the code more readable, you can assign a more descriptive name to the factory-generated decorators:</p>
<pre><code>makebold = html_deco('b')
makeitalic = html_deco('i')
@makebold
@makeitalic
def greet(whom=''):
return 'Hello' + (' ' + whom) if whom else ''
print(greet('world')) # -> <b><i>Hello world</i></b>
</code></pre>
<p>or even combine them like this:</p>
<pre><code>makebolditalic = lambda fn: makebold(makeitalic(fn))
@makebolditalic
def greet(whom=''):
return 'Hello' + (' ' + whom) if whom else ''
print(greet('world')) # -> <b><i>Hello world</i></b>
</code></pre>
| 8
|
2015-05-17T03:26:24Z
|
[
"python",
"decorator",
"python-decorators"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 34,073,212
|
<blockquote>
<h1>How can I make two decorators in Python that would do the following?</h1>
</blockquote>
<p>You want the following function, when called:</p>
<blockquote>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
</blockquote>
<p>To return:</p>
<blockquote>
<pre><code><b><i>Hello</i></b>
</code></pre>
</blockquote>
<h2>Simple direct solution</h2>
<p>To most simply do this, make decorators that return lambdas (anonymous functions) that wrap the function call:</p>
<pre><code>def makeitalic(fn):
return lambda: '<i>' + fn() + '</i>'
def makebold(fn):
return lambda: '<b>' + fn() + '</b>'
</code></pre>
<p>Now use them as desired:</p>
<pre><code>@makebold
@makeitalic
def say():
return 'Hello'
</code></pre>
<p>and now:</p>
<pre><code>>>> say()
'<b><i>Hello</i></b>'
</code></pre>
<h2>Problems with the direct solution</h2>
<p>But we seem to have nearly lost the original function. </p>
<pre><code>>>> say
<function <lambda> at 0x4ACFA070>
</code></pre>
<p>To find it, we'd need to dig into the closure of each lambda, one of which is buried in the other:</p>
<pre><code>>>> say.__closure__[0].cell_contents
<function <lambda> at 0x4ACFA030>
>>> say.__closure__[0].cell_contents.__closure__[0].cell_contents
<function say at 0x4ACFA730>
</code></pre>
<p>So if we put documentation on this function, or wanted to be able to decorate functions that take more than one argument, or we just wanted to know what function we were looking at in a debugging session, we need to do a bit more with our wrapper.</p>
<h2>Full featured solution - overcoming most of these problems</h2>
<p>We have the decorator <code>wraps</code> from the <code>functools</code> module in the standard library! </p>
<pre><code>from functools import wraps
def makeitalic(fn):
# must assign/update attributes from wrapped function to wrapper
# __module__, __name__, __doc__, and __dict__ by default
@wraps(fn) # explicitly give function whose attributes it is applying
def wrapped(*args, **kwargs):
return '<i>' + fn(*args, **kwargs) + '</i>'
return wrapped
def makebold(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return '<b>' + fn(*args, **kwargs) + '</b>'
return wrapped
</code></pre>
<p>It is unfortunate that there's still some boilerplate, but this is about as simple as we can make it. </p>
<p>In Python 3, you also get <code>__qualname__</code> and <code>__annotations__</code> assigned by default.</p>
<p>So now:</p>
<pre><code>@makebold
@makeitalic
def say():
"""This function returns a bolded, italicized 'hello'"""
return 'Hello'
</code></pre>
<p>And now:</p>
<pre><code>>>> say
<function say at 0x14BB8F70>
>>> help(say)
Help on function say in module __main__:
say(*args, **kwargs)
This function returns a bolded, italicized 'hello'
</code></pre>
<h2>Conclusion</h2>
<p>So we see that <code>wraps</code> makes the wrapping function do almost everything except tell us exactly what the function takes as arguments. </p>
<p>There are other modules that may attempt to tackle the problem, but the solution is not yet in the standard library.</p>
| 5
|
2015-12-03T18:09:54Z
|
[
"python",
"decorator",
"python-decorators"
] |
How to make a chain of function decorators in Python?
| 739,654
|
<p>How can I make two decorators in Python that would do the following?</p>
<pre><code>@makebold
@makeitalic
def say():
return "Hello"
</code></pre>
<p>...which should return:</p>
<pre><code>"<b><i>Hello</i></b>"
</code></pre>
<p>I'm not trying to make <code>HTML</code> this way in a real application - just trying to understand how decorators and decorator chaining works.</p>
| 1,920
|
2009-04-11T07:05:31Z
| 40,047,951
|
<p>This question has been answered to buggery, granted. But I have an alternate solution for anyone interested in it.</p>
<p>It allows you to use one decorator that will then go on to decorate your function/class with decorators that you give as arguments for the decorator.</p>
<pre><code>class TupDec(object): # Give a tuple of decorators, it will
# decorate the function that IT decorated with these decorators
def __init__(self, decs):
self.decs = decs # decs is a tuple: (decorator:function/class, tuple:arguments)
def __call__(self, f):
for dec in self.decs:
try:
f = dec[0](f, *dec[1]) # get a decorated "f" with its arguments
except IndexError:
f = dec[0](f)
return f
@TupDec(((decorator, [arguments]), (decorator, [arguments])))
def A():
print("Hello World!")
</code></pre>
<p>So in your case, you would use:</p>
<pre><code>@TupDec(((makeItalic,), (makeBold,)))
def say():
return "Hello"
</code></pre>
<p>If in needed arguments (like, makeItalic needed 2 and 3 as arguments) then you would:</p>
<pre><code>@TupDec(((makeItalic, (2, 3)), (makeBold,)))
def say():
return "Hello"
</code></pre>
| 0
|
2016-10-14T16:29:30Z
|
[
"python",
"decorator",
"python-decorators"
] |
Python: Locks from `threading` and `multiprocessing` interchangable?
| 739,687
|
<p>Are the locks from the <code>threading</code> module interchangeable with those from the <code>multiprocessing</code> module?</p>
| 5
|
2009-04-11T07:37:24Z
| 739,698
|
<p>I don't think so. Threading locks are within the same process, while the multiprocessing lock would likely be in shared memory.</p>
<p>Last time I checked, multiprocessing doesn't allow you to share the lock in a Queue, which is a threading lock.</p>
| 1
|
2009-04-11T07:42:18Z
|
[
"python",
"multithreading",
"locking",
"multiprocessing"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.