background preloader

The Python "with" Statement by Example

The Python "with" Statement by Example
Python’s with statement was first introduced five years ago, in Python 2.5. It’s handy when you have two related operations which you’d like to execute as a pair, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it: with open('output.txt', 'w') as f: f.write('Hi there!') The above with statement will automatically close the file after the nested block of code. (Continue reading to see exactly how the close occurs.) Here’s another example. This code sample uses a Context object (“cairo context”) to draw six rectangles, each with a different rotation. cr.translate(68, 68) for i in xrange(6): cr.rotate(2 * math.pi * i / 6) cr.rectangle(-25, -60, 50, 40) cr.stroke() cr.restore() That’s a fairly simple example, but for larger scripts, it can become cumbersome to keep track of which save goes with which restore, and to keep them correctly matched. Implementing the Context Manager as a Class Here’s the first approach. Uh oh!

Related:  Advanced TopicsPy:PatternsMachine learning en python

Python - Advanced List Sorting Consider a list of tuples. We could get such a list when processing information that was extracted from a spreadsheet program. For example, if we had a spreadsheet with raw census data, we can easily transform it into a sequence of tuples that look like the following. jobData= [ (001,'Albany','NY',162692), (003,'Allegany','NY',11986), ... (121,'Wyoming','NY',8722), (123,'Yates','NY',5094) ] Each tuple can be built from a row of the spreadsheet. Understanding Python's "with" statement Fredrik Lundh | October 2006 | Originally posted to Judging from comp.lang.python and other forums, Python 2.5’s new with statement (dead link) seems to be a bit confusing even for experienced Python programmers. As most other things in Python, the with statement is actually very simple, once you understand the problem it’s trying to solve.

Text Processing in Python (a book) A couple of you make donations each month (out of about a thousand of you reading the text each week). Tragedy of the commons and all that... but if some more of you would donate a few bucks, that would be great support of the author. In a community spirit (and with permission of my publisher), I am making my book available to the Python community. Learning Python Programming Language Through Video Lectures One of the upcoming projects I am doing (I will reveal it in one of the next blog posts.) is going to be written entirely in Python. I have a good understanding of Python but, same as I had with JavaScript, I have little experience doing projects from the ground up in it. Update: the project was, read designing (includes full source code). Before diving into the project I decided to take a look at a few Python video lectures to learn language idioms and features which I might have not heard of.

Python metaclasses by example Python rightfully prides itself as a relatively straightforward language without a lot of "magic" hiding in its workings and features. Sometimes, however, to make interesting abstractions possible, one can dig deep in Python’s more dusty and obscure corners to find language constructs that are a bit more magical than usual. Metaclasses are one such feature. Unfortunately, metaclasses have a reputation for "a solution seeking a problem". (How to Write a (Lisp) Interpreter (in Python)) Syntax and Semantics of the Lispy Scheme Subset The syntax of a language is what it looks like; the semantics is what it means. For example, in the language of mathematical expressions, the syntax for adding two plus two is "2 + 2" and the semantics of that expression is the number four. We say we are evaluating a syntactic expression when we determine its semantic referent; we would say that "2 + 2" evaluates to 4, and write that as "2 + 2" ⇒ 4. Most computer languages have a variety of syntactic conventions (keywords, infix operators, brackets, operator precedence, dot notation, semicolons, etc.), but as a member of the Lisp family of languages, all of Scheme's syntax is based on lists in parenthesized prefix notation.

Comprehensions - Dive Into Python 3 You are here: Home ‣ Dive Into Python 3 ‣ Difficulty level: ♦♦♢♢♢ ❝ Our imagination is stretched to the utmost, not, as in fiction, to imagine things which are not really there, but just to comprehend those things which are. ❞ — Richard Feynman ‣ show table of contents Diving In # Every programming language has that one feature, a complicated thing intentionally made simple.

Twitter sentiment analysis using Python and NLTK This post describes the implementation of sentiment analysis of tweets using Python and the natural language toolkit NLTK. The post also describes the internals of NLTK related to this implementation. Background The purpose of the implementation is to be able to automatically classify a tweet as a positive or negative tweet sentiment wise. Generator Tricks for Systems Programmers Generator Tricks for Systems Programmers Copyright (C) 2008David M. Presented at PyCon'08, March 13, 2008, Chicago, Illinois. Related Tutorials 5. Data Structures This chapter describes some things you’ve learned about already in more detail, and adds some new things as well. 5.1. More on Lists Develop Sentiment Analysis tool for your brand in 10 min - Textalytics Have you ever tried to understand the buzz around your brand in social networks? Simple metrics about the amount of friends or followers may matter, but what are they are actually saying? How do you extract insights from all those comments? At Textalytics, we are planning a series of tutorials to show you how you could use text analytics monitor your brand’s health. Today, we will talk about the fanciest feature: Sentiment Analysis.

doctest – Testing through documentation doctest lets you test your code by running examples embedded in the documentation and verifying that they produce the expected results. It works by parsing the help text to find examples, running them, then comparing the output text against the expected value. Many developers find doctest easier than unittest because in its simplest form, there is no API to learn before using it. However, as the examples become more complex the lack of fixture management can make writing doctest tests more cumbersome than using unittest.