background preloader

Neopythonic

Neopythonic

Python: Lambda Functions Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called "lambda". This is not exactly the same as lambda in functional programming languages, but it is a very powerful concept that's well integrated into Python and is often used in conjunction with typical functional concepts like filter(), map() and reduce(). This piece of code shows the difference between a normal function definition ("f") and a lambda function ("g"): As you can see, f() and g() do exactly the same and can be used in the same ways. Note that the lambda definition does not include a "return" statement -- it always contains an expression which is returned. The following code fragments demonstrate the use of lambda functions. The above code defines a function "make_inrementor" that creates an anonymous function on the fly and returns it. The following takes this a step further. In the second example, map() is used to convert our list.

HowTo/Sorting Original version by Andrew Dalke with a major update by Raymond Hettinger Python lists have a built-in sort() method that modifies the list in-place and a sorted() built-in function that builds a new sorted list from an iterable. There are many ways to use them to sort data and there doesn't appear to be a single, central place in the various manuals describing them, so I'll do so here. Sorting Basics A simple ascending sort is very easy -- just call the sorted() function. >>> sorted([5, 2, 3, 1, 4]) [1, 2, 3, 4, 5] You can also use the list.sort() method of a list. >>> a = [5, 2, 3, 1, 4] >>> a.sort() >>> a [1, 2, 3, 4, 5] Another difference is that the list.sort() method is only defined for lists. Key Functions Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons. For example, here's a case-insensitive string comparison: The same technique works for objects with named attributes.

PEP 257 -- Docstring Conventions What is a Docstring? A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object. All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. String literals occurring elsewhere in Python code may also act as documentation. String literals occurring immediately after a simple assignment at the top level of a module, class, or __init__ method are called "attribute docstrings".String literals occurring immediately after another docstring are called "additional docstrings". Please see PEP 258, "Docutils Design Specification" , for a detailed description of attribute and additional docstrings. XXX Mention docstrings of 2.2 properties. For consistency, always use """triple double quotes""" around docstrings. There are two forms of docstrings: one-liners and multi-line docstrings. Multi-line Docstrings

guaranteed-stable sort with the decorate-sort-undecorate idiom ( "decorate-sort-undecorate" is a general and common idiom that allows very flexible and speedy sorting of Python sequences. An auxiliary list is first built (the 'decorate' step) where each item is made up of all sort-keys (in descending order of significance) of the corresponding item of the input sequence (must include all of the information in the whole corresponding item, and/or an index to it so we can fetch it back [or reconstruct it] in the third step). This is then sorted by its builtin sort method without arguments. Finally, the desired sorted-list is extracted/reconstructed by "undecorating" the now-sorted auxiliary-list. Steps 1 and 3 can be performed in several ways, with map, zip, list comprehensions, and explicit loops, all possible. This 'naturally' supplies a sorted _copy_, but if the input-sequence is a list we can just assign to its "include everything" slice to get in-place effect.

The Python Tutorial — Python v2.6.4 documentation Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms. The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python web site, and may be freely distributed. The Python interpreter is easily extended with new functions and data types implemented in C or C++ (or other languages callable from C). This tutorial introduces the reader informally to the basic concepts and features of the Python language and system. For a description of standard objects and modules, see The Python Standard Library. The Glossary is also worth going through.

Pyline: a grep-like, sed-like command-line tool. « ActiveState C Save the script as 'pyline' somewhere on your path, e.g. /usr/local/bin/pyline, and make it executable (e.g. chmod +x /usr/local/bin/pyline). When working at the command line, it's very useful to pipe multiple commands together. Pyline tries to solve this problem. Here are a couple examples: Print out the first 20 characters of every line in the tail of my Apache access log: tail access_log | pyline "line[:20]" Print just the URLs in the access log (the seventh "word" in the line): tail access_log | pyline "words[6]" Here's a tricker one, showing how to do an import. ls | pyline -m os "os.path.isfile(line) and os.stat(line).st_size > 1024 and line" I didn't say it was pretty. ;-) The "-m a,b,c" option will import modules a, b and c for use in the subsequent expression. This last tricky example re-implements the 'md5sum' command, to return the MD5 digest values of all the .py files in the current directory. ls *.py | pyline -m md5 "'%s %s' % (md5.new(file(line).read()).hexdigest(), line)"

An Introduction to Python Lists You can use the list type to implement simple data structures, such as stacks and queues. stack = [] stack.append(object) object = stack.pop() queue = [] queue.append(object) object = queue.pop(0) The list type isn’t optimized for this, so this works best when the structures are small (typically a few hundred items or smaller). For larger structures, you may need a specialized data structure, such as collections.deque. Another data structure for which a list works well in practice, as long as the structure is reasonably small, is an LRU (least-recently-used) container. lru.remove(item) lru.append(item) If you do the above every time you access an item in the LRU list, the least recently used items will move towards the beginning of the list. Searching Lists The in operator can be used to check if an item is present in the list: if value in L: print "list contains", value To get the index of the first matching item, use index: i = L.index(value) try: i = L.index(value) except ValueError: i = -1

Python and MySQL | PC Tips & Tricks Digg this story ? In this post I will show you how to connect to a MySQL database, retrieve data from it and insert data in it using Python. What you need: 1. 2. 3. First verify that your version of Python is 2.3.4 or later, and that the MySQLdb module is installed. % python Python 2.5.2 (r252:60911, Jun 6 2008, 23:32:27) [GCC 4.3.1 20080507 (prerelease) [gcc-4_3-branch revision 135036]] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb Traceback (most recent call last): File " Scripts that access MySQL through DB-API using MySQLdb generally perform the following steps: * Import the MySQLdb module * Open a connection to the MySQL server * Issue statements and retrieve their results * Close the server connection Writing the scripts For the script examples I created a database test and a table fruits ; mysql> select * from fruits; | id | name | 1 | apple | 2 | pear | 3 | orange 3 rows in set (0.00 sec) The result is: pctips@linux:~> python fruits.py 1, apple

Python Tricks Here, I am collecting python snippets that I find enlightening and/or just useful. On a subpage, you find a JPype-using hack to access Weka's Java classes from Python. Additionally, I want to share some interesting links: When working with files or directories (using os.path), you can make your live much easier if you check out the path Python module. Uncluttered, Clean Imports I tend to write code in an unordered way, usually copy-pasting stuff from and to IPython. pyflakes is the solution to this problem. Completion in the Python Console It is handy to be able to tab-complete properties of python objects at the python prompt. However, I find it interesting to note that it is possible to have completion in the standard python console (if compiled with readline, which it really should be)! # .pythonrc.pyimport readline, rlcompleterreadline.parse_and_bind("tab: complete") Put this code in a file ~/.pythonrc.py or similar, and use the variable PYTHONSTARTUP to point python to it! Caution!

Related: