prefix
stringclasses 1
value | input_text
stringlengths 10
172
| target_text
stringlengths 18
33.9k
|
---|---|---|
QA: | PGP signatures from Python? | <p>I think <a href="http://www.gnupg.org/related_software/gpgme/" rel="nofollow">GPGME</a> and the <a href="http://pyme.sourceforge.net/" rel="nofollow">PyMe Python wrapper</a> should do what you need.</p>
|
QA: | javascript locals()? | <ul>
<li><p>locals() - No. </p></li>
<li><p>globals() - Yes.</p></li>
</ul>
<p><code>window</code> is a reference to the global scope, like <code>globals()</code> in python.</p>
<pre><code>globals()["foo"]
</code></pre>
<p>is the same as:</p>
<pre><code>window["foo"]
</code></pre>
|
QA: | Using C in a shared multi-platform POSIX environment | <p>Launching a Python interpreter instance just to select the right binary to run would be much heavier than you need. I'd distribute a shell .rc file which provides aliases.</p>
<p>In /shared/bin, you put the various binaries: /shared/bin/toolname-mac, /shared/bin/toolname-debian-x86, /shared/bin/toolname-netbsd-dreamcast, etc. Then, in the common shared shell .rc file, you put the logic to set the aliases according to platform, so that on OSX, it gets alias toolname=/shared/bin/toolname-mac, and so forth.</p>
<p>This won't work as well if you're adding new tools all the time, because the users will need to reload the aliases.</p>
<p>I wouldn't recommend distributing tools this way, though. Testing and qualifying new builds of the tools should be taking up enough time and effort that the extra time required to distribute the tools to the users is trivial. You seem to be optimizing to reduce the distribution time. Replacing tools that quickly in a live environment is all too likely to result in lengthy and confusing downtime if anything goes wrong in writing and building the tools--especially when subtle cross-platform issues creep in.</p>
|
QA: | cx_Oracle: how do I get the ORA-xxxxx error number? | <pre><code>try:
cursor.execute("select 1 / 0 from dual")
except cx_Oracle.DatabaseError, exc:
error, = exc
print "Code:", error.code
print "Message:", error.message
</code></pre>
<p>This results in the following output:</p>
<pre><code>Code: 1476
Message: ORA-01476: divisor is equal to zero
</code></pre>
|
QA: | Python deployment and /usr/bin/env portability | <p>"env" simply executes the first thing it finds in the PATH env var. To switch to different python, prepend the directory for that python's executable to the path before invoking your script.</p>
|
QA: | Python deployment and /usr/bin/env portability | <p>If you are running the scripts then you can set your PATH variable to point to a private bin directory first:</p>
<pre><code>$ mkdir ~/bin
$ ln -s `which python2.4` ~/bin/python
$ export PATH=~/bin:$PATH
</code></pre>
<p>Then when you execute your python script it'll use python 2.4. You'll have to change your login scripts to change your PATH.</p>
<p>Alternatively run your python script with the explicit interpreter you want:</p>
<pre><code>$ /path/to/python2.4 <your script>
</code></pre>
|
QA: | How can I render a tree structure (recursive) using a django template? | <p>I had a similar issue, however I had first implemented the solution using JavaScript, and just afterwards considered how I would have done the same thing in django templates.</p>
<p>I used the serializer utility to turn a list off models into json, and used the json data as a basis for my hierarchy.</p>
|
QA: | Always including the user in the django template context | <p>If you can hook your authentication into the <a href="http://www.djangoproject.com/documentation/authentication/#authentication-in-web-requests" rel="nofollow">Django authentication scheme</a> you'll be able to use <code>request.user</code>.</p>
<p>I think this should just be a case of calling <code>authenticate()</code> and <code>login()</code> based on the contents of your Cookie.</p>
<p>Edit: @Staale - I always use the <a href="http://www.djangobook.com/en/1.0/chapter04/" rel="nofollow"><code>locals()</code> trick</a> for my context so all my templates can see <code>request</code> and so <code>request.user</code>. If you're not then I guess it wouldn't be so straightforward.</p>
|
QA: | Always including the user in the django template context | <p>In a more general sense of not having to explicitly set variables in each view, it sounds like you want to look at writing your own <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors">context processor</a>.</p>
<p>From the docs:</p>
<blockquote>
<p>A context processor has a very simple interface: It's just a Python function that takes one argument, an HttpRequest object, and returns a dictionary that gets added to the template context. Each context processor must return a dictionary.</p>
</blockquote>
|
QA: | Always including the user in the django template context | <p>@Dave
To use {{user.username}} in my templates, I will then have to use
requestcontext rather than just a normal map/hash: <a href="http://www.djangoproject.com/documentation/templates_python/#subclassing-context-requestcontext" rel="nofollow">http://www.djangoproject.com/documentation/templates_python/#subclassing-context-requestcontext</a></p>
<p>So I guess there are no globals that the template engine checks.</p>
<p>But the RequestContext has some prepopulate classes that I can look into to solve my problems. Thanks.</p>
|
QA: | How do I do monkeypatching in python? | <p>A print statement does its IO through "sys.stdout.write" so you can override sys.stdout if you want to manipulate the print stream.</p>
|
QA: | Splitting tuples in Python - best practice? | <p>I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values.</p>
<p>For example:</p>
<pre><code>job={}
job['jobid'], job['label'], job['username']=<querycode>
</code></pre>
|
QA: | Splitting tuples in Python - best practice? | <p>With a tuple it will always be a hassle to add or change fields. You're right that a dictionary will be much better. </p>
<p>If you want something with slightly friendlier syntax you might want to take a look at the answers <a href="http://stackoverflow.com/questions/35988/c-like-structures-in-python" rel="nofollow">this question</a> about a simple 'struct-like' object. That way you can pass around an object, say <code>job</code>, and access its fields even more easily than a tuple or dict:</p>
<pre><code>job.jobId, job.username = jobId, username
</code></pre>
|
QA: | Splitting tuples in Python - best practice? | <p>Perhaps this is overkill for your case, but I would be tempted to create a "Job" class that takes the tuple as its constructor argument and has respective properties on it. I'd then pass instances of this class around instead.</p>
|
QA: | Splitting tuples in Python - best practice? | <p>I would use a dictionary. You can convert the tuple to a dictionary this way:</p>
<pre><code>values = <querycode>
keys = ["jobid", "label", "username"]
job = dict([[keys[i], values [i]] for i in xrange(len(values ))])
</code></pre>
<p>This will first create an array [["jobid", val1], ["label", val2], ["username", val3]] and then convert that to a dictionary. If the result order or count changes, you just need to change the list of keys to match the new result.</p>
<p>PS still fresh on Python myself, so there might be better ways off doing this.</p>
|
QA: | Splitting tuples in Python - best practice? | <p>How about this:</p>
<pre><code>class TypedTuple:
def __init__(self, fieldlist, items):
self.fieldlist = fieldlist
self.items = items
def __getattr__(self, field):
return self.items[self.fieldlist.index(field)]
</code></pre>
<p>You could then do:</p>
<pre><code>j = TypedTuple(["jobid", "label", "username"], job)
print j.jobid
</code></pre>
<p>It should be easy to swap <code>self.fieldlist.index(field)</code> with a dictionary lookup later on... just edit your <code>__init__</code> method! Something like Staale does.</p>
|
QA: | Is there a python module for regex matching in zip files | <p>Isn't it (at least theoretically) possible, to read in the ZIP's Huffman coding and then translate the regexp into the Huffman code? Might this be more efficient than first de-compressing the data, then running the regexp?</p>
<p>(Note: I know it wouldn't be quite that simple: you'd also have to deal with other aspects of the ZIP coding—file layout, block structures, back-references—but one imagines this could be fairly lightweight.)</p>
<p>EDIT: Also note that it's probably much more sensible to just use the <code>zipfile</code> solution.</p>
|
QA: | Splitting tuples in Python - best practice? | <p>@Staale</p>
<p>There is a better way:</p>
<pre><code>job = dict(zip(keys, values))
</code></pre>
|
QA: | How do I do monkeypatching in python? | <p>The python <a href="http://www.python.org/doc/current/lib/module-inspect.html" rel="nofollow">inspect</a> module makes this a lot easier and cleaner. </p>
|
QA: | Standard way to open a folder window in linux? | <p>this would probably have to be done manually, or have as a config item since there are many file managers that users may want to use. Providing a way for command options as well.</p>
<p>There might be an function that launches the defaults for kde or gnome in their respective toolkits but I haven't had reason to look for them.</p>
|
QA: | Standard way to open a folder window in linux? | <p>You're going to have to do this based on the running window manager. OSX and Windows have a (defacto) standard way because there is only one choice.</p>
<p>You shouldn't need to specify the exact filemanager application, though, this should be possible to do through the wm. I know Gnome does, and it's important to do this in KDE since there are two possible file managers (Konqueror/Dolphin) that may be in use.</p>
<p>I agree that this would be a good thing for freedesktop.org to standardize, although I doubt it will happen unless someone steps up and volunteers to do it.</p>
<p><hr /></p>
<p>EDIT: I wasn't aware of xdg-open. Good to know!</p>
|
QA: | Standard way to open a folder window in linux? | <pre><code>os.system('xdg-open "%s"' % foldername)
</code></pre>
<p><code>xdg-open</code> can be used for files/urls also</p>
|
QA: | What is a tuple useful for? | <ul>
<li>Tuples are used whenever you want to return multiple results from a function.</li>
<li>Since they're immutable, they can be used as keys for a dictionary (lists can't).</li>
</ul>
|
QA: | What is a tuple useful for? | <p>I find them useful when you always deal with two or more objects as a set.</p>
|
QA: | What is a tuple useful for? | <p>A list can always replace a tuple, with respect to functionality (except, apparently, as keys in a dict). However, a tuple can make things go faster. The same is true for, for example, immutable strings in Java -- when will you ever need to be unable to alter your strings? Never!</p>
<p>I just read a decent discussion on limiting what you can do in order to make better programs; <a href="http://weblog.raganwald.com/2007/03/why-why-functional-programming-matters.html" rel="nofollow">Why Why Functional Programming Matters Matters</a></p>
|
QA: | What is a tuple useful for? | <p>Tuples make good dictionary keys when you need to combine more than one piece of data into your key and don't feel like making a class for it.</p>
<pre><code>a = {}
a[(1,2,"bob")] = "hello!"
a[("Hello","en-US")] = "Hi There!"
</code></pre>
<p>I've used this feature primarily to create a dictionary with keys that are coordinates of the vertices of a mesh. However, in my particular case, the exact comparison of the floats involved worked fine which might not always be true for your purposes [in which case I'd probably convert your incoming floats to some kind of fixed-point integer]</p>
|
QA: | What is a tuple useful for? | <p>A tuple is useful for storing multiple values.. As you note a tuple is just like a list that is immutable - e.g. once created you cannot add/remove/swap elements.</p>
<p>One benefit of being immutable is that because the tuple is fixed size it allows the run-time to perform certain optimizations. This is particularly beneficial when a tupple is used in the context of a return value or a parameter to a function.</p>
|
QA: | What is a tuple useful for? | <p>Tuples and lists have the same uses in general. Immutable data types in general have many benefits, mostly about concurrency issues.</p>
<p>So, when you have lists that are not volatile in nature and you need to guarantee that no consumer is altering it, you may use a tuple.</p>
<p>Typical examples are fixed data in an application like company divisions, categories, etc. If this data change, typically a single producer rebuilts the tuple.</p>
|
QA: | Best way to extract text from a Word doc without using COM/automation? | <p>Open Office has an <a href="http://api.openoffice.org/" rel="nofollow">API</a></p>
|
QA: | Best way to extract text from a Word doc without using COM/automation? | <p>If it is Word 2007 docx, you could unzip it and parse the XML files that are contained inside.</p>
|
QA: | Python deployment and /usr/bin/env portability | <p>Pretty hackish solution - if your check fails, use this function (which probably could be significantly improved) to determine the best interpreter available, determine if it is acceptable, and if so relaunch your script with os.system or something similar and your sys.argv using the new interpreter.</p>
<pre><code>import os
import glob
def best_python():
plist = []
for i in os.getenv("PATH").split(":"):
for j in glob.glob(os.path.join(i, "python2.[0-9]")):
plist.append(os.path.join(i, j))
plist.sort()
plist.reverse()
if len(plist) == 0: return None
return plist[0]
</code></pre>
|
QA: | Python re.sub MULTILINE caret match | <p>Look at the definition of <a href="http://docs.python.org/library/re.html#re.sub"><code>re.sub</code></a>:</p>
<pre><code>sub(pattern, repl, string[, count])
</code></pre>
<p>The 4th argument is the count, you are using <code>re.MULTILINE</code> (which is 8) as the count, not as a flag.</p>
<p>You have to compile your regex if you wish to use flags.</p>
<pre><code>re.sub(re.compile('^//', re.MULTILINE), '', s)
</code></pre>
<p>A <code>flags</code> argument was added in Python 2.7, so the full definition is now:</p>
<pre><code>re.sub(pattern, repl, string[, count, flags])
</code></pre>
<p>Which means that:</p>
<pre><code>re.sub('^//', '', s, flags=re.MULTILINE)
</code></pre>
<p>works.</p>
|
QA: | Where can I learn more about PyPy's translation function? | <p>This document seems to go into quite a bit of detail (and I think a complete description is out of scope for a stackoverflow answer):</p>
<ul>
<li><a href="http://codespeak.net/pypy/dist/pypy/doc/translation.html" rel="nofollow">http://codespeak.net/pypy/dist/pypy/doc/translation.html</a></li>
</ul>
<p>The general idea of translating from one language to another isn't particularly revolutionary, but it has only recently been gaining popularity / applicability in "real-world" applications. <a href="http://code.google.com/webtoolkit/" rel="nofollow">GWT</a> does this with Java (generating Javascript) and there is a library for translating Haskell into various other languages as well (called <a href="http://www.haskell.org/haskellwiki/Yhc" rel="nofollow">YHC</a>)</p>
|
QA: | Python deployment and /usr/bin/env portability | <p>@morais: That's an interesting idea, but I think maybe we can take it one step farther. Maybe there's a way to use <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">Ian Bicking's virtualenv</a> to:</p>
<ul>
<li>See if we're running in an acceptable environment to begin with, and if so, do nothing.</li>
<li>Check if there exists a version-specific executable on the <code>PATH</code>, i.e. check if <code>python2.x</code> exists <code>for x in reverse(range(4, 10))</code>. If so, re-run the command with the better interpreter.</li>
<li>If no better interpreter exists, use virtualenv to try and install a newer version of Python from the older version of Python and get any prerequisite packages.</li>
</ul>
<p>I have no idea if virtualenv is capable of this, so I'll go mess around with it sometime soon. :)</p>
|
QA: | Get Last Day of the Month in Python | <p>EDIT: See @<a href="#43663">Blair Conrad's answer</a> for a cleaner solution</p>
<p><hr /></p>
<pre><code>>>> import datetime
>>> datetime.date (2000, 2, 1) - datetime.timedelta (days = 1)
datetime.date(2000, 1, 31)
>>>
</code></pre>
|
QA: | Get Last Day of the Month in Python | <p>EDIT: see my other answer. It has a better implementation than this one, which I leave here just in case someone's interested in seeing how one might "roll your own" calculator.</p>
<p>@<a href="#42997">John Millikin</a> gives a good answer, with the added complication of calculating the first day of the next month.</p>
<p>The following isn't particularly elegant, but to figure out the last day of the month that any given date lives in, you could try:</p>
<pre><code>def last_day_of_month(date):
if date.month == 12:
return date.replace(day=31)
return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)
>>> last_day_of_month(datetime.date(2002, 1, 17))
datetime.date(2002, 1, 31)
>>> last_day_of_month(datetime.date(2002, 12, 9))
datetime.date(2002, 12, 31)
>>> last_day_of_month(datetime.date(2008, 2, 14))
datetime.date(2008, 2, 29)
</code></pre>
|
QA: | How can I get a commit message from a bzr post-commit hook? | <p>And the answer is like so:</p>
<pre><code>def check_commit_msg(local, master, old_revno, old_revid, new_revno, new_revid):
branch = local or master
revision = branch.repository.get_revision(new_revid)
print revision.message
</code></pre>
<p>local and master are Branch objects, so once you have a revision, it's easy to extract the message.</p>
|
QA: | Best way to extract text from a Word doc without using COM/automation? | <p>Using the OpenOffice API, and Python, and <a href="http://www.pitonyak.org/oo.php" rel="nofollow">Andrew Pitonyak's excellent online macro book</a> I managed to do this. Section 7.16.4 is the place to start.</p>
<p>One other tip to make it work without needing the screen at all is to use the Hidden property:</p>
<pre><code>RO = PropertyValue('ReadOnly', 0, True, 0)
Hidden = PropertyValue('Hidden', 0, True, 0)
xDoc = desktop.loadComponentFromURL( docpath,"_blank", 0, (RO, Hidden,) )
</code></pre>
<p>Otherwise the document flicks up on the screen (probably on the webserver console) when you open it.</p>
|
QA: | How to generate urls in django | <p>If you need to use something similar to the <code>{% url %}</code> template tag in your code, Django provides the <code>django.core.urlresolvers.reverse()</code>. The <code>reverse</code> function has the following signature:</p>
<pre><code>reverse(viewname, urlconf=None, args=None, kwargs=None)
</code></pre>
<p><a href="https://docs.djangoproject.com/en/dev/ref/urlresolvers/">https://docs.djangoproject.com/en/dev/ref/urlresolvers/</a></p>
|
QA: | Can I write native iPhone apps using Python | <p>Not currently, currently the only languages available to access the iPhone SDK are C/C++, Objective C and Swift.</p>
<p>There is no technical reason why this could not change in the future but I wouldn't hold your breath for this happening in the short term.</p>
<p>That said, Objective-C and Swift really are not too scary...</p>
<blockquote>
<h1>2016 edit</h1>
<p>Javascript with NativeScript framework is available to use now.</p>
</blockquote>
|
QA: | Can I write native iPhone apps using Python | <p>You can use PyObjC on the iPhone as well, due to the excellent work by Jay Freeman (saurik). See <a href="http://www.saurik.com/id/5">iPhone Applications in Python</a>.</p>
<p>Note that this requires a jailbroken iPhone at the moment.</p>
|
QA: | Best way to extract text from a Word doc without using COM/automation? | <p>I use catdoc or antiword for this, whatever gives the result that is the easiest to parse. I have embedded this in python functions, so it is easy to use from the parsing system (which is written in python).</p>
<pre><code>import os
def doc_to_text_catdoc(filename):
(fi, fo, fe) = os.popen3('catdoc -w "%s"' % filename)
fi.close()
retval = fo.read()
erroroutput = fe.read()
fo.close()
fe.close()
if not erroroutput:
return retval
else:
raise OSError("Executing the command caused an error: %s" % erroroutput)
# similar doc_to_text_antiword()
</code></pre>
<p>The -w switch to catdoc turns off line wrapping, BTW.</p>
|
QA: | A python web application framework for tight DB/GUI coupling? | <p>You should have a look at django and especially its <a href="http://www.djangoproject.com/documentation/forms/" rel="nofollow">newforms</a> and <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#ref-contrib-admin" rel="nofollow">admin</a> modules. The newforms module provides a nice possibility to do server side validation with automated generation of error messages/pages for the user. Adding ajax validation is also <a href="http://lukeplant.me.uk/blog.php?id=1107301681" rel="nofollow">possible</a> </p>
|
QA: | A python web application framework for tight DB/GUI coupling? | <p>I believe that Django models does not support composite primary keys (see <a href="http://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields" rel="nofollow">documentation</a>). But perhaps you can use SQLAlchemy in Django? A <a href="http://www.google.com/search?q=sqlalchemy+django" rel="nofollow">google search</a> indicates that you can. I have not used Django, so I don't know.</p>
<p>I suggest you take a look at:</p>
<ul>
<li><a href="http://toscawidgets.org/" rel="nofollow">ToscaWidgets</a></li>
<li><a href="http://code.google.com/p/dbsprockets/" rel="nofollow">DBSprockets</a>, including <a href="http://code.google.com/p/dbsprockets/wiki/DBMechanic" rel="nofollow">DBMechanic</a></li>
<li><a href="http://www.checkandshare.com/catwalk/" rel="nofollow">Catwalk</a>. Catwalk is an application for TurboGears 1.0 that uses SQLObject, not SQLAlchemy. Also check out this <a href="http://www.checkandshare.com/blog/?p=41" rel="nofollow">blog post</a> and <a href="http://www.checkandshare.com/CATWALK2/lview/index.html" rel="nofollow">screencast</a>.</li>
<li><a href="http://docs.turbogears.org/1.0/DataController" rel="nofollow">FastData</a>. Also uses SQLObject.</li>
<li><a href="http://code.google.com/p/formalchemy/" rel="nofollow">formalchemy</a></li>
<li><a href="http://rumdemo.toscawidgets.org/" rel="nofollow">Rum</a></li>
</ul>
<p>I do not have any deep knowledge of any of the projects above. I am just in the process of trying to add something similar to one of my own applications as what the original question mentions. The above list is simply a list of interesting projects that I have stumbled across.</p>
<p>As to web application frameworks for Python, I recommend TurboGears 2. Not that I have any experience with any of the other frameworks, I just like TurboGears...</p>
<p>If the original question's author finds a solution that works well, please update or answer this thread.</p>
|
QA: | How to find the mime type of a file in python? | <p>The <a href="https://docs.python.org/library/mimetypes.html">mimetypes module</a> in the standard library will determine/guess the MIME type from a file extension.</p>
<p>If users are uploading files the HTTP post will contain the MIME type of the file alongside the data. For example, Django makes this data available as an attribute of the <a href="https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#uploadedfile-objects">UploadedFile</a> object.</p>
|
QA: | How to find the mime type of a file in python? | <p>You didn't state what web server you were using, but Apache has a nice little module called <a href="http://httpd.apache.org/docs/1.3/mod/mod_mime_magic.html" rel="nofollow">Mime Magic</a> which it uses to determine the type of a file when told to do so. It reads some of the file's content and tries to figure out what type it is based on the characters found. And as <a href="http://stackoverflow.com/questions/43580/how-to-find-the-mime-type-of-a-file-in-python#43588" rel="nofollow">Dave Webb Mentioned</a> the <a href="http://docs.python.org/lib/module-mimetypes.html" rel="nofollow">MimeTypes Module</a> under python will work, provided an extension is handy.</p>
<p>Alternatively, if you are sitting on a UNIX box you can use <code>sys.popen('file -i ' + fileName, mode='r')</code> to grab the MIME type. Windows should have an equivalent command, but I'm unsure as to what it is. </p>
|
QA: | Get Last Day of the Month in Python | <p>I didn't notice this earlier when I was looking at the <a href="https://docs.python.org/2/library/calendar.html">documentation for the calendar module</a>, but a method called <a href="http://docs.python.org/library/calendar.html#calendar.monthrange">monthrange</a> provides this information:</p>
<blockquote>
<p><b>monthrange(year, month)</b><br>
Returns weekday of first day of the month and number of days in month, for the specified year and month. </p>
</blockquote>
<pre><code>>>> import calendar
>>> calendar.monthrange(2002,1)
(1, 31)
>>> calendar.monthrange(2008,2)
(4, 29)
>>> calendar.monthrange(2100,2)
(0, 28)
</code></pre>
<p>so:</p>
<pre><code>calendar.monthrange(year, month)[1]
</code></pre>
<p>seems like the simplest way to go.</p>
<p>Just to be clear, <code>monthrange</code> supports leap years as well:</p>
<pre><code>>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)
</code></pre>
<p><a href="http://stackoverflow.com/questions/42950/get-last-day-of-the-month-in-python#43088">My previous answer</a> still works, but is clearly suboptimal.</p>
|
QA: | Pros and Cons of different approaches to web programming in Python | <p>If you've never done any CGI programming before I think it would be worth doing one project - perhaps just a sample play site just for yourself - using the DIY approach. You'll learn a lot more about how all the various parts work than you would by using a framework. This will help in you design and debug and so on all your future web applications however you write them.</p>
<p>Personally I now use <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>. The real benefit is very fast application deployment. The object relational mapping gets things moving fast and the template library is a joy to use. Also the admin interface gives you basic CRUD screens for all your objects so you don't need to write any of the "boring" stuff.</p>
<p>The downside of using an ORM based solution is that if you do want to handcraft some SQL, say for performance reasons, it much harder than it would have been otherwise, although still very possible. </p>
|
QA: | Pros and Cons of different approaches to web programming in Python | <p>If you decide to go with a framework that is WSGI-based (for instance <a href="http://www.turbogears.org/2.0" rel="nofollow">TurboGears</a>), I would recommend you go through the excellent article <a href="http://pythonpaste.org/webob/do-it-yourself.html" rel="nofollow">Another Do-It-Yourself Framework</a> by Ian Bicking.</p>
<p>In the article, he builds a simple web application framework from scratch.</p>
<p>Also, check out the video <a href="http://www.vimeo.com/3258566" rel="nofollow">Creating a web framework with WSGI</a> by Kevin Dangoor. Dangoor is the founder of the TurboGears project.</p>
|
QA: | Pros and Cons of different approaches to web programming in Python | <p>CGI is great for low-traffic websites, but it has some performance problems for anything else. This is because every time a request comes in, the server starts the CGI application in its own process. This is bad for two reasons: 1) Starting and stopping a process can take time and 2) you can't cache anything in memory. You can go with FastCGI, but I would argue that you'd be better off just writing a straight <a href="http://www.python.org/dev/peps/pep-0333/">WSGI</a> app if you're going to go that route (the way WSGI works really isn't a whole heck of a lot different from CGI).</p>
<p>Other than that, your choices are for the most part how much you want the framework to do. You can go with an all singing, all dancing framework like Django or Pylons. Or you can go with a mix-and-match approach (use something like CherryPy for the HTTP stuff, SQLAlchemy for the database stuff, paste for deployment, etc). I should also point out that most frameworks will also let you switch different components out for others, so these two approaches aren't necessarily mutually exclusive.</p>
<p>Personally, I dislike frameworks that do too much magic for me and prefer the mix-and-match technique, but I've been told that I'm also completely insane. :)</p>
<p>How much web programming experience do you have? If you're a beginner, I say go with Django. If you're more experienced, I say to play around with the different approaches and techniques until you find the right one.</p>
|
QA: | Modulus operation with negatives values - weird thing? | <p>Your Python interpreter is correct.
One (stupid) way of calculating a modulus is to subtract or add the modulus until the resulting value is between 0 and (modulus â 1).</p>
<p>e.g.:
13 mod 5 = (13 â 5) mod 5 = (13 â 10) mod 5 = 3</p>
<p>or in your case: â2 mod 5 = (â2 + 5) mod 5 = 3</p>
|
QA: | Modulus operation with negatives values - weird thing? | <p>Well, -2 divided by 5 would be 0 with a remainder of 3. I don't believe that should be very platform dependent, but I've seen stranger things.</p>
|
QA: | Modulus operation with negatives values - weird thing? | <p>It is indeed 3. In <a href="http://en.wikipedia.org/wiki/Modular_arithmetic" rel="nofollow">modular arithmetic</a>, a modulus is simply the remainder of a division, and the remainder of -2 divided by 5 is 3.</p>
|
QA: | Modulus operation with negatives values - weird thing? | <p>The result of the modulus operation on negatives seems to be programming language dependent and here is a listing <a href="http://en.wikipedia.org/wiki/Modulo_operation">http://en.wikipedia.org/wiki/Modulo_operation</a></p>
|
QA: | Modulus operation with negatives values - weird thing? | <p>Well, 0 % 5 should be 0, right?</p>
<p>-1 % 5 should be 4 because that's the next allowed digit going in the reverse direction (i.e., it can't be 5, since that's out of range).</p>
<p>And following along by that logic, -2 must be 3.</p>
<p>The easiest way to think of how it will work is that you keep adding or subtracting 5 until the number falls between 0 (inclusive) and 5 (exclusive).</p>
<p>I'm not sure about machine dependence - I've never seen an implementation that was, but I can't say it's never done.</p>
|
QA: | Modulus operation with negatives values - weird thing? | <p>By the way: most programming languages would disagree with Python and give the result <code>-2</code>. Depending on the interpretation of modulus this is correct. However, the most agreed-upon mathematical definition states that the modulus of <em>a</em> and <em>b</em> is the (strictly positive) rest <em>r</em> of the division of <em>a</em> / <em>b</em>. More precisely, 0 <= <em>r</em> < <em>b</em> by definition.</p>
|
QA: | Modulus operation with negatives values - weird thing? | <p>The result depends on the language. Python returns the sign of the divisor, where for example c# returns the sign of the dividend (ie. -2 % 5 returns -2 in c#).</p>
|
QA: | Pros and Cons of different approaches to web programming in Python | <p>The simplest web program is a CGI script, which is basically just a program whose standard output is redirected to the web browser making the request. In this approach, every page has its own executable file, which must be loaded and parsed on every request. This makes it really simple to get something up and running, but scales badly both in terms of performance and organization. So when I need a very dynamic page very quickly that won't grow into a larger system, I use a CGI script.</p>
<p>One step up from this is embedding your Python code in your HTML code, such as with PSP. I don't think many people use this nowadays, since modern template systems have made this pretty obsolete. I worked with PSP for awhile and found that it had basically the same organizational limits as CGI scripts (every page has its own file) plus some whitespace-related annoyances from trying to mix whitespace-ignorant HTML with whitespace-sensitive Python.</p>
<p>The next step up is very simple web frameworks such as web.py, which I've also used. Like CGI scripts, it's very simple to get something up and running, and you don't need any complex configuration or automatically generated code. Your own code will be pretty simple to understand, so you can see what's happening. However, it's not as feature-rich as other web frameworks; last time I used it, there was no session tracking, so I had to roll my own. It also has "too much magic behavior" to quote Guido ("upvars(), bah").</p>
<p>Finally, you have feature-rich web frameworks such as Django. These will require a bit of work to get simple Hello World programs working, but every major one has a great, well-written tutorial (especially Django) to walk you through it. I highly recommend using one of these web frameworks for any real project because of the convenience and features and documentation, etc.</p>
<p>Ultimately you'll have to decide what you prefer. For example, frameworks all use template languages (special code/tags) to generate HTML files. Some of them such as Cheetah templates let you write arbitrary Python code so that you can do anything in a template. Others such as Django templates are more restrictive and force you to separate your presentation code from your program logic. It's all about what you personally prefer.</p>
<p>Another example is URL handling; some frameworks such as Django have you define the URLs in your application through regular expressions. Others such as CherryPy automatically map your functions to urls by your function names. Again, this is a personal preference.</p>
<p>I personally use a mix of web frameworks by using CherryPy for my web server stuff (form parameters, session handling, url mapping, etc) and Django for my object-relational mapping and templates. My recommendation is to start with a high level web framework, work your way through its tutorial, then start on a small personal project. I've done this with all of the technologies I've mentioned and it's been really beneficial. Eventually you'll get a feel for what you prefer and become a better web programmer (and a better programmer in general) in the process.</p>
|
QA: | Modulus operation with negatives values - weird thing? | <p>One explanation might be that negative numbers are stored using <a href="http://en.wikipedia.org/wiki/Two%27s_complement" rel="nofollow">2's complement</a>. When the python interpreter tries to do the modulo operation it converts to unsigned value. As such instead of doing (-2) % 5 it actually computes 0xFFFF_FFFF_FFFF_FFFD % 5 which is 3. </p>
|
QA: | Modulus operation with negatives values - weird thing? | <p>As explained in other answers, there are many choices for a modulo operation with negative values. In general different languages (and different machine architectures) will give a different result.</p>
<p>According to the <a href="http://docs.python.org/ref/binary.html" rel="nofollow">Python reference manual</a>,</p>
<blockquote>
<p>The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand.</p>
</blockquote>
<p>is the choice taken by Python. Basically modulo is defined so that this always holds:</p>
<pre><code>x == (x/y)*y + (x%y)
</code></pre>
<p>so it makes sense that (-2)%5 = -2 - (-2/5)*5 = 3</p>
|
QA: | Modulus operation with negatives values - weird thing? | <p>Be careful not to rely on this mod behavior in C/C++ on all OSes and architectures. If I recall correctly, I tried to rely on C/C++ code like</p>
<pre><code>float x2 = x % n;
</code></pre>
<p>to keep x2 in the range from 0 to n-1 but negative numbers crept in when I would compile on one OS, but things would work fine on another OS. This made for an evil time debugging since it only happened half the time!</p>
|
QA: | How do I document a module in Python? | <p>It's easy, you just add a docstring at the top of the module.</p>
|
QA: | How do I document a module in Python? | <p>For the packages, you can document it in <code>__init__.py</code>.
For the modules, you can add a docstring simply in the module file.</p>
<p>All the information is here: <a href="http://www.python.org/dev/peps/pep-0257/">http://www.python.org/dev/peps/pep-0257/</a></p>
|
QA: | How do I document a module in Python? | <p>You do it the exact same way. Put a string in as the first statement in the module.</p>
|
QA: | Iterate over subclasses of a given class in a given module | <p>Here's one way to do it:</p>
<pre><code>import inspect
def get_subclasses(mod, cls):
"""Yield the classes in module ``mod`` that inherit from ``cls``"""
for name, obj in inspect.getmembers(mod):
if hasattr(obj, "__bases__") and cls in obj.__bases__:
yield obj
</code></pre>
|
QA: | Iterate over subclasses of a given class in a given module | <p>Given the module foo.py</p>
<pre><code>class foo(object): pass
class bar(foo): pass
class baz(foo): pass
class grar(Exception): pass
def find_subclasses(module, clazz):
for name in dir(module):
o = getattr(module, name)
try:
if issubclass(o, clazz):
yield name, o
except TypeError: pass
>>> import foo
>>> list(foo.find_subclasses(foo, foo.foo))
[('bar', <class 'foo.bar'>), ('baz', <class 'foo.baz'>), ('foo', <class 'foo.foo'>)]
>>> list(foo.find_subclasses(foo, object))
[('bar', <class 'foo.bar'>), ('baz', <class 'foo.baz'>), ('foo', <class 'foo.foo'>), ('grar', <class 'foo.grar'>)]
>>> list(foo.find_subclasses(foo, Exception))
[('grar', <class 'foo.grar'>)]
</code></pre>
|
QA: | How to merge two Python dictionaries in a single expression? | <p>I wanted something similar, but with the ability to specify how the values on duplicate keys were merged, so I hacked this out (but did not heavily test it). Obviously this is not a single expression, but it is a single function call.</p>
<pre><code>def merge(d1, d2, merge_fn=lambda x,y:y):
"""
Merges two dictionaries, non-destructively, combining
values on duplicate keys as defined by the optional merge
function. The default behavior replaces the values in d1
with corresponding values in d2. (There is no other generally
applicable merge strategy, but often you'll have homogeneous
types in your dicts, so specifying a merge technique can be
valuable.)
Examples:
>>> d1
{'a': 1, 'c': 3, 'b': 2}
>>> merge(d1, d1)
{'a': 1, 'c': 3, 'b': 2}
>>> merge(d1, d1, lambda x,y: x+y)
{'a': 2, 'c': 6, 'b': 4}
"""
result = dict(d1)
for k,v in d2.iteritems():
if k in result:
result[k] = merge_fn(result[k], v)
else:
result[k] = v
return result
</code></pre>
|
QA: | Pros and Cons of different approaches to web programming in Python | <p>OK, rails is actually pretty good, but there is just a little bit too much magic going on in there (from the Ruby world I would much prefer merb to rails). I personally use Pylons, and am pretty darn happy. I'd say (compared to django), that pylons allows you to interchange ints internal parts easier than django does. The downside is that you will have to write more stuff all by youself (like the basic CRUD). </p>
<p>Pros of using a framework:</p>
<ol>
<li>get stuff done quickly (and I mean lighning fast once you know the framework)</li>
<li>everything is compying to standards (which is probably not that easy to achieve when rolling your own)</li>
<li>easier to get something working (lots of tutorials) without reading gazillion articles and docs</li>
</ol>
<p>Cons:</p>
<ol>
<li>you learn less</li>
<li>harder to replace parts (not that much of an issue in pylons, more so with django)</li>
<li>harder to tweak some low-level stuff (like the above mentioned SQLs)</li>
</ol>
<p>From that you can probably devise what they are good for :-) Since you get all the code it is possible to tweak it to fit even the most bizzare situations (pylons supposedly work on the Google app engine now...).</p>
|
QA: | How would you make a comma-separated string from a list? | <pre><code>myList = ['a','b','c','d']
myString = ",".join(myList )
</code></pre>
<p>This won't work if the list contains numbers.</p>
<hr>
<p>As <a href="http://stackoverflow.com/users/3399/ricardo-reyes">Ricardo Reyes</a> suggested, if it contains non-string types (such as integers, floats, bools, None) then do:</p>
<pre><code>myList = ','.join(map(str, myList))
</code></pre>
|
QA: | How would you make a comma-separated string from a list? | <p>Why the map/lambda magic? Doesn't this work?</p>
<pre><code>>>>foo = [ 'a', 'b', 'c' ]
>>>print ",".join(foo)
a,b,c
>>>print ",".join([])
>>>print ",".join(['a'])
a
</code></pre>
<p>Edit: @mark-biek points out the case for numbers.
Perhaps the list comprehension:</p>
<pre><code>>>>','.join([str(x) for x in foo])
</code></pre>
<p>is more "pythonic".</p>
<p>Edit2:
Thanks for the suggestions. I'll use the generator rather than the list comprehension in the future.</p>
<pre><code>>>>','.join(str(x) for x in foo)
</code></pre>
|
QA: | How would you make a comma-separated string from a list? | <p>Don't you just want:</p>
<pre><code>",".join(l)
</code></pre>
<p>Obviously it gets more complicated if you need to quote/escape commas etc in the values. In that case I would suggest looking at the csv module in the standard library:</p>
<p><a href="https://docs.python.org/library/csv.html" rel="nofollow">https://docs.python.org/library/csv.html</a></p>
|
QA: | How would you make a comma-separated string from a list? | <p>Unless I'm missing something, <code>','.join(foo)</code> should do what you're asking for.</p>
<pre><code>>>> ','.join([''])
''
>>> ','.join(['s'])
's'
>>> ','.join(['a','b','c'])
'a,b,c'
</code></pre>
<p>(edit: and as jmanning2k points out, </p>
<pre><code>','.join([str(x) for x in foo])
</code></pre>
<p>is safer and quite Pythonic, though the resulting string will be difficult to parse if the elements can contain commas -- at that point, you need the full power of the <code>csv</code> module, as Douglas points out in his answer.)</p>
|
QA: | Can someone explain __all__ in Python? | <p>It's a list of public objects of that module. It overrides the default of hiding everything that begins with an underscore.</p>
|
QA: | Can someone explain __all__ in Python? | <p>From <a href="http://effbot.org/pyref/__all__.htm">(An Unofficial) Python Reference Wiki</a>:</p>
<blockquote>
<p>The public names defined by a module are determined by checking the module's namespace for a variable named <code>__all__</code>; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in <code>__all__</code> are all considered public and are required to exist. If <code>__all__</code> is not defined, the set of public names includes all names found in the module's namespace which do not begin with an underscore character ("_"). <code>__all__</code> should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).</p>
</blockquote>
|
QA: | How would you make a comma-separated string from a list? | <p>@jmanning2k using a list comprehension has the downside of creating a new temporary list. The better solution would be using itertools.imap which returns an iterator</p>
<pre><code>from itertools import imap
l = [1, "foo", 4 ,"bar"]
",".join(imap(str, l))
</code></pre>
|
QA: | Can the HTTP version or headers affect the visual appearance of a web page? | <p>Have you tried View -> Zoom -> Reset on both sites?</p>
|
QA: | Python packages - import by class, not file | <p>You need to put</p>
<pre><code>from project import Project
</code></pre>
<p>in <code>controllers/__init__.py</code>.</p>
<p>Note that when <a href="http://www.python.org/dev/peps/pep-0328/" rel="nofollow">Absolute imports</a> become the default (Python 2.7?), you will want to add a dot before the module name (to avoid collisions with a top-level model named <code>project</code>), i.e.,</p>
<pre><code>from .project import Project
</code></pre>
|
QA: | Where can I find the time and space complexity of the built-in sequence types in Python | <p>If your asking what I think your asking, you can find them <a href="http://books.google.com/books?id=vpTAq4dnmuAC&pg=RA1-PA476&lpg=RA1-PA476&dq=Big-O+of+Python+data+structures&source=web&ots=AOM5B5D7yA&sig=deLGb6VrftTpnNYN6fILVbiirXM&hl=en&sa=X&oi=book_result&resnum=7&ct=result#PRA1-PA479,M1" rel="nofollow">Here</a>... page 476 and on.</p>
<p>It's written around optimization techniques for Python; It's mostly Big-O notation of time efficiencies not much memory.</p>
|
QA: | Is there a Python library for generating .ico files? | <p>Perhaps the following would work:</p>
<ul>
<li>Generate your icon image using PIL</li>
<li>Convert the image to .ico format using the python interface to ImageMagick, <a href="http://www.imagemagick.org/download/python/">PythonMagick</a></li>
</ul>
<p>I have not tried this approach. The ImageMagick convert command line program was able to convert a .png file to .ico format, so at least ImageMagick supports the .ico format.</p>
|
QA: | Is there a Python library for generating .ico files? | <p>I don't know if this applies for all cases, but on WinXP an .ico can be a bmp of size 16x16, 32x32 or 64x64. Just change the extension to ico from bmp and you're ready to go.</p>
|
QA: | Where can I find the time and space complexity of the built-in sequence types in Python | <p>Raymond D. Hettinger does <a href="http://www.youtube.com/watch?v=hYUsssClE94" rel="nofollow">an excellent talk</a> (<a href="http://wenku.baidu.com/view/9c6fb20dcc1755270722089d.html" rel="nofollow">slides</a>) about Python's built-in collections called 'Core Python Containers - Under the Hood'. The version I saw focussed mainly on <code>set</code> and <code>dict</code>, but <code>list</code> was covered too.</p>
<p>There are also some photos of the pertinent slides from EuroPython in <a href="http://paranoid-engineering.blogspot.com/2008/07/europython-2008-day-3.html" rel="nofollow">a blog</a>.</p>
<p>Here is a summary of my notes on <code>list</code>:</p>
<ul>
<li>Stores items as an array of pointers. Subscript costs O(1) time. Append costs amortized O(1) time. Insert costs O(n) time.</li>
<li>Tries to avoid <code>memcpy</code> when growing by over-allocating. Many small lists will waste a lot of space, but large lists never waste more than about 12.5% to overallocation.</li>
<li>Some operations pre-size. Examples given were <code>range(n)</code>, <code>map()</code>, <code>list()</code>, <code>[None] * n</code>, and slicing.</li>
<li>When shrinking, the array is <code>realloc</code>ed only when it is wasting 50% of space. <code>pop</code> is cheap.</li>
</ul>
|
QA: | Wacom tablet Python interface | <p>You could perhaps take a look at the <a href="http://www.alexmac.cc/tablet-apps/tablet-apps-0.3.1.tar.bz2" rel="nofollow">software</a> described <a href="http://www.alexmac.cc/tablet-apps/" rel="nofollow">here</a>. It is a gnome applet, written in Python.</p>
<p>From the web site:</p>
<p>"The gnome wacom applet is a small gnome panel applet that shows how much pressure is being applied to your wacom tablet by the current device. Clicking on the panel icon brings up a dialog allowing you to select a different device and check what pressure and tilt information is being recieved from it. This dialog also contains a small drawing test area to give your pen a quick test."</p>
<p><a href="http://www.google.com/search?q=wacom+tablet+python" rel="nofollow">Google is your friend</a></p>
|
QA: | Is there a Python library for generating .ico files? | <p>According to <a href="http://en.wikipedia.org/wiki/Favicon">Wikipedia</a> modern browsers can handle favicons in PNG format, so maybe you could just generate that?</p>
<p>Alternatively the <a href="http://en.wikipedia.org/wiki/ICO_(icon_image_file_format)">ICO article</a> describes the format...</p>
|
QA: | Analizing MIPS binaries: is there a Python library for parsing binary data? | <p>I don't know of any, but if all else fails you could use <a href="http://docs.python.org/lib/module-ctypes.html" rel="nofollow">ctypes</a> to directly use libdwarf, libelf or libbfd.</p>
|
QA: | Where can I find the time and space complexity of the built-in sequence types in Python | <p>Checkout the <a href="http://wiki.python.org/moin/TimeComplexity">TimeComplexity</a> page on the py dot org wiki. It covers set/dicts/lists/etc at least as far as time complexity goes.</p>
|
QA: | How to know whether a window with a given title is already open in Tk? | <p>I believe you want:</p>
<pre><code>if 'normal' != root.state():
tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:]))
</code></pre>
|
QA: | How would you make a comma-separated string from a list? | <p>@<a href="#44878">Peter Hoffmann</a></p>
<p>Using generator expressions has the benefit of also producing an iterator but saves importing itertools. Furthermore, list comprehensions are generally preferred to map, thus, I'd expect generator expressions to be preferred to imap.</p>
<pre><code>>>> l = [1, "foo", 4 ,"bar"]
>>> ",".join(str(bit) for bit in l)
'1,foo,4,bar'
</code></pre>
|
QA: | Pylons error - 'MySQL server has gone away' | <p>I think I fixed it. It's turns out I had a simple config error. My ini file read:</p>
<pre><code>sqlalchemy.default.url = [connection string here]
sqlalchemy.pool_recycle = 1800
</code></pre>
<p>The problem is that my <code>environment.py</code> file declared that the engine would only map keys with the prefix: <code>sqlalchemy.default</code> so <code>pool_recycle</code> was ignored.</p>
<p>The solution is to simply change the second line in the ini to:</p>
<pre><code>sqlalchemy.default.pool_recycle = 1800
</code></pre>
|
QA: | Why Java and Python garbage collection methods are different? | <p>Reference counting is particularly difficult to do efficiently in a multi-threaded environment. I don't know how you'd even start to do it without getting into hardware assisted transactions or similar (currently) unusual atomic instructions.</p>
<p>Reference counting is easy to implement. JVMs have had a lot of money sunk into competing implementations, so it shouldn't be surprising that they implement very good solutions to very difficult problems. However, it's becoming increasingly easy to target your favourite language at the JVM.</p>
|
QA: | Iterate over subclasses of a given class in a given module | <p>Can I suggest that neither of the answers from Chris AtLee and zacherates fulfill the requirements?
I think this modification to zacerates answer is better:</p>
<pre><code>def find_subclasses(module, clazz):
for name in dir(module):
o = getattr(module, name)
try:
if (o != clazz) and issubclass(o, clazz):
yield name, o
except TypeError: pass
</code></pre>
<p>The reason I disagree with the given answers is that the first does not produce classes that are a distant subclass of the given class, and the second includes the given class.</p>
|
QA: | Which Version of Python to Use for Maximum Compatibility | <p>I've not seen a system with less than 2.3 installed for some time. Mostly 2.4+ is installed by default for most OS I use now. 2.3 is just on an older Solaris machine. Linux distros tend to have 2.4+, as does OS X.</p>
<p>IIRC, 2.4 has a lot of the features 2.5 does, but usable only with</p>
<pre><code>from __future__ import *
</code></pre>
|
QA: | Which Version of Python to Use for Maximum Compatibility | <p>As python is in kind of an transition phase towards python 3 with breaking backward compatibility I don't think it is a good idea to go python 3 only. Based on the <a href="http://www.python.org/dev/peps/pep-3000/#timeline" rel="nofollow">time line</a> there will be at least one or two following releases of the 2.x series after 2.6/3.0 in october.</p>
<p>Beside not having python 3 available on your target platforms, it will take some time until important external python libraries will be ported and usable on python 3.</p>
<p>So as Matthew suggests staying at 2.4/2.5 and keeping the <a href="http://www.python.org/dev/peps/pep-3000/#compatibility-and-transition" rel="nofollow">transition</a> plan to python 3 in mind is a solid choice.</p>
|
QA: | Django: Print url of view without hardcoding the url | <p>If you use <a href="https://docs.djangoproject.com/en/1.2/topics/http/urls/#naming-url-patterns" rel="nofollow">named url patterns</a> you can do the follwing in your template</p>
<pre><code>{% url create_object %}
</code></pre>
|
QA: | Django: Print url of view without hardcoding the url | <p>The preferred way of creating the URL is by adding a <code>get_absolute_url</code> method to your model classes. You can hardcode the path there so you at least get closer to following the KISS philosophy.</p>
<p>You can go further by utilizing the <code>permalink</code> decorator that figures the path based on the urls configuration.</p>
<p>You can read more in the django documentation <a href="https://docs.djangoproject.com/en/dev/ref/models/instances/#get-absolute-url" rel="nofollow">here</a>.</p>
|
QA: | Which Version of Python to Use for Maximum Compatibility | <p>You can use different versions of python on each machine. </p>
<p>Coding something new, I would not use anything less than python2.5. You can do <code>apt-get install python2.5</code> on stock debian stable. </p>
<p>For windows, don't really worry about it. It's very easy to install the python2.5 msi. </p>
<p>If the users can't be bothered to do that, you can deploy an executable with py2exe (so simple) and build an installer with inno setup (again simple) then it will behave like a standard windows application and will use its own python dlls, so no need to have python installed. </p>
<p>Like Peter said: keep in mind the transition to 3.0 but don't build on it yet.</p>
|
QA: | How do you set up a python wsgi server under IIS? | <p>There shouldn't be any need to use FastCGI. There exists a <a href="https://github.com/hexdump42/isapi-wsgi">ISAPI extension for WSGI</a>.</p>
|
QA: | Django: Print url of view without hardcoding the url | <p>You can use <code>get_absolute_url</code>, but that will only work for a particular object. Since your object hasn't been created yet, it won't work in this case.</p>
<p>You want to use <a href="https://docs.djangoproject.com/en/1.2/topics/http/urls/#naming-url-patterns" rel="nofollow">named URL patterns</a>. Here's a quick intro:</p>
<p>Change the line in your urls.py to:</p>
<pre><code>(r'^manage/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}, "create-product"),
</code></pre>
<p>Then, in your template you use this to display the URL:</p>
<pre><code>{% url create-product %}
</code></pre>
<p>If you're using Django 1.5 or higher you need this:</p>
<pre><code>{% url 'create-product' %}
</code></pre>
<p>You can do some more powerful things with named URL patterns, they're very handy. Note that they are only in the development version (and also 1.0).</p>
|
QA: | Is there a way to attach a debugger to a multi-threaded Python process? | <p>What platform are you attempting this on? Most debuggers allow you to attach to a running process by using the process id.
You can either output the process id via logging or using something like Task Manager.
Once that is achieved it will be possible to inspect individual threads and their call stacks.</p>
<p>EDIT: I don't have any experience with GNU Debugger (GDB), which is cross platform, however I found this <a href="http://wiki.python.org/moin/DebuggingWithGdb" rel="nofollow">link</a> and it may start you on the right path. It explains how to add debug symbols (handy for reading stack traces) and how to instruct gdb to attach to a running python process.</p>
|
QA: | Generator Expressions vs. List Comprehension | <p>Use list comprehensions when the result needs to be iterated over multiple times, or where speed is paramount. Use generator expressions where the range is large or infinite.</p>
|
QA: | Generator Expressions vs. List Comprehension | <p>Iterating over the <em>generator expression</em> or the <em>list comprehension</em> will do the same thing. However, the <em>list comprehension</em> will create the entire list in memory first while the <em>generator expression</em> will create the items on the fly, so you are able to use it for very large (and also infinite!) sequences.</p>
|