prefix
stringclasses
1 value
input_text
stringlengths
10
172
target_text
stringlengths
18
33.9k
QA:
Sanitising user input using Python
<p>I don't do web development much any longer, but when I did, I did something like so:</p> <p>When no parsing is supposed to happen, I usually just escape the data to not interfere with the database when I store it, and escape everything I read up from the database to not interfere with html when I display it (cgi.escape() in python).</p> <p>Chances are, if someone tried to input html characters or stuff, they actually wanted that to be displayed as text anyway. If they didn't, well tough :)</p> <p>In short always escape what can affect the current target for the data.</p> <p>When I did need some parsing (markup or whatever) I usually tried to keep that language in a non-intersecting set with html so I could still just store it suitably escaped (after validating for syntax errors) and parse it to html when displaying without having to worry about the data the user put in there interfering with your html.</p> <p>See also <a href="http://wiki.python.org/moin/EscapingHtml" rel="nofollow">Escaping HTML</a></p>
QA:
Binary buffer in Python
<p>As long as you don't try to put any unicode data into your <code>StringIO</code> and you are careful NOT to use <code>cStringIO</code> you should be fine.</p> <p>According to the <a href="https://docs.python.org/library/stringio.html" rel="nofollow">StringIO</a> documentation, as long as you keep to either unicode or 8-bits everything works as expected. Presumably, <code>StringIO</code> does something special when someone does a <code>f.write(u"asdf")</code> (which ZipFile does not do, to my knowledge). Anyway;</p> <pre><code>import zipfile import StringIO s = StringIO.StringIO() z = zipfile.ZipFile(s, "w") z.write("test.txt") z.close() f = file("x.zip", "w") f.write(s.getvalue()) s.close() f.close() </code></pre> <p>works just as expected, and there's no difference between the file in the resulting archive and the original file.</p> <p>If you know of a particular case where this approach does not work, I'd be most interested to hear about it :)</p>
QA:
A Transpose/Unzip Function in Python (inverse of zip)
<p>You could also do</p> <pre><code>result = ([ a for a,b in original ], [ b for a,b in original ]) </code></pre> <p>It <em>should</em> scale better. Especially if Python makes good on not expanding the list comprehensions unless needed.</p> <p>(Incidentally, it makes a 2-tuple (pair) of lists, rather than a list of tuples, like <code>zip</code> does.)</p> <p>If generators instead of actual lists are ok, this would do that:</p> <pre><code>result = (( a for a,b in original ), ( b for a,b in original )) </code></pre> <p>The generators don't munch through the list until you ask for each element, but on the other hand, they do keep references to the original list.</p>
QA:
cx_Oracle: How do I iterate over a result set?
<p>There's also the way <code>psyco-pg</code> seems to do it... From what I gather, it seems to create dictionary-like row-proxies to map key lookup into the memory block returned by the query. In that case, fetching the whole answer and working with a similar proxy-factory over the rows seems like useful idea. Come to think of it though, it feels more like Lua than Python.</p> <p>Also, this should be applicable to all <a href="http://www.python.org/dev/peps/pep-0249/" rel="nofollow">PEP-249 DBAPI2.0</a> interfaces, not just Oracle, or did you mean just <em>fastest</em> using <em>Oracle</em>?</p>
QA:
pyGame within a pyGTK application
<p>You may be interested in <a href="http://www.daa.com.au/pipermail/pygtk/2006-September/012888.html" rel="nofollow">this message thread</a>. Looks like they recommend against it.</p>
QA:
Python super class reflection
<p><code>C.__bases__</code> is an array of the super classes, so you could implement your hypothetical function like so:</p> <pre><code>def magicGetSuperClasses(cls): return cls.__bases__ </code></pre> <p>But I imagine it would be easier to just reference <code>cls.__bases__</code> directly in most cases.</p>
QA:
Is there any difference between "foo is None" and "foo == None"?
<p><code>is</code> always returns <code>True</code> if it compares the same object instance</p> <p>Whereas <code>==</code> is ultimately determined by the <code>__eq__()</code> method</p> <p>i.e.</p> <pre><code> >>> class foo(object): def __eq__(self, other): return True >>> f = foo() >>> f == None True >>> f is None False </code></pre>
QA:
Is there any difference between "foo is None" and "foo == None"?
<p>You may want to read this <a href="http://mail.python.org/pipermail/python-list/2001-November/094920.html">object identity and equivalence</a>.</p> <p>The statement 'is' is used for object identity, it checks if objects refer to the same instance (same address in memory).</p> <p>And the '==' statement refers to equality (same value).</p>
QA:
Is there any difference between "foo is None" and "foo == None"?
<p>For None there shouldn't be a difference between equality (==) and identity (is). The NoneType probably returns identity for equality. Since None is the only instance you can make of NoneType (I think this is true), the two operations are the same. In the case of other types this is not always the case. For example:</p> <pre><code>list1 = [1, 2, 3] list2 = [1, 2, 3] if list1==list2: print "Equal" if list1 is list2: print "Same" </code></pre> <p>This would print "Equal" since lists have a comparison operation that is not the default returning of identity.</p>
QA:
wxpython: How do I examine dragged data in OnDragOver?
<p>One solution, which is a hack of limited usefulness, is when a drag is initiated, store the dragged data in a global or static reference somewhere. This way, in the OnEnter and OnDragOver handlers, it is possible to get a reference to the data being dragged. This is of course only useful for drags within the same application (the same instance of the application, actually).</p>
QA:
What's the best way to grab/parse command line arguments passed to a Python script?
<p><strong>This answer suggests <code>optparse</code> which is appropriate for older Python versions. For Python 2.7 and above, <code>argparse</code> replaces <code>optparse</code>. See <a href="http://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse">this answer</a> for more information.</strong></p> <p>As other people pointed out, you are better off going with optparse over getopt. getopt is pretty much a one-to-one mapping of the standard getopt(3) C library functions, and not very easy to use.</p> <p>optparse, while being a bit more verbose, is much better structured and simpler to extend later on.</p> <p>Here's a typical line to add an option to your parser:</p> <pre><code>parser.add_option('-q', '--query', action="store", dest="query", help="query string", default="spam") </code></pre> <p>It pretty much speaks for itself; at processing time, it will accept -q or --query as options, store the argument in an attribute called query and has a default value if you don't specify it. It is also self-documenting in that you declare the help argument (which will be used when run with -h/--help) right there with the option.</p> <p>Usually you parse your arguments with:</p> <pre><code>options, args = parser.parse_args() </code></pre> <p>This will, by default, parse the standard arguments passed to the script (sys.argv[1:])</p> <p>options.query will then be set to the value you passed to the script.</p> <p>You create a parser simply by doing</p> <pre><code>parser = optparse.OptionParser() </code></pre> <p>These are all the basics you need. Here's a complete Python script that shows this:</p> <pre><code>import optparse parser = optparse.OptionParser() parser.add_option('-q', '--query', action="store", dest="query", help="query string", default="spam") options, args = parser.parse_args() print 'Query string:', options.query </code></pre> <p>5 lines of python that show you the basics.</p> <p>Save it in sample.py, and run it once with</p> <pre><code>python sample.py </code></pre> <p>and once with</p> <pre><code>python sample.py --query myquery </code></pre> <p>Beyond that, you will find that optparse is very easy to extend. In one of my projects, I created a Command class which allows you to nest subcommands in a command tree easily. It uses optparse heavily to chain commands together. It's not something I can easily explain in a few lines, but feel free to <a href="https://thomas.apestaart.org/moap/trac/browser/trunk/moap/extern/command/command.py">browse around in my repository</a> for the main class, as well as <a href="https://thomas.apestaart.org/moap/trac/browser/trunk/moap/command/doap.py">a class that uses it and the option parser</a></p>
QA:
Find broken symlinks with Python
<p>A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two calls in your code.</p> <p><strong>A typical mistake is to write something like</strong>:</p> <pre><code>if os.path.exists(path): os.unlink(path) </code></pre> <p>The second call (os.unlink) may fail if something else deleted it after your if test, raise an Exception, and stop the rest of your function from executing. (You might think this doesn't happen in real life, but we just fished another bug like that out of our codebase last week - and it was the kind of bug that left a few programmers scratching their head and claiming 'Heisenbug' for the last few months)</p> <p>So, in your particular case, I would probably do:</p> <pre><code>try: os.stat(path) except OSError, e: if e.errno == errno.ENOENT: print 'path %s does not exist or is a broken symlink' % path else: raise e </code></pre> <p>The annoyance here is that stat returns the same error code for a symlink that just isn't there and a broken symlink.</p> <p>So, I guess you have no choice than to break the atomicity, and do something like</p> <pre><code>if not os.path.exists(os.readlink(path)): print 'path %s is a broken symlink' % path </code></pre>
QA:
Is there any difference between "foo is None" and "foo == None"?
<p>@<a href="http://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none#26698" rel="nofollow">Jason</a>:</p> <blockquote> <p>I recommend using something more along the lines of</p> <pre><code>if foo: #foo isn't None else: #foo is None </code></pre> </blockquote> <p>I don't like using "if foo:" unless foo truly represents a boolean value (i.e. 0 or 1). If foo is a string or an object or something else, "if foo:" may work, but it looks like a lazy shortcut to me. If you're checking to see if x is None, say "if x is None:".</p>
QA:
Where can I learn more about PyPy's translation function?
<p>Are you looking for Python specific translation, or just the general "how do you compile some code to bytecode"? If the latter is your case, check <a href="http://llvm.org/docs/tutorial/" rel="nofollow">the LLVM tutorial</a>. I especially find chapter two, which teaches you to write a compiler for your own language, interesting.</p>
QA:
Class views in Django
<p>If you want to share common functionality between pages I suggest you look at custom tags. They're quite <a href="https://docs.djangoproject.com/en/1.1/howto/custom-template-tags/" rel="nofollow">easy to create</a>, and are very powerful.</p> <p>Also, <a href="https://code.djangoproject.com/wiki/ExtendingTemplates" rel="nofollow">templates can extend from other templates</a>. This allows you to have a base template to set up the layout of the page and to share this between other templates which fill in the blanks. You can nest templates to any depth; allowing you to specify the layout on separate groups of related pages in one place.</p>
QA:
Class views in Django
<p>You can always create a class, override the <em><code>__call__</code></em> function and then point the URL file to an instance of the class. You can take a look at the <a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/formtools/wizard.py" rel="nofollow">FormWizard</a> class to see how this is done.</p>
QA:
How to use Xpath in Python?
<p><a href="http://xmlsoft.org/python.html">libxml2</a> has a number of advantages:</p> <ol> <li>Compliance to the <a href="http://www.w3.org/TR/xpath">spec</a></li> <li>Active development and a community participation </li> <li>Speed. This is really a python wrapper around a C implementation. </li> <li>Ubiquity. The libxml2 library is pervasive and thus well tested.</li> </ol> <p>Downsides include:</p> <ol> <li>Compliance to the <a href="http://www.w3.org/TR/xpath">spec</a>. It's strict. Things like default namespace handling are easier in other libraries.</li> <li>Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain.</li> <li>Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic.</li> </ol> <p>If you are doing simple path selection, stick with <a href="http://effbot.org/zone/element-xpath.htm">ElementTree</a> ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2.</p> <p><strong>Sample of libxml2 XPath Use</strong></p> <hr> <pre><code>import libxml2 doc = libxml2.parseFile("tst.xml") ctxt = doc.xpathNewContext() res = ctxt.xpathEval("//*") if len(res) != 2: print "xpath query: wrong node set size" sys.exit(1) if res[0].name != "doc" or res[1].name != "foo": print "xpath query: wrong node set value" sys.exit(1) doc.freeDoc() ctxt.xpathFreeContext() </code></pre> <p><strong>Sample of ElementTree XPath Use</strong></p> <hr> <pre><code>from elementtree.ElementTree import ElementTree mydoc = ElementTree(file='tst.xml') for e in mydoc.findall('/foo/bar'): print e.get('title').text</code></pre> <hr>
QA:
Is there any difference between "foo is None" and "foo == None"?
<p>A word of caution: </p> <pre><code>if foo: # do something </code></pre> <p>Is <strong>not</strong> exactly the same as:</p> <pre><code>if x is not None: # do something </code></pre> <p>The former is a boolean value test and can evaluate to false in different contexts. There are a number of things that represent false in a boolean value tests for example empty containers, boolean values. None also evaluates to false in this situation but other things do too.</p>
QA:
Does PHP have an equivalent to this type of Python string substitution?
<p>Some of the user-contributed notes and functions in <a href="http://us3.php.net/sprintf" rel="nofollow">PHP's documentation for sprintf</a> come quite close.</p> <p>Note: search the page for "sprintf2".</p>
QA:
Does PHP have an equivalent to this type of Python string substitution?
<pre><code>function subst($str, $dict){ return preg_replace(array_map(create_function('$a', 'return "/%\\($a\\)s/";'), array_keys($dict)), array_values($dict), $str); } </code></pre> <p>You call it like so:</p> <pre><code>echo subst('The %(site)s site %(adj)s because it %(adj)s', array('site'=&gt;'Stackoverflow', 'adj'=&gt;'rocks')); </code></pre>
QA:
Does PHP have an equivalent to this type of Python string substitution?
<p>@<a href="http://stackoverflow.com/questions/28165/does-php-have-an-equivalent-to-this-type-of-python-string-substitution#28199" rel="nofollow">Marius</a></p> <p>I don't know if it's faster, but you can do it without regexes:</p> <pre><code>function subst($str, $dict) { foreach ($dict AS $key, $value) { $str = str_replace($key, $value, $str); } return $str; } </code></pre>
QA:
How to check what OS am I running on in Python?
<p>You can also use sys.platform if you already have imported sys and you don't want to import another module</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.platform 'linux2' </code></pre>
QA:
Is "safe_eval" really safe?
<p>Writing your own parser could be fun! It might be a better option because people are expecting to use the familiar spreadsheet syntax (Excel, etc) and not Python when they're entering formulas. I'm not familiar with safe_eval but I would imagine that anything like this certainly has the potential for exploitation.</p>
QA:
Prototyping with Python code before compiling
<p>I haven't used SWIG or SIP, but I find writing Python wrappers with <a href="http://www.boost.org/doc/libs/1_35_0/libs/python/doc/index.html" rel="nofollow">boost.python</a> to be very powerful and relatively easy to use.</p> <p>I'm not clear on what your requirements are for passing types between C/C++ and python, but you can do that easily by either exposing a C++ type to python, or by using a generic <a href="http://www.boost.org/doc/libs/1_35_0/libs/python/doc/v2/object.html" rel="nofollow">boost::python::object</a> argument to your C++ API. You can also register converters to automatically convert python types to C++ types and vice versa.</p> <p>If you plan use boost.python, the <a href="http://www.boost.org/doc/libs/1_35_0/libs/python/doc/tutorial/doc/html/index.html" rel="nofollow">tutorial</a> is a good place to start.</p> <p>I have implemented something somewhat similar to what you need. I have a C++ function that accepts a python function and an image as arguments, and applies the python function to each pixel in the image.</p> <pre><code>Image* unary(boost::python::object op, Image&amp; im) { Image* out = new Image(im.width(), im.height(), im.channels()); for(unsigned int i=0; i&lt;im.size(); i++) { (*out)[i] == extract&lt;float&gt;(op(im[i])); } return out; } </code></pre> <p>In this case, Image is a C++ object exposed to python (an image with float pixels), and op is a python defined function (or really any python object with a &#95;&#95;call&#95;&#95; attribute). You can then use this function as follows (assuming unary is located in the called image that also contains Image and a load function):</p> <pre><code>import image im = image.load('somefile.tiff') double_im = image.unary(lambda x: 2.0*x, im) </code></pre> <p>As for using arrays with boost, I personally haven't done this, but I know the functionality to expose arrays to python using boost is available - <a href="http://www.boost.org/doc/libs/1_35_0/libs/python/doc/v2/faq.html#question2" rel="nofollow">this</a> might be helpful.</p>
QA:
Most Pythonic way equivalent for: while ((x = next()) != END)
<p>Maybe it's not terribly idiomatic, but I'd be inclined to go with</p> <pre><code>x = next() while x != END: do_something_with_x x = next() </code></pre> <p>... but that's because I find that sort of thing easy to read</p>
QA:
Most Pythonic way equivalent for: while ((x = next()) != END)
<p>What are you trying to do here? If you're iterating over a list, you can use <code>for e in L</code> where e is the element and L is the list. If you're filtering a list, you can use list comprehensions (i.e. <code>[ e for e in L if e % 2 == 0 ]</code> to get all the even numbers in a list).</p>
QA:
Most Pythonic way equivalent for: while ((x = next()) != END)
<p>It depends a bit what you want to do. To match your example as far as possible, I would make next a generator and iterate over it:</p> <pre><code>def next(): for num in range(10): yield num for x in next(): print x </code></pre>
QA:
Most Pythonic way equivalent for: while ((x = next()) != END)
<p>If you need to do this more than once, the pythonic way would use an iterator</p> <pre><code>for x in iternext(): do_something_with_x </code></pre> <p>where <code>iternext</code> would be defined using something like (<a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">explicit is better than implicit!</a>):</p> <pre><code>def iternext(): x = next() while x != END: yield x x = next() </code></pre>
QA:
Best way to extract data from a FileMaker Pro database in a script?
<p>It has been a <strong>really</strong> long time since I did anything with FileMaker Pro, but I know that it does have capabilities for an ODBC (and JDBC) connection to be made to it (however, I don't know how, or if, that translates to the linux/perl/python world though). </p> <p>This article shows how to share/expose your FileMaker data via ODBC &amp; JDBC:<br /> <a href="http://www.filemaker.com/help/15-Using%20ODBC2.html">Sharing FileMaker Pro data via ODBC or JDBC</a> </p> <p>From there, if you're able to create an ODBC/JDBC connection you could query out data as needed.</p>
QA:
Accessing mp3 Meta-Data with Python
<p>If you can use IronPython, there is TagLibSharp. <a href="http://stackoverflow.com/questions/28664/what-is-the-besta-very-good-meta-data-reader-library#28687">It can be used from any .NET language</a>.</p>
QA:
Most Pythonic way equivalent for: while ((x = next()) != END)
<p>Short answer: there's no way to do inline variable assignment in a while loop in Python. Meaning that I <strong>cannot</strong> say:</p> <pre><code>while x=next(): // do something here! </code></pre> <p>Since that's not possible, there are a number of "idiomatically correct" ways of doing this:</p> <pre><code>while 1: x = next() if x != END: // Blah else: break </code></pre> <p>Obviously, this is kind of ugly. You can also use one of the "iterator" approaches listed above, but, again, that may not be ideal. Finally, you can use the "pita pocket" approach that I actually just found while googling:</p> <pre><code>class Pita( object ): __slots__ = ('pocket',) marker = object() def __init__(self, v=marker): if v is not self.marker: self.pocket = v def __call__(self, v=marker): if v is not self.marker: self.pocket = v return self.pocket </code></pre> <p>Now you can do:</p> <pre><code>p = Pita() while p( next() ) != END: // do stuff with p.pocket! </code></pre> <p>Thanks for this question; learning about the <code>__call__</code> idiom was really cool! :)</p> <p>EDIT: I'd like to give credit where credit is due. The 'pita pocket' idiom was found <a href="http://mail.python.org/pipermail/python-list/2003-July/216789.html" rel="nofollow">here</a></p>
QA:
Most Pythonic way equivalent for: while ((x = next()) != END)
<p>Can you provide more information about what you're trying to accomplish? It's not clear to me why you can't just say</p> <pre><code>for x in everything(): ... </code></pre> <p>and have the everything function return everything, instead of writing a next function to just return one thing at a time. Generators can even do this quite efficiently.</p>
QA:
pyGame within a pyGTK application
<p>I've never attempted it myself, but hearing plenty about other people who've tried, it's not a road you want to go down.</p> <p>There is the alternative of putting the gui in pygame itself. There are plenty of gui toolkits built specifically for pygame that you could use. Most of them are rather unfinished, but there are 2 big, actively maintained ones: <a href="http://www.pygame.org/project/108/" rel="nofollow">PGU</a> and <a href="http://www.pygame.org/project/125/" rel="nofollow">OcempGUI</a>. The full list on the pygame site is <a href="http://www.pygame.org/tags/gui" rel="nofollow">here</a>.</p>
QA:
How to capture Python interpreter's and/or CMD.EXE's output from a Python script?
<p>Actually, you definitely can, and it's beautiful, ugly, and crazy at the same time!</p> <p>You can replace sys.stdout and sys.stderr with StringIO objects that collect the output.</p> <p>Here's an example, save it as evil.py:</p> <pre><code>import sys import StringIO s = StringIO.StringIO() sys.stdout = s print "hey, this isn't going to stdout at all!" print "where is it ?" sys.stderr.write('It actually went to a StringIO object, I will show you now:\n') sys.stderr.write(s.getvalue()) </code></pre> <p>When you run this program, you will see that:</p> <ul> <li>nothing went to stdout (where print usually prints to)</li> <li>the first string that gets written to stderr is the one starting with 'It'</li> <li>the next two lines are the ones that were collected in the StringIO object</li> </ul> <p>Replacing sys.stdout/err like this is an application of what's called monkeypatching. Opinions may vary whether or not this is 'supported', and it is definitely an ugly hack, but it has saved my bacon when trying to wrap around external stuff once or twice.</p> <p>Tested on Linux, not on Windows, but it should work just as well. Let me know if it works on Windows!</p>
QA:
How do I create an xml document in python
<p>Setting an attribute on an object won't give a compile-time or a run-time error, it will just do nothing useful if the object doesn't access it (i.e. "<code>node.noSuchAttr = 'bar'</code>" would also not give an error).</p> <p>Unless you need a specific feature of <code>minidom</code>, I would look at <code>ElementTree</code>:</p> <pre><code>import sys from xml.etree.cElementTree import Element, ElementTree def make_xml(): node = Element('foo') node.text = 'bar' doc = ElementTree(node) return doc if __name__ == '__main__': make_xml().write(sys.stdout) </code></pre>
QA:
How do I create an xml document in python
<p>@Daniel</p> <p>Thanks for the reply, I also figured out how to do it with the minidom (I'm not sure of the difference between the ElementTree vs the minidom)</p> <pre> <code> from xml.dom.minidom import * def make_xml(): doc = Document(); node = doc.createElement('foo') node.appendChild(doc.createTextNode('bar')) doc.appendChild(node) return doc if __name__ == '__main__': make_xml().writexml(sys.stdout) </code> </pre> <p>I swear I tried this before posting my question...</p>
QA:
How do I create an xml document in python
<p>I found a <a href="http://www.boddie.org.uk/python/XML_intro.html" rel="nofollow">pretty verbose tutorial on the minidom method</a></p> <p>Here's a <a href="http://drfox.com/cgi-bin/topic_display.py?name=climbing_etree" rel="nofollow">tutorial for the etree method</a>. It's much nicer to read, and seems quite simple. It also goes over parsing of xml (briefly)</p>
QA:
What refactoring tools do you use for Python?
<p>Most editors support the "whole word" search option. It's usually a checkbox in the search dialog, and what it does is only match the search term if it has leading and trailing spaces, dots, and most other delimiters. It will probably work in your case.</p>
QA:
Is "safe_eval" really safe?
<p>Although that code looks quite secure, I've always held the opinion that any sufficiently motivated person could break it given adequate time. I do think it will take quite a bit of determination to get through that, but I'm relatively sure it could be done.</p>
QA:
Python distutils - does anyone know how to use it?
<p>See the <a href="http://docs.python.org/dist/simple-example.html" rel="nofollow">distutils simple example</a>. That's basically what it is like, except real install scripts usually contain a bit more information. I have not seen any that are fundamentally more complicated, though. In essence, you just give it a list of what needs to be installed. Sometimes you need to give it some mapping dicts since the source and installed trees might not be the same.</p> <p>Here is a real-life (anonymized) example:</p> <pre><code>#!/usr/bin/python from distutils.core import setup setup (name = 'Initech Package 3', description = "Services and libraries ABC, DEF", author = "That Guy, Initech Ltd", author_email = "[email protected]", version = '1.0.5', package_dir = {'Package3' : 'site-packages/Package3'}, packages = ['Package3', 'Package3.Queries'], data_files = [ ('/etc/Package3', ['etc/Package3/ExternalResources.conf']) ]) </code></pre>
QA:
What refactoring tools do you use for Python?
<p>In the meantime, I've tried it two tools that have some sort of integration with vim.</p> <p>The first is <a href="http://rope.sourceforge.net/">Rope</a>, a python refactoring library that comes with a Vim (and emacs) plug-in. I tried it for a few renames, and that definitely worked as expected. It allowed me to preview the refactoring as a diff, which is nice. It is a bit text-driven, but that's alright for me, just takes longer to learn.</p> <p>The second is <a href="http://bicyclerepair.sourceforge.net/">Bicycle Repair Man</a> which I guess wins points on name. Also plugs into vim and emacs. Haven't played much with it yet, but I remember trying it a long time ago.</p> <p>Haven't played with both enough yet, or tried more types of refactoring, but I will do some more hacking with them.</p>
QA:
Python distutils - does anyone know how to use it?
<p>Most Python programs will use distutils. <a href="http://www.djangoproject.com" rel="nofollow">Django</a> is a one - see <a href="http://code.djangoproject.com/svn/django/trunk/setup.py" rel="nofollow">http://code.djangoproject.com/svn/django/trunk/setup.py</a></p> <p>You should also read <a href="http://docs.python.org/dist/dist.html" rel="nofollow">the documentation</a>, as it's very comprehensive and has some good examples.</p>
QA:
Install Python to match directory layout in OS X 10.5
<p>Not sure I entirely understand your question, but can't you simply build and install a 64 bit version and then create symbolic links so that /Library/Python/2.5 and below point to your freshly built version of python?</p>
QA:
What's the best way to grab/parse command line arguments passed to a Python script?
<p>I think the best way for larger projects is optparse, but if you are looking for an easy way, maybe <a href="http://werkzeug.pocoo.org/documentation/script" rel="nofollow">http://werkzeug.pocoo.org/documentation/script</a> is something for you.</p> <pre><code>from werkzeug import script # actions go here def action_foo(name=""): """action foo does foo""" pass def action_bar(id=0, title="default title"): """action bar does bar""" pass if __name__ == '__main__': script.run() </code></pre> <p>So basically every function action_* is exposed to the command line and a nice help message is generated for free. </p> <pre><code>python foo.py usage: foo.py &lt;action&gt; [&lt;options&gt;] foo.py --help actions: bar: action bar does bar --id integer 0 --title string default title foo: action foo does foo --name string </code></pre>
QA:
Using 'in' to match an attribute of Python objects in an array
<p>you could always write one yourself:</p> <pre><code>def iterattr(iterator, attributename): for obj in iterator: yield getattr(obj, attributename) </code></pre> <p>will work with anything that iterates, be it a tuple, list, or whatever.</p> <p>I love python, it makes stuff like this very simple and no more of a hassle than neccessary, and in use stuff like this is hugely elegant.</p>
QA:
Using 'in' to match an attribute of Python objects in an array
<p>If you plan on searching anything of remotely decent size, your best bet is going to be to use a dictionary or a set. Otherwise, you basically have to iterate through every element of the iterator until you get to the one you want.</p> <p>If this isn't necessarily performance sensitive code, then the list comprehension way should work. But note that it is fairly inefficient because it goes over every element of the iterator and then goes BACK over it again until it finds what it wants.</p> <p>Remember, python has one of the most efficient hashing algorithms around. Use it to your advantage.</p>
QA:
Python distutils - does anyone know how to use it?
<p>distutils really isn't all that difficult once you get the hang of it. It's really just a matter of putting in some meta-information (program name, author, version, etc) and then selecting what files you want to include. For example, here's a sample distutils setup.py module from a decently complex python library:</p> <p><a href="http://code.google.com/p/kamaelia/source/browse/trunk/Code/Python/Kamaelia/setup.py" rel="nofollow">Kamaelia setup.py</a></p> <p>Note that this doesn't deal with any data files or or whatnot, so YMMV.</p> <p>On another note, I agree that the distutils documentation is probably some of python's worst documentation. It is extremely inclusive in some areas, but neglects some really important information in others.</p>
QA:
Install Python to match directory layout in OS X 10.5
<p>Essentially, yes. I was not sure you could do it like that (current version does not do it like that). When using the python install script, however, there is no option (that I can find) to specify where to put directories and files (eg --prefix). I was hoping to match the current layout of python related files so as to avoid 'polluting' my machine with redundant files.</p>
QA:
How do threads work in Python, and what are common Python-threading specific pitfalls?
<p>Below is a basic threading sample. It will spawn 20 threads; each thread will output its thread number. Run it and observe the order in which they print.</p> <pre><code>import threading class Foo (threading.Thread): def __init__(self,x): self.__x = x threading.Thread.__init__(self) def run (self): print str(self.__x) for x in xrange(20): Foo(x).start() </code></pre> <p>As you have hinted at Python threads are implemented through time-slicing. This is how they get the "parallel" effect. </p> <p>In my example my Foo class extends thread, I then implement the <code>run</code> method, which is where the code that you would like to run in a thread goes. To start the thread you call <code>start()</code> on the thread object, which will automatically invoke the <code>run</code> method...</p> <p>Of course, this is just the very basics. You will eventually want to learn about semaphores, mutexes, and locks for thread synchronization and message passing.</p>
QA:
How do threads work in Python, and what are common Python-threading specific pitfalls?
<p>Python's a fairly easy language to thread in, but there are caveats. The biggest thing you need to know about is the Global Interpreter Lock. This allows only one thread to access the interpreter. This means two things: 1) you rarely ever find yourself using a lock statement in python and 2) if you want to take advantage of multi-processor systems, you have to use separate processes. EDIT: I should also point out that you can put some of the code in C/C++ if you want to get around the GIL as well.</p> <p>Thus, you need to re-consider why you want to use threads. If you want to parallelize your app to take advantage of dual-core architecture, you need to consider breaking your app up into multiple processes.</p> <p>If you want to improve responsiveness, you should CONSIDER using threads. There are other alternatives though, namely <a href="http://en.wikipedia.org/wiki/Microthread" rel="nofollow">microthreading</a>. There are also some frameworks that you should look into:</p> <ul> <li><a href="http://www.stackless.com/" rel="nofollow">stackless python</a></li> <li><a href="http://greenlet.readthedocs.org/en/latest/" rel="nofollow">greenlets</a></li> <li><a href="http://www.gevent.org/" rel="nofollow">gevent</a></li> <li><a href="https://github.com/saucelabs/monocle" rel="nofollow">monocle</a></li> </ul>
QA:
Install Python to match directory layout in OS X 10.5
<p>Personally, I wouldn't worry about it until you see a problem. Messing with the default python install on a *Nix system can cause more trouble than it's worth. I can say from personal experience that you never truly understand what python has done for the nix world until you have a problem with it.</p> <p>You can also add a second python installation, but that also causes more problems than it's worth IMO.</p> <p>So I suppose the best question to start out with would be why exactly do you want to use the 64 bit version of python?</p>
QA:
How do threads work in Python, and what are common Python-threading specific pitfalls?
<p>Yes, because of the Global Interpreter Lock (GIL) there can only run one thread at a time. Here are some links with some insights about this:</p> <ul> <li><a href="http://www.artima.com/weblogs/viewpost.jsp?thread=214235">http://www.artima.com/weblogs/viewpost.jsp?thread=214235</a></li> <li><a href="http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/">http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/</a></li> </ul> <p>From the last link an interesting quote:</p> <blockquote> <p>Let me explain what all that means. Threads run inside the same virtual machine, and hence run on the same physical machine. Processes can run on the same physical machine or in another physical machine. If you architect your application around threads, you’ve done nothing to access multiple machines. So, you can scale to as many cores are on the single machine (which will be quite a few over time), but to really reach web scales, you’ll need to solve the multiple machine problem anyway.</p> </blockquote> <p>If you want to use multi core, <a href="http://www.python.org/dev/peps/pep-0371/">pyprocessing</a> defines an process based API to do real parallelization. The <a href="http://en.wikipedia.org/wiki/Python_Enhancement_Proposal#Development">PEP</a> also includes some interesting benchmarks.</p>
QA:
Install Python to match directory layout in OS X 10.5
<p>The short answer is because I can. The long answer, expanding on what the OP said, is to be more compatible with apache and mysql/postgresql. They are all 64bit (apache is a fat binary with ppc, ppc64 x86 and x86 and x86_64, the others just straight 64bit). <strong>Mysqldb and mod_python wont compile unless they are all running the same architecture.</strong> Yes I could run them all in 32bit (and have in the past) but this is much more work then compiling one program.</p> <p>EDIT: You pretty much convinced though to just let the installer do its thing and update the PATH to reflect this.</p>
QA:
How do threads work in Python, and what are common Python-threading specific pitfalls?
<p>Use threads in python if the individual workers are doing I/O bound operations. If you are trying to scale across multiple cores on a machine either find a good <a href="http://www.python.org/dev/peps/pep-0371/">IPC</a> framework for python or pick a different language.</p>
QA:
Install Python to match directory layout in OS X 10.5
<p>Hyposaurus,</p> <p>It is possible to have multiple versions of Python installed simultaneously. Installing two versions in parallel solves your problem and helps avoid the problems laid out by Jason Baker above. </p> <p>The easiest way, and the way I recommend, is to use <a href="http://www.macports.org/" rel="nofollow">MacPorts</a>, which will install all its software separately. By default, for example, everything is installed in /opt/local</p> <p>Another method is to simply download the source and compile with a specified prefix. Note that this method doesn't modify your PATH environment variable, so you'll need to do that yourself if you want to avoid typing the fully qualified path to the python executable each time</p> <pre><code>./configure --prefix=/usr/local/python64 make sudo make install </code></pre> <p>Then you can simply point your Apache install at the new version using mod_python's <a href="http://www.modpython.org/live/current/doc-html/dir-other-pi.html" rel="nofollow">PythonInterpreter</a> directive</p>
QA:
How can I create a directly-executable cross-platform GUI app using Python?
<p>Another system (not mentioned in the accepted answer yet) is PyInstaller, which worked for a PyQt project of mine when py2exe would not. I found it easier to use.</p> <p><a href="http://www.pyinstaller.org/">http://www.pyinstaller.org/</a></p> <p>Pyinstaller is based on Gordon McMillan's Python Installer. Which is no longer available.</p>
QA:
What's the best way to use web services in python?
<p>If I have to expose APIs, I prefer doing it as JSON. Python has excellent support for JSON objects (JSON Objects are infact python dictionaries)</p>
QA:
pyGame within a pyGTK application
<p>PyGame works much better when it can manage its own window, or even better, use the whole screen. GTK has flexible enough widgets to allow creation of a drawing area. </p> <p><a href="http://faq.pygtk.org/index.py?req=show&amp;file=faq23.042.htp" rel="nofollow">This page</a> may help, though, if you want to try it.</p>
QA:
Is "safe_eval" really safe?
<p>Daniel, <a href="http://jinja.pocoo.org/2/documentation/intro" rel="nofollow">Jinja</a> implements a sandboxe environment that may or may not be useful to you. From what I remember, it doesn't yet "comprehend" list comprehensions. </p> <p><a href="http://jinja.pocoo.org/2/documentation/sandbox" rel="nofollow">Sanbox info</a> </p>
QA:
Is "safe_eval" really safe?
<p>Depends on your definition of safe I suppose. A lot of the security depends on what you pass in and what you are allowed to pass in the context. For instance, if a file is passed in, I can open arbitrary files:</p> <pre><code>&gt;&gt;&gt; names['f'] = open('foo', 'w+') &gt;&gt;&gt; safe_eval.safe_eval("baz = type(f)('baz', 'w+')", names) &gt;&gt;&gt; names['baz'] &lt;open file 'baz', mode 'w+' at 0x413da0&gt; </code></pre> <p>Furthermore, the environment is very restricted (you cannot pass in modules), thus, you can't simply pass in a module of utility functions like re or random.</p> <p>On the other hand, you don't need to write your own parser, you could just write your own evaluator for the python ast:</p> <pre><code>&gt;&gt;&gt; import compiler &gt;&gt;&gt; ast = compiler.parse("print 'Hello world!'") </code></pre> <p>That way, hopefully, you could implement safe imports. The other idea is to use Jython or IronPython and take advantage of Java/.Net sandboxing capabilities.</p>
QA:
How can I render a tree structure (recursive) using a django template?
<p>I think the canonical answer is: "Don't".</p> <p>What you should probably do instead is unravel the thing in your <em>view</em> code, so it's just a matter of iterating over (in|de)dents in the template. I think I'd do it by appending indents and dedents to a list while recursing through the tree and then sending that "travelogue" list to the template. (the template would then insert <code>&lt;li&gt;</code> and <code>&lt;/li&gt;</code> from that list, creating the recursive structure with "understanding" it.)</p> <p>I'm also pretty sure recursively including template files is really a <em>wrong</em> way to do it...</p>
QA:
Programmatically editing Python source
<p>Python's standard library provides pretty good facilities for working with Python source; note the <a href="https://docs.python.org/2/library/tokenize.html" rel="nofollow">tokenize</a> and <a href="https://docs.python.org/2/library/parser.html" rel="nofollow">parser</a> modules.</p>
QA:
Is it possible to run a Python script as a service in Windows? If possible, how?
<p>Yes you can. I do it using the pythoncom libraries that come included with <a href="http://www.activestate.com/Products/activepython/index.mhtml" rel="nofollow">ActivePython</a> or can be installed with <a href="https://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a> (Python for Windows extensions).</p> <p>This is a basic skeleton for a simple service:</p> <pre><code>import win32serviceutil import win32service import win32event import servicemanager import socket class AppServerSvc (win32serviceutil.ServiceFramework): _svc_name_ = "TestService" _svc_display_name_ = "Test Service" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None,0,0,None) socket.setdefaulttimeout(60) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_,'')) self.main() def main(self): pass if __name__ == '__main__': win32serviceutil.HandleCommandLine(AppServerSvc) </code></pre> <p>Your code would go in the main() method, usually with some kind of infinite loop that might be interrumped by checking a flag, that you set in the SvcStop method</p>
QA:
How can I render a tree structure (recursive) using a django template?
<p>this might be way more than you need, but there is a django module called 'mptt' - this stores a hierarchical tree structure in an sql database, and includes templates for display in the view code. you might be able to find something useful there.</p> <p>here's the link : <a href="https://github.com/django-mptt/django-mptt/" rel="nofollow">django-mptt</a></p>
QA:
How to generate dynamic (parametrized) unit tests in python?
<p>i use something like this:</p> <pre><code>import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequense(unittest.TestCase): pass def test_generator(a, b): def test(self): self.assertEqual(a,b) return test if __name__ == '__main__': for t in l: test_name = 'test_%s' % t[0] test = test_generator(t[1], t[2]) setattr(TestSequense, test_name, test) unittest.main() </code></pre> <p>The <a href="https://github.com/wolever/nose-parameterized"><code>nose-parameterized</code></a> package can be used to automate this process:</p> <pre><code>from nose_parameterized import parameterized class TestSequence(unittest.TestCase): @parameterized.expand([ ["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"], ]) def test_sequence(self, name, a, b): self.assertEqual(a,b) </code></pre> <p>Which will generate the tests:</p> <pre><code>test_sequence_0_foo (__main__.TestSequence) ... ok test_sequence_1_bar (__main__.TestSequence) ... FAIL test_sequence_2_lee (__main__.TestSequence) ... ok ====================================================================== FAIL: test_sequence_1_bar (__main__.TestSequence) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/nose_parameterized/parameterized.py", line 233, in &lt;lambda&gt; standalone_func = lambda *a: func(*(a + p.args), **p.kwargs) File "x.py", line 12, in test_sequence self.assertEqual(a,b) AssertionError: 'a' != 'b' </code></pre>
QA:
Programmatically editing Python source
<p>I had the same issue and I simply opened the file and did some replace: then reload the file in the Python interpreter. This works fine and is easy to do. </p> <p>Otherwise AFAIK you have to use some conf objects.</p>
QA:
ssh hangs when command invoked directly, but exits cleanly when run interactive
<blockquote> <pre><code>s = p.stderr.readline() </code></pre> </blockquote> <p>I suspect it's the above line. When you invoke a command directly through ssh, you don't get your full pty (assuming Linux), and thus no stderr to read from.</p> <p>When you log in interactively, stdin, stdout, and stderr are set up for you, and so your script works.</p>
QA:
Extending base classes in Python
<p>Ints are immutable and you can't modify them in place, so you should go with option #2 (because option #1 is impossible without some trickery).</p>
QA:
Extending base classes in Python
<p><strong>int</strong> is a value type, so each time you do an assignment, (e.g. both instances of <strong>+=</strong> above), it doesn't modify the object you have on the heap, but replaces the reference with one of the result of the right hand side of the assignment (i.e. an int)</p> <p><strong>list</strong> isn't a value type, so it isn't bound by the same rules.</p> <p>this page has more details on the differences: <a href="http://docs.python.org/ref/objects.html">http://docs.python.org/ref/objects.html</a></p> <p>IMO, yes, you should define a new class that keeps an int as an instance variable</p>
QA:
Extending base classes in Python
<p>Your two <code>xint</code> examples don't work for two different reasons.</p> <p>The first doesn't work because <code>self += value</code> is equivalent to <code>self = self + value</code> which just reassigns the local variable <code>self</code> to a different object (an integer) but doesn't change the original object. You can't really get this </p> <pre><code>&gt;&gt;&gt; x = xint(10) &gt;&gt;&gt; x.add(2) </code></pre> <p>to work with a subclass of <code>int</code> since integers are <a href="http://docs.python.org/ref/objects.html">immutable</a>.</p> <p>To get the second one to work you can define an <a href="http://docs.python.org/ref/numeric-types.html"><code>__add__</code> method</a>, like so:</p> <pre><code>class xint(int): def __add__(self, value): return xint(int.__add__(self, value)) &gt;&gt;&gt; x = xint(10) &gt;&gt;&gt; type(x) &lt;class '__main__.xint'&gt; &gt;&gt;&gt; x += 3 &gt;&gt;&gt; x 13 &gt;&gt;&gt; type(x) &lt;class '__main__.xint'&gt; </code></pre>
QA:
ssh hangs when command invoked directly, but exits cleanly when run interactive
<p>what if you do the following:</p> <h2><code>ssh &lt;remote host&gt; '&lt;your command&gt; ;&lt;your regexp using awk or something&gt;'</code></h2> <p>For example</p> <h2><code>ssh &lt;remote host&gt; '&lt;your program&gt;; ps aux | awk \'/root/ {print $2}\''</code></h2> <p>This will connect to , execute and then print each PSID for any user root or any process with root in its description.</p> <p>I have used this method for running all kinds of commands on remote machines. The catch is to wrap the command(s) you wish to execute in single quotation marks (') and to separate each command with a semi-colon (;).</p>
QA:
ssh hangs when command invoked directly, but exits cleanly when run interactive
<p>@Ben Collins</p> <p>I think you're right about stderr being an issue. I am pretty sure it's blocking on the readline() call. </p> <p>In the end, I gave up and decided to use the pxssh module from <a href="http://pexpect.sourceforge.net" rel="nofollow">pexpect</a> to automate my interaction with an ssh session.</p> <p>@Misha M</p> <p>Unfortunately, the semi-colon trick doesn't work here: it blocks on executing my program. </p>
QA:
Specifying a mySQL ENUM in a Django model
<p>Using the <code>choices</code> parameter won't use the ENUM db type; it will just create a VARCHAR or INTEGER, depending on whether you use <code>choices</code> with a CharField or IntegerField. Generally, this is just fine. If it's important to you that the ENUM type is used at the database level, you have three options:</p> <ol> <li>Use "./manage.py sql appname" to see the SQL Django generates, manually modify it to use the ENUM type, and run it yourself. If you create the table manually first, "./manage.py syncdb" won't mess with it.</li> <li>If you don't want to do this manually every time you generate your DB, put some custom SQL in appname/sql/modelname.sql to perform the appropriate ALTER TABLE command.</li> <li>Create a <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields" rel="nofollow">custom field type</a> and define the db_type method appropriately.</li> </ol> <p>With any of these options, it would be your responsibility to deal with the implications for cross-database portability. In option 2, you could use <a href="http://www.djangoproject.com/documentation/model-api/#database-backend-specific-sql-data" rel="nofollow">database-backend-specific custom SQL</a> to ensure your ALTER TABLE is only run on MySQL. In option 3, your db_type method would need to check the database engine and set the db column type to a type that actually exists in that database.</p> <p><strong>UPDATE</strong>: Since the migrations framework was added in Django 1.7, options 1 and 2 above are entirely obsolete. Option 3 was always the best option anyway. The new version of options 1/2 would involve a complex custom migration using <code>SeparateDatabaseAndState</code> -- but really you want option 3.</p>
QA:
Class views in Django
<p>I've created and used my own generic view classes, defining <strong><code>__call__</code></strong> so an instance of the class is callable. I really like it; while Django's generic views allow some customization through keyword arguments, OO generic views (if their behavior is split into a number of separate methods) can have much more fine-grained customization via subclassing, which lets me repeat myself a lot less. (I get tired of rewriting the same create/update view logic anytime I need to tweak something Django's generic views don't quite allow).</p> <p>I've posted some code at <a href="http://www.djangosnippets.org/snippets/1009/">djangosnippets.org</a>.</p> <p>The only real downside I see is the proliferation of internal method calls, which may impact performance somewhat. I don't think this is much of a concern; it's rare that Python code execution would be your performance bottleneck in a web app.</p> <p><strong>UPDATE</strong>: Django's own <a href="http://docs.djangoproject.com/en/dev/topics/class-based-views/">generic views</a> are now class-based.</p> <p><strong>UPDATE</strong>: FWIW, I've changed my opinion on class-based views since this answer was written. After having used them extensively on a couple of projects, I feel they tend to lead to code that is satisfyingly DRY to write, but very hard to read and maintain later, because functionality is spread across so many different places, and subclasses are so dependent on every implementation detail of the superclasses and mixins. I now feel that <a href="https://docs.djangoproject.com/en/dev/ref/template-response/">TemplateResponse</a> and view decorators is a better answer for decomposing view code.</p>
QA:
Find out how much memory is being used by an object in Python
<p>I haven't any personal experience with either of the following, but a simple search for a "Python [memory] profiler" yield:</p> <ul> <li><p>PySizer, "a memory profiler for Python," found at <a href="http://pysizer.8325.org/" rel="nofollow">http://pysizer.8325.org/</a>. However the page seems to indicate that the project hasn't been updated for a while, and refers to...</p></li> <li><p>Heapy, "support[ing] debugging and optimization regarding memory related issues in Python programs," found at <a href="http://guppy-pe.sourceforge.net/#Heapy" rel="nofollow">http://guppy-pe.sourceforge.net/#Heapy</a>.</p></li> </ul> <p>Hope that helps.</p>
QA:
Are Python threads buggy?
<p>I've used it in several applications and have never had nor heard of threading being anything other than 100% reliable, as long as you know its limits. You can't spawn 1000 threads at the same time and expect your program to run properly on Windows, however you can easily write a worker pool and just feed it 1000 operations, and keep everything nice and under control.</p>
QA:
Are Python threads buggy?
<p>As far as I know there are no real bugs, but the performance when threading in cPython is really bad (compared to most other threading implementations, but usually good enough if all most of the threads do is block) due to the <a href="http://docs.python.org/api/threads.html" rel="nofollow">GIL</a> (Global Interpreter Lock), so really it is implementation specific rather than language specific. Jython, for example, does not suffer from this due to using the Java thread model.</p> <p>See <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=214235" rel="nofollow">this</a> post on why it is not really feasible to remove the GIL from the cPython implementation, and <a href="http://www.pyzine.com/Issue001/Section_Articles/article_ThreadingGlobalInterpreter.html" rel="nofollow">this</a> for some practical elaboration and workarounds.</p> <p>Do a quick google for <a href="http://www.google.com/search?q=python+gil" rel="nofollow">"Python GIL"</a> for more information.</p>
QA:
Are Python threads buggy?
<p>Python threads are good for <strong>concurrent I/O programming</strong>. Threads are swapped out of the CPU as soon as they block waiting for input from file, network, etc. This allows other Python threads to use the CPU while others wait. This would allow you to write a multi-threaded web server or web crawler, for example.</p> <p>However, Python threads are serialized by the <a href="http://en.wikipedia.org/wiki/Global_Interpreter_Lock">GIL</a> when they enter interpreter core. This means that if two threads are crunching numbers, only one can run at any given moment. It also means that you can't take advantage of multi-core or multi-processor architectures.</p> <p>There are solutions like running multiple Python interpreters concurrently, using a C based threading library. This is not for the faint of heart and the benefits might not be worth the trouble. Let's hope for an all Python solution in a future release.</p>
QA:
Are Python threads buggy?
<p>The GIL (Global Interpreter Lock) might be a problem, but the API is quite OK. Try out the excellent <code>processing</code> module, which implements the Threading API for separate processes. I am using that right now (albeit on OS X, have yet to do some testing on Windows) and am really impressed. The Queue class is really saving my bacon in terms of managing complexity!</p> <p><strong>EDIT</strong>: it seemes the processing module is being included in the standard library as of version 2.6 (<code>import multiprocessing</code>). Joy!</p>
QA:
How to generate dynamic (parametrized) unit tests in python?
<p>The <a href="https://nose.readthedocs.org/en/latest/">nose</a> testing framework <a href="https://nose.readthedocs.org/en/latest/writing_tests.html#test-generators">supports this</a>. </p> <p>Example (the code below is the entire contents of the file containing the test):</p> <pre><code>param_list = [('a', 'a'), ('a', 'b'), ('b', 'b')] def test_generator(): for params in param_list: yield check_em, params[0], params[1] def check_em(a, b): assert a == b </code></pre> <p>The output of the nosetests command:</p> <pre><code>> nosetests -v testgen.test_generator('a', 'a') ... ok testgen.test_generator('a', 'b') ... FAIL testgen.test_generator('b', 'b') ... ok ====================================================================== FAIL: testgen.test_generator('a', 'b') ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/nose-0.10.1-py2.5.egg/nose/case.py", line 203, in runTest self.test(*self.arg) File "testgen.py", line 7, in check_em assert a == b AssertionError ---------------------------------------------------------------------- Ran 3 tests in 0.006s FAILED (failures=1) </code></pre>
QA:
How to specify an authenticated proxy for a python http connection?
<p>This works for me: </p> <pre><code>import urllib2 proxy = urllib2.ProxyHandler({'http': 'http:// username:password@proxyurl:proxyport'}) auth = urllib2.HTTPBasicAuthHandler() opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) urllib2.install_opener(opener) conn = urllib2.urlopen('http://python.org') return_str = conn.read() </code></pre>
QA:
Python descriptor protocol analog in other languages?
<p>I've not heard of a direct equivalent either. You could probably achieve the same effect with macros, especially in a language like Lisp which has extremely powerful macros.</p> <p>I wouldn't be at all surprised if other languages start to incorporate something similar because it is so powerful.</p>
QA:
How do I make Windows aware of a service I have written in Python?
<p>Here is code to install a python-script as a service, written in python :)</p> <p><a href="http://code.activestate.com/recipes/551780/">http://code.activestate.com/recipes/551780/</a></p> <p>This post could also help you out:</p> <p><a href="http://essiene.blogspot.com/2005/04/python-windows-services.html">http://essiene.blogspot.com/2005/04/python-windows-services.html</a></p>
QA:
Django ImageField core=False in newforms admin
<p>This is simple. I started getting this problems a few revisions ago. Basically, just remove the "core=True" parameter in the ImageField in the models, and then follow the instructions <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects" rel="nofollow">here</a> to convert to what the newforms admin uses.</p>
QA:
How do I make Windows aware of a service I have written in Python?
<p>As with most "aware" things in Windows, the answer is "Registry".</p> <p>Take a look at this Microsoft Knowledge Base article: <a href="http://support.microsoft.com/kb/103000" rel="nofollow">http://support.microsoft.com/kb/103000</a></p> <p>Search for "A Win32 program that can be started by the Service Controller and that obeys the service control protocol." This is the kind of service you're interested in.</p> <p>The service registration (contents of KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services \myservice) carries information about the service, including things like its executable location, what to do when it fails (halt the OS?), what services must be started before this one, what user it runs as.</p> <p>As to service control protocol, main() of your program is supposed to invoke a Windows API call, setting up callbacks for start, stop, pause for your service. What you do in those callbacks is all up to you.</p>
QA:
How do I make Windows aware of a service I have written in Python?
<p>You can use srvany.exe from Windows NT Resource Kit to create a user defined service that will show up in the admin tools...</p> <p><a href="http://support.microsoft.com/kb/137890" rel="nofollow">http://support.microsoft.com/kb/137890</a></p> <p>I am using this method to run tracd (a python script / server) for trac. </p> <p>Here are some very clear instructions: <a href="http://www.tacktech.com/display.cfm?ttid=197" rel="nofollow">http://www.tacktech.com/display.cfm?ttid=197</a></p> <p>It does require some registry editing (very minimal and easy) but will allow you to make any command line / script a windows service. </p>
QA:
Finding what methods an object has
<p>It appears you can use this code, replacing 'object' with the object you're interested in:-</p> <pre><code>[method for method in dir(object) if callable(getattr(object, method))] </code></pre> <p>I discovered it at <a href="http://www.diveintopython.net/power_of_introspection/index.html">this site</a>, hopefully that should provide some further detail!</p>
QA:
Finding what methods an object has
<p>You can use the built in <code>dir()</code> function to get a list of all the attributes a module has. Try this at the command line to see how it works.</p> <pre><code>&gt;&gt;&gt; import moduleName &gt;&gt;&gt; dir(moduleName) </code></pre> <p>Also, you can use the <code>hasattr(module_name, "attr_name")</code> function to find out if a module has a specific attribute.</p> <p>See the <a href="http://www.ibm.com/developerworks/library/l-pyint.html">Guide to Python introspection</a> for more information.</p>
QA:
Finding what methods an object has
<p>To check if it has a particular method:</p> <pre><code>hasattr(object,"method") </code></pre>
QA:
Finding what methods an object has
<p>On top of the more direct answers, I'd be remiss if I didn't mention <a href="http://ipython.scipy.org/">iPython</a>. Hit 'tab' to see the available methods, with autocompletion.</p> <p>And once you've found a method, try:</p> <pre><code>help(object.method) </code></pre> <p>to see the pydocs, method signature, etc.</p> <p>Ahh... <a href="http://en.wikipedia.org/wiki/REPL">REPL</a>.</p>
QA:
Python Sound ("Bell")
<p>If you have PyObjC (the Python - Objective-C bridge) installed or are running on OS X 10.5's system python (which ships with PyObjC), you can do</p> <pre><code>from AppKit import NSBeep NSBeep() </code></pre> <p>to play the system alert.</p>
QA:
Are Python threads buggy?
<p>The standard implementation of Python (generally known as CPython as it is written in C) uses OS threads, but since there is the <a href="http://en.wikipedia.org/wiki/Global_Interpreter_Lock" rel="nofollow">Global Interpreter Lock</a>, only one thread at a time is allowed to run Python code. But within those limitations, the threading libraries are robust and widely used.</p> <p>If you want to be able to use multiple CPU cores, there are a few options. One is to use multiple python interpreters concurrently, as mentioned by others. Another option is to use a different implementation of Python that does not use a GIL. The two main options are <a href="http://en.wikipedia.org/wiki/Jython" rel="nofollow">Jython</a> and <a href="http://en.wikipedia.org/wiki/IronPython" rel="nofollow">IronPython</a>.</p> <p>Jython is written in Java, and is now fairly mature, though some incompatibilities remain. For example, the web framework <a href="http://zyasoft.com/pythoneering/2008/01/django-on-jython-minding-gap.html" rel="nofollow">Django does not run perfectly yet</a>, but is getting closer all the time. Jython is <a href="http://mail.python.org/pipermail/python-list/2001-December/116555.html" rel="nofollow">great for thread safety</a>, comes out <a href="http://blogs.warwick.ac.uk/dwatkins/entry/benchmarking_parallel_python_1_2/" rel="nofollow">better in benchmarks</a> and has a <a href="http://cgwalters.livejournal.com/17956.html" rel="nofollow">cheeky message for those wanting the GIL</a>.</p> <p>IronPython uses the .NET framework and is written in C#. Compatibility is reaching the stage where <a href="http://www.infoq.com/news/2008/03/django-and-ironpython" rel="nofollow">Django can run on IronPython</a> (at least as a demo) and there are <a href="http://www.voidspace.org.uk/ironpython/threading.shtml" rel="nofollow">guides to using threads in IronPython</a>.</p>
QA:
Django ImageField core=False in newforms admin
<p>The <code>core</code> attribute isn't used anymore.</p> <p>From <a href="http://oebfare.com/blog/2008/jul/20/newforms-admin-migration-and-screencast/" rel="nofollow">Brian Rosner's Blog</a>:</p> <blockquote> <p>You can safely just remove any and all <code>core</code> arguments. They are no longer used. <em>newforms-admin</em> now provides a nice delete checkbox for exisiting instances in inlines.</p> </blockquote>
QA:
Scaffolding in pylons
<p>I hear you, I've followed the Pylons mailing list for a while looking for something similar. There have been some attempts in the past (see <a href="http://adminpylon.devjavu.com/" rel="nofollow">AdminPylon</a> and <a href="http://code.google.com/p/restin/" rel="nofollow">Restin</a>) but none have really kept up with SQLAlchemy's rapidly developing orm api.</p> <p>Since DBSprockets is likely to be incorporated into TurboGears it will likely be maintained. I'd bite the bullet and go with that.</p>
QA:
Python super class reflection
<p>@John: Your snippet doesn't work -- you are returning the <em>class</em> of the base classes (which are also known as metaclasses). You really just want <code>cls.__bases__</code>:</p> <pre><code>class A: pass class B: pass class C(A, B): pass c = C() # Instance assert C.__bases__ == (A, B) # Works assert c.__class__.__bases__ == (A, B) # Works def magicGetSuperClasses(clz): return tuple([base.__class__ for base in clz.__bases__]) assert magicGetSuperClasses(C) == (A, B) # Fails </code></pre> <p>Also, if you're using Python 2.4+ you can use <a href="http://www.python.org/dev/peps/pep-0289/">generator expressions</a> instead of creating a list (via []), then turning it into a tuple (via <code>tuple</code>). For example:</p> <pre><code>def get_base_metaclasses(cls): """Returns the metaclass of all the base classes of cls.""" return tuple(base.__class__ for base in clz.__bases__) </code></pre> <p>That's a somewhat confusing example, but genexps are generally easy and cool. :)</p>
QA:
How to specify an authenticated proxy for a python http connection?
<p>The best way of going through a proxy that requires authentication is using <a href="http://docs.python.org/lib/module-urllib2.html">urllib2</a> to build a custom url opener, then using that to make all the requests you want to go through the proxy. Note in particular, you probably don't want to embed the proxy password in the url or the python source code (unless it's just a quick hack).</p> <pre><code>import urllib2 def get_proxy_opener(proxyurl, proxyuser, proxypass, proxyscheme="http"): password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, proxyurl, proxyuser, proxypass) proxy_handler = urllib2.ProxyHandler({proxyscheme: proxyurl}) proxy_auth_handler = urllib2.ProxyBasicAuthHandler(password_mgr) return urllib2.build_opener(proxy_handler, proxy_auth_handler) if __name__ == "__main__": import sys if len(sys.argv) &gt; 4: url_opener = get_proxy_opener(*sys.argv[1:4]) for url in sys.argv[4:]: print url_opener.open(url).headers else: print "Usage:", sys.argv[0], "proxy user pass fetchurls..." </code></pre> <p>In a more complex program, you can seperate these components out as appropriate (for instance, only using one password manager for the lifetime of the application). The python documentation has <a href="http://docs.python.org/lib/urllib2-examples.html">more examples on how to do complex things with urllib2</a> that you might also find useful.</p>
QA:
Validate (X)HTML in Python
<p>XHTML is easy, use <a href="http://lxml.de/validation.html" rel="nofollow">lxml</a>.</p> <p>HTML is harder, since there's traditionally not been as much interest in validation among the HTML crowd (run StackOverflow itself through a validator, yikes). The easiest solution would be to execute external applications such as <a href="http://www.jclark.com/sp/" rel="nofollow">nsgmls</a> or <a href="http://openjade.sourceforge.net/" rel="nofollow">OpenJade</a>, and then parse their output.</p>
QA:
Validate (X)HTML in Python
<p>I think that <a href="http://tidy.sourceforge.net/" rel="nofollow">HTML tidy</a> will do what you want. There is a Python binding for it.</p>
QA:
Validate (X)HTML in Python
<p>Try tidylib. You can get some really basic bindings as part of the elementtidy module (builds elementtrees from HTML documents). <a href="http://effbot.org/downloads/#elementtidy">http://effbot.org/downloads/#elementtidy</a></p> <pre><code>&gt;&gt;&gt; import _elementtidy &gt;&gt;&gt; xhtml, log = _elementtidy.fixup("&lt;html&gt;&lt;/html&gt;") &gt;&gt;&gt; print log line 1 column 1 - Warning: missing &lt;!DOCTYPE&gt; declaration line 1 column 7 - Warning: discarding unexpected &lt;/html&gt; line 1 column 14 - Warning: inserting missing 'title' element </code></pre> <p>Parsing the log should give you pretty much everything you need.</p>
QA:
Why does Python's iter() on a mapping return iterkeys() instead of iteritems()?
<p>Check out <a href="http://mail.python.org/pipermail/python-3000/2007-September/010209.html" rel="nofollow">this thread</a> for a discussion on the reasons behind this behavior (including that Guido likes it, and it's <a href="http://mail.python.org/pipermail/python-3000/2007-September/010222.html" rel="nofollow">not likely to change</a>).</p>