prefix
stringclasses
1 value
input_text
stringlengths
10
172
target_text
stringlengths
18
33.9k
QA:
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
<p>The notion of tuples are highly expressive:</p> <ul> <li><p>Pragmatically, they are great for packing and unpacking values (<code>x,y=coord</code>).</p></li> <li><p>In combination with dictionaries (hash tables), they allow forms of mapping that would otherwise require many levels of association. For example, consider marking that (x,y) has been found.</p> <pre><code>// PHP if (!isset($found[$x])) { $found[$x] = Array(); $found[$x][$y] = true; } else if (!isset($found[$x][$y])) { $found[$x][$y] = true; } # Python found[(x,y)] = True # parens added for clarity </code></pre></li> <li><p>Lists should be used with the expectation of operations on its contents (hence the various mentions of immutability). One will want to pop, push, splice, slice, search, insert before, insert after, etc with a list.</p></li> <li><p>Tuples should be a low-level representation of an object, where simple comparisons are made, or operations such as extracting the n'th element or n elements in a predictable fashion, such as the coordinates example given earlier.</p></li> <li><p>Lastly, lists are not hashable, so the type of mapping done with dictionaries (hash tables in Perl, associative arrays in PHP) must be done with tuples.</p> <p>Here's a simple example of tuples and dictionaries, together at last:</p> <pre><code>""" couple is a tuple of two people doesLike is a dictionary mapping couples to True or False """ couple = "john", "jane" doesLike = dict() doesLike[couple] = True doesLike["jane", "john"] = False # unrequited love :'( </code></pre></li> </ul>
QA:
Can you check that an exception is thrown with doctest in Python?
<p>Yes. You can do it. The <a href="https://docs.python.org/3/library/doctest.html">doctest module documentation</a> and Wikipedia has an <a href="http://en.wikipedia.org/wiki/Doctest#Example_2%3a_doctests_embedded_in_a_README.txt_file">example</a> of it.</p> <pre><code> &gt;&gt;&gt; x Traceback (most recent call last): ... NameError: name 'x' is not defined </code></pre>
QA:
Using an XML catalog with Python's lxml?
<p>Can you give an example? According to the <a href="http://codespeak.net/lxml/validation.html" rel="nofollow">lxml validation docs</a>, lxml can handle DTD validation (specified in the XML doc or externally in code) and system catalogs, which covers most cases I can think of.</p> <pre><code>f = StringIO("&lt;!ELEMENT b EMPTY&gt;") dtd = etree.DTD(f) dtd = etree.DTD(external_id = "-//OASIS//DTD DocBook XML V4.2//EN") </code></pre>
QA:
How do you express binary literals in Python?
<p>For reference&mdash;<em>future</em> Python possibilities:<br /> Starting with Python 2.6 you can express binary literals using the prefix <strong>0b</strong> or <strong>0B</strong>:</p> <pre><code>&gt;&gt;&gt; 0b101111 47 </code></pre> <p>You can also use the new <strong>bin</strong> function to get the binary representation of a number:</p> <pre><code>&gt;&gt;&gt; bin(173) '0b10101101' </code></pre> <p>Development version of the documentation: <a href="http://docs.python.org/dev/whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax">What's New in Python 2.6</a></p>
QA:
Replacement for for... if array iteration
<p>Depends on the language and what you need to do, a "map" as it's called in many languages could be what you're looking for. I don't know C#, but according to <a href="http://blogs.msdn.com/devdev/archive/2006/06/30/652802.aspx" rel="nofollow">this</a> page, .NET 2.0 calls map "ConvertAll".</p> <p>The meaning of "map" is pretty simple - take a list, and apply a function to each element of it, returning a new list. You may also be looking for "filter", which would give you a list of items that satisfy a predicate in another list.</p>
QA:
Replacement for for... if array iteration
<p>in Ruby:</p> <pre><code>intArray.select { |x| x &gt; 3 }.each do |x| # do other processing end </code></pre> <p>or if "other processing" is a short one-liner:</p> <pre><code>intArray.select { |x| x &gt; 3 }.each { |x| something_that_uses x } </code></pre> <p>lastly, if you want to return a new array containing the results of the processing of those elements greater than 3:</p> <pre><code>intArray.select { |x| x &gt; 3 }.map { |x| do_something_to x } </code></pre>
QA:
Replacement for for... if array iteration
<p>In Python, you have <a href="http://docs.python.org/tut/node7.html#SECTION007130000000000000000" rel="nofollow" title="Human Interface Guidelines">filter and map</a>, which can so what you want:</p> <pre><code>map(lambda x: foo(x + 1) filter(lambda x: x &gt; 3, intArray)) </code></pre> <p>There's also <a href="http://docs.python.org/tut/node7.html#SECTION007140000000000000000" rel="nofollow">list comprehensions</a> which can do both in one easy statement:</p> <pre><code>[f(x + 1) for x in intArray if x &gt; 3] </code></pre>
QA:
Replacement for for... if array iteration
<p>In C# you can apply selective processing on anything that lives inside an IEnumerable like this: </p> <pre><code>intArray.Where(i =&gt; i &gt; 3).ConvertAll(); DoStuff(intArray.Where(i =&gt; i 3)); </code></pre> <p>Etc..</p>
QA:
Replacement for for... if array iteration
<p>The increment in the original <code>foreach</code> loop will not affect the contents of the array, the only way to do this remains a <code>for</code> loop:</p> <pre><code>for(int i = 0; i &lt; intArray.Length; ++i) { if(intArray[i] &gt; 3) ++intArray[i]; } </code></pre> <p>Linq is not intended to modify existing collections or sequences. It creates new sequences based on existing ones. It is possible to achieve the above code using Linq, though it is slightly against its purposes:</p> <pre><code>var newArray1 = from i in intArray select ((i &gt; 3) ? (i + 1) : (i)); var newArray2 = intArray.Select(i =&gt; (i &gt; 3) ? (i + 1) : (i)); </code></pre> <p>Using <code>where</code> (or equivalent), as shown in some of the other answers, will exclude any values less than or equal to 3 from the resulting sequence.</p> <pre><code>var intArray = new int[] { 10, 1, 20, 2 }; var newArray = from i in intArray where i &gt; 3 select i + 1; // newArray == { 11, 21 } </code></pre> <p>There is a <code>ForEach</code> method on arrays that will allow you to use a lambda function instead of a <code>foreach</code> block, though for anything more than a method call I would stick with <code>foreach</code>.</p> <pre><code>intArray.ForEach(i =&gt; DoSomething(i)); </code></pre>
QA:
Python version of PHP's stripslashes
<p>You can obviously concatenate everything together:</p> <pre><code>cleaned = stringwithslashes.replace("\\n","\n").replace("\\r","\n").replace("\\","") </code></pre> <p>Is that what you were after? Or were you hoping for something more terse?</p>
QA:
Python version of PHP's stripslashes
<p>Python has a built-in escape() function analogous to PHP's addslashes, but no unescape() function (stripslashes), which in my mind is kind of ridiculous.</p> <p>Regular expressions to the rescue (code not tested):</p> <pre><code>p = re.compile( '\\(\\\S)') p.sub('\1',escapedstring) </code></pre> <p>In theory that takes anything of the form \\(not whitespace) and returns \(same char)</p> <p>edit: Upon further inspection, Python regular expressions are broken as all hell;</p> <pre><code>&gt;&gt;&gt; escapedstring 'This is a \\n\\n\\n test' &gt;&gt;&gt; p = re.compile( r'\\(\S)' ) &gt;&gt;&gt; p.sub(r"\1",escapedstring) 'This is a nnn test' &gt;&gt;&gt; p.sub(r"\\1",escapedstring) 'This is a \\1\\1\\1 test' &gt;&gt;&gt; p.sub(r"\\\1",escapedstring) 'This is a \\n\\n\\n test' &gt;&gt;&gt; p.sub(r"\(\1)",escapedstring) 'This is a \\(n)\\(n)\\(n) test' </code></pre> <p>In conclusion, what the hell, Python.</p>
QA:
Python version of PHP's stripslashes
<p>Not totally sure this is what you want, but..</p> <pre><code>cleaned = stringwithslashes.decode('string_escape') </code></pre>
QA:
Python version of PHP's stripslashes
<p>It sounds like what you want could be reasonably efficiently handled through regular expressions:</p> <pre><code>import re def stripslashes(s): r = re.sub(r"\\(n|r)", "\n", s) r = re.sub(r"\\", "", r) return r cleaned = stripslashes(stringwithslashes) </code></pre>
QA:
Python Regular Expressions to implement string unescaping
<p>Well, I think you might have missed the r or miscounted the backslashes...</p> <pre><code>"\\n" == r"\n" &gt;&gt;&gt; import re &gt;&gt;&gt; mystring = r"This is \\n a test \\r" &gt;&gt;&gt; p = re.compile( r"[\\][\\](.)" ) &gt;&gt;&gt; print p.sub( r"\\\1", mystring ) This is \n a test \r &gt;&gt;&gt; </code></pre> <p>Which, if I understood is what was requested.</p> <p>I suspect the more common request is this:</p> <pre><code>&gt;&gt;&gt; d = {'n':'\n', 'r':'\r', 'f':'\f'} &gt;&gt;&gt; p = re.compile(r"[\\]([nrfv])") &gt;&gt;&gt; print p.sub(lambda mo: d[mo.group(1)], mystring) This is \ a test \ &gt;&gt;&gt; </code></pre> <p>The interested student should also read Ken Thompson's <a href="http://cm.bell-labs.com/who/ken/trust.html" rel="nofollow" title="Cherry G80-11900">Reflections on Trusting Trust"</a>, wherein our hero uses a similar example to explain the perils of trusting compilers you haven't bootstrapped from machine code yourself.</p>
QA:
Python Regular Expressions to implement string unescaping
<p>You are being tricked by Python's representation of the result string. The Python expression:</p> <pre><code>'This is \\n a test \\r' </code></pre> <p>represents the string</p> <pre><code>This is \n a test \r </code></pre> <p>which is I think what you wanted. Try adding 'print' in front of each of your p.sub() calls to print the actual string returned instead of a Python representation of the string.</p> <pre><code>&gt;&gt;&gt; mystring = r"This is \n a test \r" &gt;&gt;&gt; mystring 'This is \\n a test \\r' &gt;&gt;&gt; print mystring This is \n a test \r </code></pre>
QA:
Can you explain closures (as they relate to Python)?
<p>It's simple: A function that references variables from a containing scope, potentially after flow-of-control has left that scope. That last bit is very useful:</p> <pre><code>&gt;&gt;&gt; def makeConstantAdder(x): ... constant = x ... def adder(y): ... return y + constant ... return adder ... &gt;&gt;&gt; f = makeConstantAdder(12) &gt;&gt;&gt; f(3) 15 &gt;&gt;&gt; g = makeConstantAdder(4) &gt;&gt;&gt; g(3) 7 </code></pre> <p>Note that 12 and 4 have "disappeared" inside f and g, respectively, this feature is what make f and g proper closures.</p>
QA:
Python Regular Expressions to implement string unescaping
<p>The idea is that I'll read in an escaped string, and unescape it (a feature notably lacking from Python, which you shouldn't need to resort to regular expressions for in the first place). Unfortunately I'm not being tricked by the backslashes...</p> <p>Another illustrative example:</p> <pre><code>&gt;&gt;&gt; mystring = r"This is \n ridiculous" &gt;&gt;&gt; print mystring This is \n ridiculous &gt;&gt;&gt; p = re.compile( r"\\(\S)" ) &gt;&gt;&gt; print p.sub( 'bloody', mystring ) This is bloody ridiculous &gt;&gt;&gt; print p.sub( r'\1', mystring ) This is n ridiculous &gt;&gt;&gt; print p.sub( r'\\1', mystring ) This is \1 ridiculous &gt;&gt;&gt; print p.sub( r'\\\1', mystring ) This is \n ridiculous </code></pre> <p>What I'd like it to print is</p> <pre><code>This is ridiculous </code></pre>
QA:
Can you explain closures (as they relate to Python)?
<p>I've never heard of transactions being used in the same context as explaining what a closure is and there really aren't any transaction semantics here.</p> <p>It's called a closure because it "closes over" the outside variable (constant)--i.e., it's not just a function but an enclosure of the environment where the function was created. </p> <p>In the following example, calling the closure g after changing x will also change the value of x within g, since g closes over x:</p> <pre><code>x = 0 def f(): def g(): return x * 2 return g closure = f() print(closure()) # 0 x = 2 print(closure()) # 4 </code></pre>
QA:
Can you explain closures (as they relate to Python)?
<p>I like <a href="http://effbot.org/zone/closure.htm">this rough, succinct definition</a>:</p> <blockquote> <p>A function that can refer to environments that are no longer active.</p> </blockquote> <p>I'd add</p> <blockquote> <p>A closure allows you to bind variables into a function <em>without passing them as parameters</em>.</p> </blockquote> <p>Decorators which accept parameters are a common use for closures. Closures are a common implementation mechanism for that sort of "function factory". I frequently choose to use closures in the <a href="http://c2.com/cgi/wiki?StrategyPattern">Strategy Pattern</a> when the strategy is modified by data at run-time.</p> <p>In a language that allows anonymous block definition -- e.g., Ruby, C# -- closures can be used to implement (what amount to) novel new control structures. The lack of anonymous blocks is among <a href="http://ivan.truemesh.com/archives/000411.html">the limitations of closures in Python</a>.</p>
QA:
Python Regular Expressions to implement string unescaping
<p>Isn't that what <a href="#13844">Anders' second example</a> does?</p> <p>In 2.5 there's also a <code>string-escape</code> encoding you can apply:</p> <pre><code>&gt;&gt;&gt; mystring = r"This is \n a test \r" &gt;&gt;&gt; mystring.decode('string-escape') 'This is \n a test \r' &gt;&gt;&gt; print mystring.decode('string-escape') This is a test &gt;&gt;&gt; </code></pre>
QA:
Python Sound ("Bell")
<p>Have you tried :</p> <pre><code>import sys sys.stdout.write('\a') sys.stdout.flush() </code></pre> <p>That works for me here on Mac OS 10.5</p> <p>Actually, I think your original attempt works also with a little modification:</p> <pre><code>print('\a') </code></pre> <p>(You just need the single quotes around the character sequence).</p>
QA:
Python Regular Expressions to implement string unescaping
<p>Mark; his second example requires every escaped character thrown into an array initially, which generates a KeyError if the escape sequence happens not to be in the array. It will die on anything but the three characters provided (give \v a try), and enumerating every possible escape sequence every time you want to unescape a string (or keeping a global array) is a really bad solution. Analogous to PHP, that's using <code>preg_replace_callback()</code> with a lambda instead of <code>preg_replace()</code>, which is utterly unnecessary in this situation.</p> <p>I'm sorry if I'm coming off as a dick about it, I'm just utterly frustrated with Python. This is supported by every other regular expression engine I've ever used, and I can't understand why this wouldn't work.</p> <p>Thank you for responding; the <code>string.decode('string-escape')</code> function is precisely what i was looking for initially. If someone has a general solution to the regex backreference problem, feel free to post it and I'll accept that as an answer as well.</p>
QA:
Python Sound ("Bell")
<p>I had to turn off the "Silence terminal bell" option in my active Terminal Profile in iTerm for <code>print('\a')</code> to work. It seemed to work fine by default in Terminal.</p> <p>You can also use the Mac module <code>Carbon.Snd</code> to play the system beep:</p> <pre><code>&gt;&gt;&gt; import Carbon.Snd &gt;&gt;&gt; Carbon.Snd.SysBeep(1) &gt;&gt;&gt; </code></pre> <p>The Carbon modules don't have any documentation, so I had to use <code>help(Carbon.Snd)</code> to see what functions were available. It seems to be a direct interface onto Carbon, so the docs on Apple Developer Connection probably help.</p>
QA:
Is there a python module for regex matching in zip files
<p>You could loop through the zip files, reading individual files using the zipfile module and running your regex on those, eliminating to unzip all the files at once. </p> <p>I'm fairly certain that you can't run a regex over the zipped data, at least not meaningfully.</p>
QA:
Is there a python module for regex matching in zip files
<p>To access the contents of a zip file you have to unzip it, although the zipfile package makes this fairly easy, as you can unzip each file within an archive individually.</p> <p><a href="http://docs.python.org/lib/module-zipfile.html" rel="nofollow">Python zipfile module</a></p>
QA:
Is there a python module for regex matching in zip files
<p>There's nothing that will automatically do what you want.</p> <p>However, there is a python zipfile module that will make this easy to do. Here's how to iterate over the lines in the file.</p> <pre><code>#!/usr/bin/python import zipfile f = zipfile.ZipFile('myfile.zip') for subfile in f.namelist(): print subfile data = f.read(subfile) for line in data.split('\n'): print line </code></pre>
QA:
Regex and unicode
<p>Use a subrange of [\u0000-\uFFFF] for what you want.</p> <p>You can also use the re.UNICODE compile flag. <a href="http://docs.python.org/lib/re-syntax.html">The docs</a> say that if UNICODE is set, \w will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database. </p> <p>See also <a href="http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-05/2560.html">http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-05/2560.html</a>.</p>
QA:
Regex and unicode
<p>\X seems to be available as a generic word-character in some languages, it allows you to match a single character disregarding of how many bytes it takes up. Might be useful.</p>
QA:
Regex and unicode
<p>In Mastering Regular Expressions from Jeffrey Friedl (great book) it is mentioned that you could use \p{Letter} which will match unicode stuff that is considered a letter.</p>
QA:
Pylons error - 'MySQL server has gone away'
<p>You might want to check MySQL's timeout variables:</p> <pre><code>show variables like '%timeout%'; </code></pre> <p>You're probably interested in <code>wait_timeout</code> (less likely but possible: <code>interactive_timeout</code>). On Debian and Ubuntu, the defaults are 28800 (MySQL kills connections after 8 hours), but maybe the default for your platform is different or whoever administrates the server has configured things differently.</p> <p>AFAICT, <code>pool_recycle</code> doesn't actually keep the connections alive, it expires them on its own before MySQL kills them. I'm not familiar with pylons, but if causing the connections to intermittently do a <code>SELECT 1;</code> is an option, that will keep them alive at the cost of basically no server load and minimal network traffic. One final thought: are you somehow managing to use a connection that pylons thinks it has expired?</p>
QA:
How to sell Python to a client/boss/person with lots of cash
<p>I agree with mreggen. Tell them by working in Python you can get things done faster. Getting things done faster possibly means money saved by the client. In the least it means that you are working with a language you a more comfortable in, meaning faster development, debugging, and refactoring time. There will be less time spent looking up documentation on what function to use to find the length of a string, etc. </p>
QA:
How to sell Python to a client/boss/person with lots of cash
<p>It's one of the preferred languages over at Google - It's several years ahead of Ruby in terms of "maturity" (what ever that really means - but managers like that). Since it's prefered by Google you can also run it on the Google App Engine.</p> <p>Mircosoft is also embracing Python, and will have a v2.0 of IronPython coming out shortly. They are working on a Ruby implementation as well, but the Python version is way ahead, and is actually "ready for primetime". That give you the possibility for easy integration with .NET code, as well as being able to write client side RIAs in Python when Silverlight 2 ships.</p>
QA:
How do I validate xml against a DTD file in Python
<p>Another good option is <a href="http://lxml.de/validation.html" rel="nofollow">lxml's validation</a> which I find quite pleasant to use.</p> <p>A simple example taken from the lxml site:</p> <pre><code>from StringIO import StringIO from lxml import etree dtd = etree.DTD(StringIO("""&lt;!ELEMENT foo EMPTY&gt;""")) root = etree.XML("&lt;foo/&gt;") print(dtd.validate(root)) # True root = etree.XML("&lt;foo&gt;bar&lt;/foo&gt;") print(dtd.validate(root)) # False print(dtd.error_log.filter_from_errors()) # &lt;string&gt;:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content </code></pre>
QA:
How can I create a directly-executable cross-platform GUI app using Python?
<p>For the GUI itself:</p> <p><a href="http://wiki.python.org/moin/PyQt" rel="nofollow">PyQT</a> is pretty much the reference.</p> <p>Another way to develop a rapid user interface is to write a web app, have it run locally and display the app in the browser.</p> <p>Plus, if you go for the Tkinter option suggested by lubos hasko you may want to try portablepy to have your app run on Windows environment without Python.</p>
QA:
Does anyone have experience creating a shared library in MATLAB?
<p>Perhaps try <a href="http://python.net/crew/theller/ctypes/" rel="nofollow">ctypes </a>instead of SWIG. If it has been included as a part of Python 2.5, then it must be good :-)</p>
QA:
Prototyping with Python code before compiling
<p>In my experience, there are two easy ways to call into C code from Python code. There are other approaches, all of which are more annoying and/or verbose.</p> <p>The first and easiest is to compile a bunch of C code as a separate shared library and then call functions in that library using ctypes. Unfortunately, passing anything other than basic data types is non-trivial.</p> <p>The second easiest way is to write a Python module in C and then call functions in that module. You can pass anything you want to these C functions without having to jump through any hoops. And it's easy to call Python functions or methods from these C functions, as described here: <a href="https://docs.python.org/extending/extending.html#calling-python-functions-from-c" rel="nofollow">https://docs.python.org/extending/extending.html#calling-python-functions-from-c</a></p> <p>I don't have enough experience with SWIG to offer intelligent commentary. And while it is possible to do things like pass custom Python objects to C functions through ctypes, or to define new Python classes in C, these things are annoying and verbose and I recommend taking one of the two approaches described above.</p>
QA:
Sanitising user input using Python
<p>If you are using a framework like <a href="http://www.djangoproject.com/" rel="nofollow">django</a>, the framework can easily do this for you using standard filters. In fact, I'm pretty sure django automatically does it unless you tell it not to.</p> <p>Otherwise, I would recommend using some sort of regex validation before accepting inputs from forms. I don't think there's a silver bullet for your problem, but using the re module, you should be able to construct what you need.</p>
QA:
Sanitising user input using Python
<p>Jeff Atwood himself described how StackOverflow.com sanitizes user input (in non-language-specific terms) on the Stack Overflow blog: <a href="http://blog.stackoverflow.com/2008/06/safe-html-and-xss/" rel="nofollow">http://blog.stackoverflow.com/2008/06/safe-html-and-xss/</a></p> <p>However, as Justin points out, if you use Django templates or something similar then they probably sanitize your HTML output anyway.</p> <p>SQL injection also shouldn't be a concern. All of Python's database libraries (MySQLdb, cx_Oracle, etc) always sanitize the parameters you pass. These libraries are used by all of Python's object-relational mappers (such as Django models), so you don't need to worry about sanitation there either.</p>
QA:
Create an encrypted ZIP file in Python
<p>You can use the <a href="http://www.chilkatsoft.com/python.asp" rel="nofollow">Chilkat</a> library. It's commercial, but has a free evaluation and seems pretty nice.</p> <p>Here's an example I got from <a href="http://www.example-code.com/python/zip.asp" rel="nofollow">here</a>:</p> <pre><code>import chilkat # Demonstrates how to create a WinZip-compatible 128-bit AES strong encrypted zip zip = chilkat.CkZip() zip.UnlockComponent("anything for 30-day trial") zip.NewZip("strongEncrypted.zip") # Set the Encryption property = 4, which indicates WinZip compatible AES encryption. zip.put_Encryption(4) # The key length can be 128, 192, or 256. zip.put_EncryptKeyLength(128) zip.SetPassword("secret") zip.AppendFiles("exampleData/*",True) zip.WriteZip() </code></pre>
QA:
Prototyping with Python code before compiling
<p>The best way to plan for an eventual transition to compiled code is to write the performance sensitive portions as a module of simple functions in a <a href="http://en.wikipedia.org/wiki/Functional_programming" rel="nofollow">functional style</a> (stateless and without side effects), which accept and return basic data types.</p> <p>This will provide a one-to-one mapping from your Python prototype code to the eventual compiled code, and will let you use <a href="https://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a> easily and avoid a whole bunch of headaches.</p> <p>For peak fitting, you'll almost certainly need to use arrays, which will complicate things a little, but is still very doable with ctypes.</p> <p>If you really want to use more complicated data structures, or modify the passed arguments, <a href="http://www.swig.org/" rel="nofollow">SWIG</a> or <a href="https://docs.python.org/extending/" rel="nofollow">Python's standard C-extension interface</a> will let you do what you want, but with some amount of hassle.</p> <p>For what you're doing, you may also want to check out <a href="http://numpy.scipy.org/" rel="nofollow">NumPy</a>, which might do some of the work you would want to push to C, as well as offering <a href="http://projects.scipy.org/scipy/numpy/wiki/NumPyCAPI" rel="nofollow">some additional help in moving data back and forth between Python and C</a>.</p>
QA:
What's the best way to distribute python command-line tools?
<p>Try the <code>entry_points.console_scripts</code> parameter in the setup() call. As described in the <a href="http://peak.telecommunity.com/DevCenter/setuptools#automatic-script-creation">setuptools docs</a>, this should do what I think you want.</p> <p>To reproduce here:</p> <pre><code>from setuptools import setup setup( # other arguments here... entry_points = { 'console_scripts': [ 'foo = package.module:func', 'bar = othermodule:somefunc', ], } ) </code></pre>
QA:
Build a Basic Python Iterator
<p>First of all the <a href="https://docs.python.org/3/library/itertools.html">itertools module</a> is incredibly useful for all sorts of cases in which an iterator would be useful, but here is all you need to create an iterator in python:</p> <blockquote> <p>yield</p> </blockquote> <p>Isn't that cool? Yield can be used to replace a normal <strong>return</strong> in a function. It returns the object just the same, but instead of destroying state and exiting, it saves state for when you want to execute the next iteration. Here is an example of it in action pulled directly from the <a href="http://docs.python.org/lib/itertools-functions.html">itertools function list</a>:</p> <pre><code> def count(n=0): while True: yield n n += 1 </code></pre> <p>As stated in the functions description (it's the <strong>count()</strong> function from the itertools module...) , it produces an iterator that returns consecutive integers starting with n.</p> <p><a href="https://docs.python.org/2/reference/expressions.html#generator-expressions">Generator expressions</a> are a whole other can of worms (awesome worms!). They may be used in place of a <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk">List Comprehension</a> to save memory (list comprehensions create a list in memory that is destroyed after use if not assigned to a variable, but generator expressions can create a Generator Object... which is a fancy way of saying Iterator). Here is an example of a generator expression definition:</p> <pre><code>gen = (n for n in xrange(0,11)) </code></pre> <p>This is very similar to our iterator definition above except the full range is predetermined to be between 0 and 10.</p> <p>I just found <strong>xrange()</strong> (suprised I hadn't seen it before...) and added it to the above example. <strong>xrange()</strong> is an iterable version of <strong>range()</strong> which has the advantage of not prebuilding the list. It would be very useful if you had a giant corpus of data to iterate over and only had so much memory to do it in.</p>
QA:
A Transpose/Unzip Function in Python (inverse of zip)
<p><a href="http://docs.python.org/library/functions.html#zip"><code>zip</code></a> is its own inverse! Provided you use the special * operator.</p> <pre><code>&gt;&gt;&gt; zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)]) [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] </code></pre> <p>The way this works is by calling <code>zip</code> with the arguments:</p> <pre><code>zip(('a', 1), ('b', 2), ('c', 3), ('d', 4)) </code></pre> <p>… except the arguments are passed to <code>zip</code> directly (after being converted to a tuple), so there's no need to worry about the number of arguments getting too big.</p>
QA:
How to check set of files conform to a naming scheme
<p>maybe you should take the approach of defaulting to: "the filename is correct" and work from there to disprove that statement:</p> <p>with the fact that you only allow filenames with: 'show name', 'season number x episode number' and 'episode name', you know for certain that these items should be separated by a "-" (dash) so you have to have 2 of those for a filename to be correct.<br> if that checks out, you can use your code to check that the show name matches the show name as seen in the parent's parent folder (case insensitive i assume), the season number matches the parents folder numeric value (with or without an extra 0 prepended).</p> <p>if however you don't see the correct amount of dashes you instantly know that there is something wrong and stop before the rest of the tests etc.</p> <p>and separately you can check if the file <code>folder.jpg</code> exists and take the necessary actions. <strong>or</strong> do that first and filter that file from the rest of the files in that folder.</p>
QA:
Introducing Python
<p>Well, python is a high level language.. its not hard to learn and if the guys already have programming knowledge it should be much easier to learn.. i like django.. i think it should be a nice try to use django .. </p>
QA:
Introducing Python
<p>If the mandate of the new lead is to put the house in order, the current situation should likely be simplified as much as possible prior. If I had to bring things to order, I wouldn't want to have to manage an ongoing language conversion project on top of everything else, or at least I'd like some choice when initiating the project. When making your recommendation, did you think about the additional managerial complexity that coming into the middle of a conversion would entail?</p>
QA:
Introducing Python
<p>I don't think it's a matter of a programming language as such. </p> <p>What is the proficiency level of PHP in the team you're talking about? Are they doing spaghetti code or using some structured framework like Zend? If this is the first case then I absolutely understand the guy's interest in Python and Django. It this is the latter, it's just a hype.</p>
QA:
Introducing Python
<p>@darkdog:</p> <p>Using a new language in production code is about more than easy syntax and high-level capability. You want to be familiar with core APIs and feel like you can fix something through logic instead of having to comb through the documentation.</p> <p>I'm not saying transitioning to Python would be a bad idea for this company, but I'm with John--keep things simple during the transition. The new lead will appreciate having a say in such decisions.</p> <p>If you'd really, really, really like to introduce Python, consider writing some extensions or utilities in straight-up Python or in the framework. You won't be upsetting your core initiatives, so it will be a low/no-risk opportunity to prove the merits of a switch.</p>
QA:
Introducing Python
<p>I think the language itself is not an issue here, as python is really nice high level language with good and easy to find, thorough documentation.</p> <p>From what I've seen, the Django framework is also a great tooklit for web development, giving much the same developer performance boost Rails is touted to give.</p> <p>The real issue is at the maintenance and management level.</p> <p>How will this move fragment the maintenance between PHP and Python code. Is there a need to migrate existing code from one platform to another? What problems will adopting Python and Django solve that you have in your current development workflow and frameworks, etc.</p>
QA:
Introducing Python
<p>I recently introduced Python to my company, which does consulting work for the Post Office. I did this by waiting until there was a project for which I would be the only programmer, then getting permission to do this new project in Python. I then did another small project in Python with similarly impressive results. In addition, I used Python for all of my small throwaway assignments ("can you parse the stats in these files into a CSV file organized by date and site?", etc) and had a quick turnaround time on all of them.</p> <p>I also evangelized Python a bit; I went out of my way to NOT be obnoxious about it, but I'd occasionally describe why I liked it so much, talked about the personal projects I use it for in my free time and why it's awesome for me, etc.</p> <p>Eventually we started another project and I convinced everyone to use Python for it. I took care to point everyone to a lot of documentation, including the specific webpages relating to what they were working on, and every time they had a question, I'd explain how to do things properly by explaining the Pythonic approach to things, etc.</p> <p>This has worked really well. However, this might be somewhat different than what you're describing. In my case I started with moderately small projects and Python is only being used for new projects. Also, none of my co-workers were really Perl or PHP gurus; they all knew those languages and had been using them for awhile, but it didn't take much effort for them to become more productive in Python than they'd been before.</p> <p>So if you're talking about new projects with people who currently use PHP but aren't super-experts and don't love that language, then I think switching to Python is a no-brainer. However, if you're talking about working with a large existing PHP code base with a lot of very experienced PHP programmers who are happy with their current setup, then switching languages is probably not a good idea. You're probably somewhere in between, so you'll have to weigh the tradeoffs; hopefully my answer will help you do that.</p>
QA:
Introducing Python
<p>I love Python and Django, and use both to develop the our core webapps.</p> <p>That said, it's hard to make a business case for switching at this point. Specifically:</p> <ul> <li>Any new platform is risky compared to staying with the tried and true</li> <li>You'll have the developer fragmentation you mentioned</li> <li>It's far easier to find PHP programmers than python programmers</li> </ul> <p>Moreover, as other posters have mention, if the issue is more with spaghetti code than PHP itself, there are plenty of nice PHP frameworks that could be used to refactor the code.</p> <p>That said, if this developer is excited about python, stopping them outright is probably demoralizing. My suggestion would be to encourage them to develop in python, but not the mission critical parts of the app. Instead they could write some utility scripts, some small internal application that needs doing, etc.</p> <p>In conclusion: I don't recommend switching from PHP, but I do recommend accommodating the developer's interest in some way at work.</p>
QA:
Introducing Python
<p>It's really all about schedules. To me the break should be with a specific project. If you decide your direction is Django then start new projects with that. Before you start a new project with a new language/framework, either make sure that you have scheduled time to get up to speed in this new direction, or get up to speed before using on new projects.</p> <p>I would avoid going with a tool of the month. Make sure you want it to be your direction and commit some time/resources to learning enough to make a good decision.</p>
QA:
What's the best way to grab/parse command line arguments passed to a Python script?
<p>Use <code>optparse</code> which comes with the standard library. For example:</p> <pre><code>#!/usr/bin/env python import optparse def main(): p = optparse.OptionParser() p.add_option('--person', '-p', default="world") options, arguments = p.parse_args() print 'Hello %s' % options.person if __name__ == '__main__': main() </code></pre> <p>Source: <a href="http://www.ibm.com/developerworks/aix/library/au-pythocli/" rel="nofollow">Using Python to create UNIX command line tools</a></p> <p>However as of Python 2.7 optparse is deprecated, see: <a href="http://stackoverflow.com/q/3217673/55075">Why use argparse rather than optparse?</a></p>
QA:
What's the best way to grab/parse command line arguments passed to a Python script?
<p>Pretty much everybody is using <a href="http://python.active-venture.com/lib/module-getopt.html" rel="nofollow">getopt</a></p> <p>Here is the example code for the doc :</p> <pre><code>import getopt, sys def main(): try: opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) output = None verbose = False for o, a in opts: if o == "-v": verbose = True if o in ("-h", "--help"): usage() sys.exit() if o in ("-o", "--output"): output = a </code></pre> <p>So in a word, here is how it works.</p> <p>You've got two types of options. Those who are receiving arguments, and those who are just like switches.</p> <p><code>sys.argv</code> is pretty much your <code>char** argv</code> in C. Like in C you skip the first element which is the name of your program and parse only the arguments : <code>sys.argv[1:]</code></p> <p><code>Getopt.getopt</code> will parse it according to the rule you give in argument.</p> <p><code>"ho:v"</code> here describes the short arguments : <code>-ONELETTER</code>. The <code>:</code> means that <code>-o</code> accepts one argument.</p> <p>Finally <code>["help", "output="]</code> describes long arguments ( <code>--MORETHANONELETTER</code> ). The <code>=</code> after output once again means that output accepts one arguments.</p> <p>The result is a list of couple (option,argument)</p> <p>If an option doesn't accept any argument (like <code>--help</code> here) the <code>arg</code> part is an empty string. You then usually want to loop on this list and test the option name as in the example.</p> <p>I hope this helped you.</p>
QA:
What's the best way to grab/parse command line arguments passed to a Python script?
<p>Just in case you might need to, this may help if you need to <strong>grab</strong> unicode arguments on Win32 (2K, XP etc):</p> <pre><code> from ctypes import * def wmain(argc, argv): print argc for i in argv: print i return 0 def startup(): size = c_int() ptr = windll.shell32.CommandLineToArgvW(windll.kernel32.GetCommandLineW(), byref(size)) ref = c_wchar_p * size.value raw = ref.from_address(ptr) args = [arg for arg in raw] windll.kernel32.LocalFree(ptr) exit(wmain(len(args), args)) startup() </code></pre>
QA:
What's the best way to grab/parse command line arguments passed to a Python script?
<p>I prefer optparse to getopt. It's very declarative: you tell it the names of the options and the effects they should have (e.g., setting a boolean field), and it hands you back a dictionary populated according to your specifications.</p> <p><a href="http://docs.python.org/lib/module-optparse.html" rel="nofollow">http://docs.python.org/lib/module-optparse.html</a></p>
QA:
Find broken symlinks with Python
<p>Can I mention testing for hardlinks without python? /bin/test has the FILE1 -ef FILE2 condition that is true when files share an inode.</p> <p>Therefore, something like <code>find . -type f -exec test \{} -ef /path/to/file \; -print</code> works for hard link testing to a specific file.</p> <p>Which brings me to reading <code>man test</code> and the mentions of <code>-L</code> and <code>-h</code> which both work on one file and return true if that file is a symbolic link, however that doesn't tell you if the target is missing.</p> <p>I did find that <code>head -0 FILE1</code> would return an exit code of <code>0</code> if the file can be opened and a <code>1</code> if it cannot, which in the case of a symbolic link to a regular file works as a test for whether it's target can be read.</p>
QA:
Find broken symlinks with Python
<p>I'm not a python guy but it looks like os.readlink()? The logic I would use in perl is to use readlink() to find the target and the use stat() to test to see if the target exists.</p> <p>Edit: I banged out some perl that demos readlink. I believe perl's stat and readlink and python's os.stat() and os.readlink()are both wrappers for the system calls, so this should translate reasonable well as proof of concept code:</p> <pre><code>wembley 0 /home/jj33/swap &gt; cat p my $f = shift; while (my $l = readlink($f)) { print "$f -&gt; $l\n"; $f = $l; } if (!-e $f) { print "$f doesn't exist\n"; } wembley 0 /home/jj33/swap &gt; ls -l | grep ^l lrwxrwxrwx 1 jj33 users 17 Aug 21 14:30 link -&gt; non-existant-file lrwxrwxrwx 1 root users 31 Oct 10 2007 mm -&gt; ../systems/mm/20071009-rewrite// lrwxrwxrwx 1 jj33 users 2 Aug 21 14:34 mmm -&gt; mm/ wembley 0 /home/jj33/swap &gt; perl p mm mm -&gt; ../systems/mm/20071009-rewrite/ wembley 0 /home/jj33/swap &gt; perl p mmm mmm -&gt; mm mm -&gt; ../systems/mm/20071009-rewrite/ wembley 0 /home/jj33/swap &gt; perl p link link -&gt; non-existant-file non-existant-file doesn't exist wembley 0 /home/jj33/swap &gt; </code></pre>
QA:
Find broken symlinks with Python
<p><a href="https://docs.python.org/2/library/os.html#os.lstat" rel="nofollow">os.lstat()</a> may be helpful. If lstat() succeeds and stat() fails, then it's probably a broken link.</p>
QA:
Find broken symlinks with Python
<p><a href="http://docs.python.org/lib/module-os.path.html" rel="nofollow">os.path</a></p> <p>You may try using realpath() to get what the symlink points to, then trying to determine if it's a valid file using is file.</p> <p>(I'm not able to try that out at the moment, so you'll have to play around with it and see what you get)</p>
QA:
updating an auto_now DateTimeField in a parent model w/ Django
<p>You would also need to then save the message. Then it that should work.</p>
QA:
How to sell Python to a client/boss/person with lots of cash
<p>The best sell of Python I've ever seen was by a manager in our group who had a young daughter. He used a quote attributed to Einstein:</p> <blockquote> <p>If you can't explain something to a six-year-old, you really don't understand it yourself.</p> </blockquote> <p>The next few slides of his presentation demonstrated how he was able to teach his young daughter some basic Python in less than 30 minutes, with examples of the code she wrote and an explanation of what it did.</p> <p>He ended the presentation with a picture of his daughter and her quote "Programming is fun!"</p> <p>I would focus on Python's user friendliness and wealth of libraries and frameworks. There are also a lot of little libraries that you might not get in other languages, and would have to write yourself (i.e. <a href="http://blog.programmerslog.com/?p=124">How a C++ developer writes Python</a>).</p> <p>Good luck!</p>
QA:
How to check set of files conform to a naming scheme
<blockquote> <p>I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state..</p> </blockquote> <p>This doesn't look bad. In fact your current code does it very nicely, and Sven mentioned a good way to do it as well:</p> <ol> <li>Get a list of all the files</li> <li>Check for "required" files</li> </ol> <p>You would just have have add to your dictionary a list of required files:</p> <pre><code>checker = { ... 'required': ['file', 'list', 'for_required'] } </code></pre> <p>As far as there being a better/extensible way to do this? I am not exactly sure. I could only really think of a way to possibly drop the "multiple" regular expressions and build off of Sven's idea for using a delimiter. So my strategy would be defining a dictionary as follows (and I'm sorry I don't know Python syntax and I'm a tad to lazy to look it up but it should make sense. The /regex/ is shorthand for a regex):</p> <pre><code>check_dict = { 'delim' : /\-/, 'parts' : [ 'Show Name', 'Episode Name', 'Episode Number' ], 'patterns' : [/valid name/, /valid episode name/, /valid number/ ], 'required' : ['list', 'of', 'files'], 'ignored' : ['.*', 'hidden.txt'], 'start_dir': '/path/to/dir/to/test/' } </code></pre> <ol> <li>Split the filename based on the delimiter.</li> <li>Check each of the parts.</li> </ol> <p>Because its an ordered list you can determine what parts are missing and if a section doesn't match any pattern it is malformed. Here the <code>parts</code> and <code>patterns</code> have a 1 to 1 ratio. Two arrays instead of a dictionary enforces the order.</p> <p>Ignored and required files can be listed. The <code>.</code> and <code>..</code> files should probably be ignored automatically. The user should be allowed to input "globs" which can be shell expanded. I'm thinking here of <code>svn:ignore</code> properties, but globbing is natural for listing files.</p> <p>Here <code>start_dir</code> would be default to the current directory but if you wanted a single file to run automated testing of a bunch of directories this would be useful.</p> <p>The real loose end here is the path template and along the same lines what path is required for "valid files". I really couldn't come up with a solid idea without writing one large regular expression and taking groups from it... to build a template. It felt a lot like writing a TextMate language grammar. But that starts to stray on the ease of use. The real problem was that the path template was not composed of <code>parts</code>, which makes sense but adds complexity.</p> <p>Is this strategy in tune with what you were thinking of?</p>
QA:
Specifying a mySQL ENUM in a Django model
<p>From the <a href="https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.choices" rel="nofollow">Django documentation</a>:</p> <pre><code>MAYBECHOICE = ( ('y', 'Yes'), ('n', 'No'), ('u', 'Unknown'), ) </code></pre> <p>And you define a charfield in your model :</p> <pre><code>married = models.CharField(max_length=1, choices=MAYBECHOICE) </code></pre> <p>You can do the same with integer fields if you don't like to have letters in your db.</p> <p>In that case, rewrite your choices:</p> <pre><code>MAYBECHOICE = ( (0, 'Yes'), (1, 'No'), (2, 'Unknown'), ) </code></pre>
QA:
Why Java and Python garbage collection methods are different?
<p>I think the article "<a href="http://www.ibm.com/developerworks/java/library/j-jtp10283/">Java theory and practice: A brief history of garbage collection</a>" from IBM should help explain some of the questions you have.</p>
QA:
Why Java and Python garbage collection methods are different?
<p>There are drawbacks of using reference counting. One of the most mentioned is circular references: Suppose A references B, B references C and C references B. If A were to drop its reference to B, both B and C will still have a reference count of 1 and won't be deleted with traditional reference counting. CPython (reference counting is not part of python itself, but part of the C implementation thereof) catches circular references with a separate garbage collection routine that it runs periodically...</p> <p>Another drawback: Reference counting can make execution slower. Each time an object is referenced and dereferenced, the interpreter/VM must check to see if the count has gone down to 0 (and then deallocate if it did). Garbage Collection does not need to do this.</p> <p>Also, Garbage Collection can be done in a separate thread (though it can be a bit tricky). On machines with lots of RAM and for processes that use memory only slowly, you might not want to be doing GC at all! Reference counting would be a bit of a drawback there in terms of performance...</p>
QA:
Why does this python date/time conversion seem wrong?
<pre><code>mktime(...) mktime(tuple) -&gt; floating point number Convert a time tuple in local time to seconds since the Epoch. </code></pre> <p>local time... fancy that.</p> <p>The time tuple:</p> <pre><code>The other representation is a tuple of 9 integers giving local time. The tuple items are: year (four digits, e.g. 1998) month (1-12) day (1-31) hours (0-23) minutes (0-59) seconds (0-59) weekday (0-6, Monday is 0) Julian day (day in the year, 1-366) DST (Daylight Savings Time) flag (-1, 0 or 1) If the DST flag is 0, the time is given in the regular time zone; if it is 1, the time is given in the DST time zone; if it is -1, mktime() should guess based on the date and time. </code></pre> <p>Incidentally, we seem to be 6 hours apart:</p> <pre><code>&gt;&gt;&gt; time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1)) 1233356400.0 &gt;&gt;&gt; (1233378000.0 - 1233356400)/(60*60) 6.0 </code></pre>
QA:
Why does this python date/time conversion seem wrong?
<p>Interesting. I don't know, but I did try this:</p> <pre><code>&gt;&gt;&gt; now = time.mktime((2008, 8, 22, 11 ,17, -1, -1, -1, -1)) &gt;&gt;&gt; tomorrow = time.mktime((2008, 8, 23, 11 ,17, -1, -1, -1, -1)) &gt;&gt;&gt; tomorrow - now 86400.0 </code></pre> <p>which is what you expected. My guess? Maybe some time correction was done since the epoch. This could be only a few seconds, something like a leap year. I think I heard something like this before, but can't remember exactly how and when it is done...</p>
QA:
Why does this python date/time conversion seem wrong?
<p>Short answer: Because of timezones.</p> <p>The Epoch is in UTC.</p> <p>For example, I'm on IST (Irish Stsandard Time) or GMT+1. time.mktime() is relative to my timezone, so on my system this refers to</p> <pre><code>&gt;&gt;&gt; time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1)) 1233360000.0 </code></pre> <p>Because you got the result 1233378000, that would suggest that you're 5 hours behind me</p> <pre><code>&gt;&gt;&gt; (1233378000 - 1233360000) / (60*60) 5 </code></pre> <p>Have a look at the time.gmtime() function which works off UTC.</p>
QA:
Why does this python date/time conversion seem wrong?
<p>Phil's answer really solved it, but I'll elaborate a little more. Since the epoch is in UTC, if I want to compare other times to the epoch, I need to interpret them as UTC as well.</p> <pre><code>&gt;&gt;&gt; calendar.timegm((2009, 1, 31, 0, 0, 0, 5, 31, -1)) 1233360000 &gt;&gt;&gt; 1233360000 / (60*60*24) 14275 </code></pre> <p>By converting the time tuple to a timestamp treating is as UTC time, I get a number which <em>is</em> evenly divisible by the number of seconds in a day.</p> <p>I can use this to convert a date to a days-from-the-epoch representation which is what I'm ultimately after.</p>
QA:
Unicode vs UTF-8 confusion in Python / Django?
<p>Python stores Unicode as UTF-16. str() will return the UTF-8 representation of the UTF-16 string.</p>
QA:
Unicode vs UTF-8 confusion in Python / Django?
<p>From <a href="http://en.wikipedia.org/wiki/UTF-8" rel="nofollow">Wikipedia on UTF-8</a>: </p> <blockquote> UTF-8 (8-bit UCS/Unicode Transformation Format) is a <strong>variable-length character encoding for Unicode. It is able to represent any character in the Unicode standard</strong>, yet the initial encoding of byte codes and character assignments for UTF-8 is backwards compatible with ASCII. For these reasons, it is steadily becoming the preferred encoding for e-mail, web pages[1], and other places where characters are stored or streamed. </blockquote> <p>So, it's anywhere between one and four bytes depending on which character you wish to represent within the realm of Unicode.</p> <p><a href="http://en.wikipedia.org/wiki/Unicode" rel="nofollow">From Wikipedia on Unicode:</a></p> <blockquote> In computing, Unicode is an industry standard allowing computers to consistently represent and manipulate text expressed in <strong>most of the world's writing systems</strong>. </blockquote> <p>So it's able to represent most (but not all) of the world's writing systems. </p> <p>I hope this helps :)</p>
QA:
Unicode vs UTF-8 confusion in Python / Django?
<blockquote> <p>so what is a "Unicode string" in Python?</p> </blockquote> <p>Python 'knows' that your string is Unicode. Hence if you do regex on it, it will know which is character and which is not etc, which is really helpful. If you did a strlen it will also give the correct result. As an example if you did string count on Hello, you will get 5 (even if it's Unicode). But if you did a string count of a foreign word and that string was not a Unicode string than you will have much larger result. Pythong uses the information form the Unicode Character Database to identify each character in the Unicode String. Hope that helps. </p>
QA:
Unicode vs UTF-8 confusion in Python / Django?
<p>Meanwhile, I did a refined research to verify what the internal representation in Python is, and also what its limits are. "<a href="http://www.cmlenz.net/archives/2008/07/the-truth-about-unicode-in-python">The Truth About Unicode In Python</a>" is a very good article which cites directly from the Python developers. Apparently, internal representation is either UCS-2 or UCS-4 depending on a compile-time switch. So Jon, it's not UTF-16, but your answer put me on the right track anyway, thanks.</p>
QA:
Why Java and Python garbage collection methods are different?
<p>Darren Thomas gives a good answer. However, one big difference between the Java and Python approaches is that with reference counting in the common case (no circular references) objects are cleaned up immediately rather than at some indeterminate later date.</p> <p>For example, I can write sloppy, non-portable code in CPython such as</p> <pre><code>def parse_some_attrs(fname): return open(fname).read().split("~~~")[2:4] </code></pre> <p>and the file descriptor for that file I opened will be cleaned up immediately because as soon as the reference to the open file goes away, the file is garbage collected and the file descriptor is freed. Of course, if I run Jython or IronPython or possibly PyPy, then the garbage collector won't necessarily run until much later; possibly I'll run out of file descriptors first and my program will crash.</p> <p>So you SHOULD be writing code that looks like</p> <pre><code>def parse_some_attrs(fname): with open(fname) as f: return f.read().split("~~~")[2:4] </code></pre> <p>but sometimes people like to rely on reference counting to always free up their resources because it can sometimes make your code a little shorter.</p> <p>I'd say that the best garbage collector is the one with the best performance, which currently seems to be the Java-style generational garbage collectors that can run in a separate thread and has all these crazy optimizations, etc. The differences to how you write your code should be negligible and ideally non-existent.</p>
QA:
Adding a Method to an Existing Object Instance
<p>What Jason Pratt posted is correct.</p> <pre><code>&gt;&gt;&gt; class Test(object): ... def a(self): ... pass ... &gt;&gt;&gt; def b(self): ... pass ... &gt;&gt;&gt; Test.b = b &gt;&gt;&gt; type(b) &lt;type 'function'&gt; &gt;&gt;&gt; type(Test.a) &lt;type 'instancemethod'&gt; &gt;&gt;&gt; type(Test.b) &lt;type 'instancemethod'&gt; </code></pre> <p>As you can see, Python doesn't consider b() any different than a(). In Python all methods are just variables that happen to be functions. </p>
QA:
Format numbers to strings in Python
<p>Formatting in Python is done via the <a href="http://docs.python.org/2/library/stdtypes.html#string-formatting">string formatting (<code>%</code>) operator</a>:</p> <pre><code>"%02d:%02d:%02d" % (hours, minutes, seconds) </code></pre> <p>/Edit: There's also <a href="https://docs.python.org/2/library/time.html#time.strftime">strftime</a>.</p>
QA:
Format numbers to strings in Python
<p>You can use C style string formatting:</p> <pre><code>"%d:%d:d" % (hours, minutes, seconds) </code></pre> <p>See here, especially: <a href="https://web.archive.org/web/20120415173443/http://diveintopython3.ep.io/strings.html" rel="nofollow">https://web.archive.org/web/20120415173443/http://diveintopython3.ep.io/strings.html</a></p>
QA:
How do I download a file over HTTP using Python?
<p>In Python 2, use urllib2 which comes with the standard library.</p> <pre><code>import urllib2 response = urllib2.urlopen('http://www.example.com/') html = response.read() </code></pre> <p>This is the most basic way to use the library, minus any error handling. You can also do more complex stuff such as changing headers. The documentation can be found <a href="http://docs.python.org/2/library/urllib2.html">here.</a></p>
QA:
How do I download a file over HTTP using Python?
<pre class="lang-py prettyprint-override"><code>import urllib2 mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3") with open('test.mp3','wb') as output: output.write(mp3file.read()) </code></pre> <p>The <code>wb</code> in <code>open('test.mp3','wb')</code> opens a file (and erases any existing file) in binary mode so you can save data with it instead of just text.</p>
QA:
How do I download a file over HTTP using Python?
<p>I agree with Corey, urllib2 is more complete than <a href="http://docs.python.org/lib/module-urllib.html">urllib</a> and should likely be the module used if you want to do more complex things, but to make the answers more complete, urllib is a simpler module if you want just the basics:</p> <pre><code>import urllib response = urllib.urlopen('http://www.example.com/sound.mp3') mp3 = response.read() </code></pre> <p>Will work fine. Or, if you don't want to deal with the "response" object you can call <strong>read()</strong> directly:</p> <pre><code>import urllib mp3 = urllib.urlopen('http://www.example.com/sound.mp3').read() </code></pre>
QA:
How do I download a file over HTTP using Python?
<p>One more, using <a href="http://docs.python.org/2/library/urllib.html#urllib.urlretrieve"><code>urlretrieve</code></a>:</p> <pre><code>import urllib urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3") </code></pre> <p>(for Python 3+ use 'import urllib.request' and urllib.request.urlretrieve)</p> <p>Yet another one, with a "progressbar"</p> <pre><code>import urllib2 url = "http://download.thinkbroadband.com/10MB.zip" file_name = url.split('/')[-1] u = urllib2.urlopen(url) f = open(file_name, 'wb') meta = u.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (file_name, file_size) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8)*(len(status)+1) print status, f.close() </code></pre>
QA:
How do content discovery engines, like Zemanta and Open Calais work?
<p>Open Calais probably use language parsing technology and language statics to guess which words or phrases are Names, Places, Companies, etc. Then, it is just another step to do some kind of search for those entities and return meta data.</p> <p>Zementa probably does something similar, but matches the phrases against meta-data attached to images in order to acquire related results.</p> <p>It certainly isn't easy.</p>
QA:
What's the best way to duplicate fork() in windows?
<p>Possibly a version of spawn() for python? <a href="http://en.wikipedia.org/wiki/Spawn_(operating_system)" rel="nofollow">http://en.wikipedia.org/wiki/Spawn_(operating_system)</a></p>
QA:
What's the best way to duplicate fork() in windows?
<p>Have a look at the process management functions in the <a href="http://python.org/doc/2.5/lib/os-process.html" rel="nofollow">os module</a>. There are function for starting new processes in many different ways, both synchronously and asynchronously.</p> <p>I should note also that Windows doesn't provide functionality that is exactly like fork() on other systems. To do multiprocessing on Windows, you will need to use the <a href="http://python.org/doc/2.5/lib/module-threading.html" rel="nofollow">threading</a> module.</p>
QA:
What's the best way to duplicate fork() in windows?
<p>In addition to the process management code in the os module that Greg pointed out, you should also take a look at the threading module: <a href="https://docs.python.org/library/threading.html" rel="nofollow">https://docs.python.org/library/threading.html</a></p> <pre><code>from threading import Thread def separate_computations(x, y): print sum(x for i in range(y)) # really expensive multiplication Thread(target=separate_compuations, args=[57, 83]).start() print "I'm continuing while that other function runs in another thread!" </code></pre>
QA:
Why Java and Python garbage collection methods are different?
<p>The latest Sun Java VM actually have multiple GC algorithms which you can tweak. The Java VM specifications intentionally omitted specifying actual GC behaviour to allow different (and multiple) GC algorithms for different VMs.</p> <p>For example, for all the people who dislike the "stop-the-world" approach of the default Sun Java VM GC behaviour, there are VM such as <a href="http://www-01.ibm.com/software/webservers/realtime/" rel="nofollow">IBM's WebSphere Real Time</a> which allows real-time application to run on Java.</p> <p>Since the Java VM spec is publicly available, there is (theoretically) nothing stopping anyone from implementing a Java VM that uses CPython's GC algorithm.</p>
QA:
Can you explain closures (as they relate to Python)?
<p>To be honest, I understand closures perfectly well except I've never been clear about what exactly is the thing which is the "closure" and what's so "closure" about it. I recommend you give up looking for any logic behind the choice of term.</p> <p>Anyway, here's my explanation:</p> <pre><code>def foo(): x = 3 def bar(): print x x = 5 return bar bar = foo() bar() # print 5 </code></pre> <p>A key idea here is that the function object returned from foo retains a hook to the local var 'x' even though 'x' has gone out of scope and should be defunct. This hook is to the var itself, not just the value that var had at the time, so when bar is called, it prints 5, not 3.</p> <p>Also be clear that Python 2.x has limited closure: there's no way I can modify 'x' inside 'bar' because writing 'x = bla' would declare a local 'x' in bar, not assign to 'x' of foo. This is a side-effect of Python's assignment=declaration. To get around this, Python 3.0 introduces the nonlocal keyword:</p> <pre><code>def foo(): x = 3 def bar(): print x def ack(): nonlocal x x = 7 x = 5 return (bar, ack) bar, ack = foo() ack() # modify x of the call to foo bar() # print 7 </code></pre>
QA:
How can I graph the Lines of Code history for git repo?
<p>The first thing that jumps to mind is the possibility of your git history having a nonlinear history. You might have difficulty determining a sensible sequence of commits.</p> <p>Having said that, it seems like you could keep a log of commit ids and the corresponding lines of code in that commit. In a post-commit hook, starting from the HEAD revision, work backwards (branching to multiple parents if necessary) until all paths reach a commit that you've already seen before. That should give you the total lines of code for each commit id.</p> <p>Does that help any? I have a feeling that I've misunderstood something about your question.</p>
QA:
Python code generator for Visual Studio?
<p>I recall that in previous versions of VS, there was a way to add custom build steps to the build process. I used that a lot to do exactly the kind of automated code generation you describe.</p> <p>I imagine the custom build step feature is still there in 2008.</p>
QA:
Python code generator for Visual Studio?
<p>I don't understand what you are trying to do here. Are you trying to execute a Python script that generates a C# file and then compile that with the project? Or are you trying to compile a Python script to C#?</p>
QA:
Python code generator for Visual Studio?
<p>OK, I see. Well, as far as I know there isn't any code generator for Python. There is a good introduction on how to roll your own <a href="http://www.drewnoakes.com/snippets/WritingACustomCodeGeneratorToolForVisualStudio/" rel="nofollow">here</a>.</p> <p>Actually, that's quite an under-used part of the environment, I suppose it's so because it needs you to use the IDE to compile the project, as it'd seem only the IDE knows about these "generators", but MSBuild ignores them.</p>
QA:
Build a Basic Python Iterator
<p>Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: <code>__iter__()</code> and <code>next()</code>. The <code>__iter__</code> returns the iterator object and is implicitly called at the start of loops. The <code>next()</code> method returns the next value and is implicitly called at each loop increment. <code>next()</code> raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.</p> <p>Here's a simple example of a counter:</p> <pre><code>class Counter: def __init__(self, low, high): self.current = low self.high = high def __iter__(self): return self def next(self): # Python 3: def __next__(self) if self.current &gt; self.high: raise StopIteration else: self.current += 1 return self.current - 1 for c in Counter(3, 8): print c </code></pre> <p>This will print:</p> <pre><code>3 4 5 6 7 8 </code></pre> <p>This is easier to write using a generator, as covered in a previous answer:</p> <pre><code>def counter(low, high): current = low while current &lt;= high: yield current current += 1 for c in counter(3, 8): print c </code></pre> <p>The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter.</p> <p>David Mertz's article, <a href="https://www.ibm.com/developerworks/library/l-pycon/">Iterators and Simple Generators</a>, is a pretty good introduction. </p>
QA:
How to capture Python interpreter's and/or CMD.EXE's output from a Python script?
<p>In which context are you asking?</p> <p>Are you trying to capture the output from a program you start on the command line?</p> <p>if so, then this is how to execute it:</p> <pre><code>somescript.py | your-capture-program-here </code></pre> <p>and to read the output, just read from standard input.</p> <p>If, on the other hand, you're executing that script or cmd.exe or similar from within your program, and want to wait until the script/program has finished, and capture all its output, then you need to look at the library calls you use to start that external program, most likely there is a way to ask it to give you some way to read the output and wait for completion.</p>
QA:
How to capture Python interpreter's and/or CMD.EXE's output from a Python script?
<p>You want <a href="http://docs.python.org/lib/module-subprocess.html" rel="nofollow">subprocess</a>. Look specifically at Popen in 17.1.1 and communicate in 17.1.2.</p>
QA:
How to capture Python interpreter's and/or CMD.EXE's output from a Python script?
<p>If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation:</p> <pre><code>python script_a.py | python script_b.py </code></pre> <p>This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on <a href="http://en.wikipedia.org/wiki/Standard_streams" rel="nofollow">standard streams</a> on Wikipedia.</p> <p>If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication):</p> <pre><code>import subprocess # Of course you can open things other than python here :) process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) x = process.stderr.readline() y = process.stdout.readline() process.wait() </code></pre> <p>See the Python <a href="http://docs.python.org/lib/module-subprocess.html" rel="nofollow">subprocess</a> module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard <a href="http://docs.python.org/lib/bltin-file-objects.html" rel="nofollow">file objects</a>.</p> <p>For use with pipes, reading from standard input as <a href="http://stackoverflow.com/questions/24931/how-to-capture-python-interpreters-andor-cmdexes-output-from-a-python-script#24939" rel="nofollow">lassevk</a> suggested you'd do something like this:</p> <pre><code>import sys x = sys.stderr.readline() y = sys.stdin.readline() </code></pre> <p>sys.stdin and sys.stdout are standard file objects as noted above, defined in the <a href="http://docs.python.org/lib/module-sys.html" rel="nofollow">sys</a> module. You might also want to take a look at the <a href="http://docs.python.org/lib/module-pipes.html" rel="nofollow">pipes</a> module.</p> <p>Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into <a href="http://docs.python.org/lib/poll-objects.html" rel="nofollow">polling</a> which unfortunately does not work in windows, but I'm sure there's some alternative out there.</p>
QA:
Format numbers to strings in Python
<p><em>str()</em> in python on an integer will <strong>not</strong> print any decimal places.</p> <p>If you have a float that you want to ignore the decimal part, then you can use str(int(floatValue)).</p> <p>Perhaps the following code will demonstrate:</p> <pre><code>&gt;&gt;&gt; str(5) '5' &gt;&gt;&gt; int(8.7) 8 </code></pre>
QA:
What's the best way to duplicate fork() in windows?
<p>You might also like using the processing module (<a href="http://pypi.python.org/pypi/processing" rel="nofollow">http://pypi.python.org/pypi/processing</a>). It has lot's of functionality for writing parallel systems with the same API as the threading module...</p>
QA:
Binary buffer in Python
<p>Look at the struct package: <a href="https://docs.python.org/library/struct.html" rel="nofollow">https://docs.python.org/library/struct.html</a>, it allows you to interpret strings as packed binary data.</p> <p>Not sure if this will completely answer your question but you can use struct.unpack() to convert binary data to python objects.</p> <pre> <code> import struct f = open(filename, "rb") s = f.read(8) x, y = struct.unpack(">hl", s) </code> </pre> <p>int this example, the ">" tells to read big-endian the "h" reads a 2-byte short, and the "l" is for a 4-byte long. you can obviously change these to whatever you need to read out of the binary data...</p>
QA:
Sanitising user input using Python
<p>Here is a snippet that will remove all tags not on the white list, and all tag attributes not on the attribues whitelist (so you can't use <code>onclick</code>).</p> <p>It is a modified version of <a href="http://www.djangosnippets.org/snippets/205/">http://www.djangosnippets.org/snippets/205/</a>, with the regex on the attribute values to prevent people from using <code>href="javascript:..."</code>, and other cases described at <a href="http://ha.ckers.org/xss.html">http://ha.ckers.org/xss.html</a>.<br> (e.g. <code>&lt;a href="ja&amp;#x09;vascript:alert('hi')"&gt;</code> or <code>&lt;a href="ja vascript:alert('hi')"&gt;</code>, etc.)</p> <p>As you can see, it uses the (awesome) <a href="http://www.crummy.com/software/BeautifulSoup/">BeautifulSoup</a> library.</p> <pre><code>import re from urlparse import urljoin from BeautifulSoup import BeautifulSoup, Comment def sanitizeHtml(value, base_url=None): rjs = r'[\s]*(&amp;#x.{1,7})?'.join(list('javascript:')) rvb = r'[\s]*(&amp;#x.{1,7})?'.join(list('vbscript:')) re_scripts = re.compile('(%s)|(%s)' % (rjs, rvb), re.IGNORECASE) validTags = 'p i strong b u a h1 h2 h3 pre br img'.split() validAttrs = 'href src width height'.split() urlAttrs = 'href src'.split() # Attributes which should have a URL soup = BeautifulSoup(value) for comment in soup.findAll(text=lambda text: isinstance(text, Comment)): # Get rid of comments comment.extract() for tag in soup.findAll(True): if tag.name not in validTags: tag.hidden = True attrs = tag.attrs tag.attrs = [] for attr, val in attrs: if attr in validAttrs: val = re_scripts.sub('', val) # Remove scripts (vbs &amp; js) if attr in urlAttrs: val = urljoin(base_url, val) # Calculate the absolute url tag.attrs.append((attr, val)) return soup.renderContents().decode('utf8') </code></pre> <p>As the other posters have said, pretty much all Python db libraries take care of SQL injection, so this should pretty much cover you.</p>