Popular recipes by Brett Cannon http://code.activestate.com/recipes/users/98030/2010-03-06T16:15:57-08:00ActiveState Code RecipesContext manager to temporarily set an attribute on an object (Python) 2010-03-06T16:15:57-08:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/577089-context-manager-to-temporarily-set-an-attribute-on/ <p style="color: grey"> Python recipe 577089 by <a href="/recipes/users/98030/">Brett Cannon</a> . </p> <p>When testing, it can be really handy to temporarily override an object's attribute with a mock object. This recipe provides a context manager that does that.</p> Generic execution script for a package/application (Python) 2010-03-06T16:10:35-08:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/577088-generic-execution-script-for-a-packageapplication/ <p style="color: grey"> Python recipe 577088 by <a href="/recipes/users/98030/">Brett Cannon</a> . </p> <p>If you keep your application's front-end execution logic in a <code>__main__.py</code> file within your package and change the <code>XXX</code> string to the name of your application's package, this script will handle executing your application for you just like how Python's <code>-m</code> option does it.</p> Context manager for managing a test file (Python) 2007-03-05T17:53:14-08:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/502278-context-manager-for-managing-a-test-file/ <p style="color: grey"> Python recipe 502278 by <a href="/recipes/users/98030/">Brett Cannon</a> . </p> <p>This recipe helps to manage a temporary file used in a test. It returns an open file so as to write the test data, and upon exiting the 'with' statement, makes sure that the created file is deleted.</p> Context manager for calling a method when exiting a 'with' statement (Python) 2007-01-11T10:58:46-08:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/499372-context-manager-for-calling-a-method-when-exiting-/ <p style="color: grey"> Python recipe 499372 by <a href="/recipes/users/98030/">Brett Cannon</a> (<a href="/recipes/tags/shortcuts/">shortcuts</a>). </p> <p>Provides a context manager that allows the user to specify a method on the passed-in object to be called when the 'with' statement is exited. This is a generalization of contextlib.closing.</p> icmplib: library for creating and reading ICMP packets (Python) 2007-07-15T19:37:46-07:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/409689-icmplib-library-for-creating-and-reading-icmp-pack/ <p style="color: grey"> Python recipe 409689 by <a href="/recipes/users/98030/">Brett Cannon</a> (<a href="/recipes/tags/network/">network</a>). Revision 2. </p> <p>[co-authored with Philip E. Nu�ez]</p> <p>Python's stdlib does not have any included library for supporting ICMP packets; both reading them or creating them. But ICMP packets are common and useful; they are used for both the traceroute and ping utilities. And thus they can be useful to control to do network diagnostics.</p> <p>The Packet class is what is used to create and read ICMP packets. To create a packet you instantiate the class, set the header and data fields, and then call the create() method which will the string representation that can be passed to a socket.</p> <p>To read a packet, use the Packet.parse() classmethod, which will return an instance of Packet with the fields filled out.</p> <p>To show its use you can also see the ping() method that is included. Just use the code as a script and pass in an address to ping. Response time is printed to stdout.</p> <p>One word of warning, though, when using this module. Raw sockets tend to require root permissions on the process. Thus you might need to use sudo to execute the Python interpreter to make this all work. ping() does drop sudo permissions as soon as it can, though, for security reasons.</p> extend textwrap.TextWrapper to handle multiple paragraphs (Python) 2004-12-11T02:04:02-08:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/358228-extend-textwraptextwrapper-to-handle-multiple-para/ <p style="color: grey"> Python recipe 358228 by <a href="/recipes/users/98030/">Brett Cannon</a> (<a href="/recipes/tags/text/">text</a>). </p> <p>textwrap is a very handy module. The problem with it, though, is that it expects to be used with individual paragraphs. But what if you want to wrap an entire document? It will still wrap the lines, but it will improperly consider it all a single paragraph.</p> <p>This recipe alleviates that issue by overriding textwrap.TextWrapper.wrap with an implementation that handles spiltting a document into paragraphs and processing each individually. This allows things such as initial_indent to work as expected.</p> Sort names and separate by last name initial (Python) 2004-09-02T11:05:30-07:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/303177-sort-names-and-separate-by-last-name-initial/ <p style="color: grey"> Python recipe 303177 by <a href="/recipes/users/98030/">Brett Cannon</a> (<a href="/recipes/tags/search/">search</a>). </p> <p>When you write a directory for a group of people, you want it grouped by last name initial and then sorted alphabetically. This recipe does just that; it creates a dictionary keyed by last name initial with a value of a tuple of names sorted in alphabetical order.</p> <p>The input to 'groupnames' should be an iterable that returns strings that contain names written in first-middle-last fashion with each part separated by whitespace. The resulting names in the grouped dict will have normalized whitespace.</p> *Very* simple accountant's calculator (Python) 2004-09-02T10:54:01-07:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/303176-very-simple-accountants-calculator/ <p style="color: grey"> Python recipe 303176 by <a href="/recipes/users/98030/">Brett Cannon</a> . </p> <p>One of the signs that you love Python is when you start to use it as a simple calculator. The problem with that is beyond the usefulness of 'sum' the interactive interpreter is not optimal for any calculations beyond a few numbers. This mostly seems to stem from the numbers not being formatted in a nice fashion; <code>2345634+2894756-2345823</code> is not the easiest thing to read. That's where an accountant's calculator comes in handy; the tape presents numbers in a column view that is very uncluttered. And thanks to the decimal package a <em>very</em> simple one can be implemented quickly.</p> <p>To use this recipe you input the number, an optional space, and then the operator (/, *, -, or +; everything you would find on the numeric keypad on your keyboard) and then press return. This will apply the number to the running total using the operator. To output the total just enter a blank line. To quit enter the letter 'q' and press return. This simple interface matches the output of a typical accountant's calculator, removing the need to have some other form of output.</p> Helper subclass for win32pdhquery (Python) 2004-09-03T10:03:51-07:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/303338-helper-subclass-for-win32pdhquery/ <p style="color: grey"> Python recipe 303338 by <a href="/recipes/users/98030/">Brett Cannon</a> (<a href="/recipes/tags/debugging/">debugging</a>). </p> <p>One of the few perks one can have when developing on Windows (at least NT or newer) is the use of the Performance Data Helper (the PDH can be found on Windows XP under the Control Panel at Administrative Tools -> Performance) for system statistics gathering. There is a bevy of counters available that can greatly help you measure the impact your code has on the current system.</p> <p>And luckily win32all provides a wrapper to create counters. The only drawback, though, is that the API is not the best in the world. So, to help deal with that I wrote a subclass to help with adding counters and formatting the output in a more usable fashion as either CSV or a dict that can be pickled.</p> Convert from decimal to any base number (Python) 2004-06-30T20:33:14-07:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/65212-convert-from-decimal-to-any-base-number/ <p style="color: grey"> Python recipe 65212 by <a href="/recipes/users/98030/">Brett Cannon</a> . Revision 3. </p> <p>This function takes in any base-10 integer and returns the string representation of that number in its specified base-n form.</p> <p>Up to base-36 is supported without special notation for symbolizing when a number is really in a single digit position. When that does occur, the number that takes up that single base is surrounded by parantheses.</p> <p>[2004-06-30: Renamed function to base10toN to be more proper]</p> <p>[2001-06-17: Changed comments to base-36 instead of base-35; thanks Klaus Alexander Seistrup]</p> <p>[2001-06-17: Added for loop mechanism in Discussion for alternative way of creating num_rep dictionary; thanks Hamish Lawson for suggesting that possibility]</p> Convert a string into a raw string (Python) 2001-06-19T00:18:59-07:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/65211-convert-a-string-into-a-raw-string/ <p style="color: grey"> Python recipe 65211 by <a href="/recipes/users/98030/">Brett Cannon</a> (<a href="/recipes/tags/text/">text</a>). Revision 3. </p> <p>This function takes in an arbitrary string and converts it into its raw string equivalent. Unfortunately \x will raise a ValueError and I cannot figure out how to deal with it.</p> <p>[2001-06-18: Completely reworked function for performance]</p> Generator for arbitrary assignment (Python) 2002-11-24T01:50:48-08:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/163968-generator-for-arbitrary-assignment/ <p style="color: grey"> Python recipe 163968 by <a href="/recipes/users/98030/">Brett Cannon</a> (<a href="/recipes/tags/shortcuts/">shortcuts</a>). </p> <p>A discussion on python-dev ( <a href="http://mail.python.org/pipermail/python-dev/2002-November/030380.html" rel="nofollow">http://mail.python.org/pipermail/python-dev/2002-November/030380.html</a> ) came up with the idea of allowing arbitrary assignments::</p> <pre class="prettyprint"><code>&gt;&gt;&gt; a,b,*c = (1,2,3,4,5) &gt;&gt;&gt; a 1 &gt;&gt;&gt; b 2 &gt;&gt;&gt; c (3, 4, 5) </code></pre> <p>I didn't like the idea of adding this to the language for assignments, so I came up with a generator that basically does the above but assigns the last variable the used iterator, and all without any new syntax.</p> <p>Thanks to Alex Martelli for simplifying the code and Oren Tirosh for coming up with better variable names.</p> fileinput as a generator (Python) 2002-02-09T23:25:26-08:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/112506-fileinput-as-a-generator/ <p style="color: grey"> Python recipe 112506 by <a href="/recipes/users/98030/">Brett Cannon</a> (<a href="/recipes/tags/files/">files</a>). Revision 2. </p> <p>This is a basic re-implementation of fileinput using generators. It supports all basic functionality that the library module has (nextfile(), lineno(), filelineno(), close(), and filename()). It also adds an __iter__() method that is a generator.</p> Dynamically added methods to a class (Python) 2001-10-15T02:49:01-07:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/81732-dynamically-added-methods-to-a-class/ <p style="color: grey"> Python recipe 81732 by <a href="/recipes/users/98030/">Brett Cannon</a> (<a href="/recipes/tags/oop/">oop</a>). </p> <p>Ruby has the functionality of being able to add a method to a class at an arbitrary point in your code. I figured Python must have some way for allowing this to happen, and it turned out it did. The method is available instantly to all already existing instances and of course ones yet to be created. If you specify method_name then that name is used for the method call.</p> <p>One thing to make sure to do is that the function has a variable for the instance to be passed to (i.e. self).</p> Pure Python strptime (Python) 2003-09-15T18:01:45-07:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/56036-pure-python-strptime/ <p style="color: grey"> Python recipe 56036 by <a href="/recipes/users/98030/">Brett Cannon</a> . Revision 10. </p> <p>This is a modification of the Python code that powers time.strptime() in CVS on 2003-08-11 (Python 2.4 development) to be compatible with Jython 2.1 and CPython 2.1 . It does require the datetime package if you want missing date info to be filled in; it can be found in CVS at /python/nondist/sandbox/datetime/ .</p> <p>If you are using CPython version 2.3.0 or higher, then you do not need this. A more modernized version of the code is included in the language.</p> Finding the index of an item in embedded sequences (Python) 2001-06-19T22:15:09-07:00Brett Cannonhttp://code.activestate.com/recipes/users/98030/http://code.activestate.com/recipes/65252-finding-the-index-of-an-item-in-embedded-sequences/ <p style="color: grey"> Python recipe 65252 by <a href="/recipes/users/98030/">Brett Cannon</a> (<a href="/recipes/tags/search/">search</a>). </p> <p>This function will return a list containing the indices needed to reach an item in embedded sequences.</p> <p>So deepindex([[1,2],[3,[4,[5,6]]],7,[8,9]],6) will return [1,1,1,1].</p>