background preloader

Python 1

Facebook Twitter

Decorator

Zope. What I Learned at EuroPython. Computing ThoughtsWhat I Learned at EuroPythonby Bruce EckelJuly 3, 2009 Summary People who've made the switch to dynamic languages seem much, much happier. I was a bit out of sorts from jet lag and travel in general when I entered the Birmingham UK conference and suddenly a wash of good feelings poured over me. "Ahh! Python Programmers! " I worked long and hard on my two presentations and the audience was extremely appreciative.

Many people came up to me during the rest of the conference and said how much they enjoyed both the keynote and the metaprogramming talk. It really makes it worth your efforts to know you've made a difference. I also sat on a panel chaired by Steve Holden about open-spaces style conferences. All the "eyes-forward" (non-open-spaces) presentations have audio recordings and the slides are downloadable; see the EuroPython site for availability.

The first open-spaces session I attended was on the MoinMoin wiki system. Python: What the Hell is a Slot? WDVL: Python: Intro to Python Introspection and Dynamic Programm. An object-calculus evaluator. A short list of things I don’t like about Python. Yeah, I haven't posted in awhile - since pycon I've been sick off an on, working my butt off at the place which allows me to purchase ice cream for my kid, and so on. Busy busy. Not to mention, I've been suffering a slight case of burnout - long story. That all being said, I think it was last week when I twittered a minor philosophical point which was picked up and ran with by pydanny. The little point I made was something like: I don't think it's unreasonable to be able to name at least 5 things you don't like/would change about something you love.

Now, before I delve into my personal list, I want to provide some context to this comment. In my case, I've long maintained that if you can not name things you would change, irk you or generally dislike about something (not just a language) you supposedly love, whether it be a tool, a language, an OS, etc - then it shows you have a certain lack of self-awareness or pragmatism (there is another word I'm grasping for here, but it escapes me). Tinypy. Man, could I have even thought of a title that sounds dustier? It just screams “Get ready for the boring lecture of the year folks.” I should totally re-name this post to something like “putting your brain through a blender .. FOR FUN!” Or maybe I should have gone the pretentious route and named it something like “Analysis of modern programming meta-method paradigms.” Here’s how python does it: class X: def __get__(self,k): return “OK” Here’s how tinypy does it: class MetaX: def __get__(self,k): return “OK” class X: def __init__(self): setmeta(self,MetaX) Okay .. so .. the python way is WAY more readable.

So let me remember if there was a good reason for doing it a different way in tinypy … I think the answer is “maybe” ? In tinypy dict == object, which means a.x == a['x']. So what did I gain by going the lua route instead of the python route? A few days later … With a bit of effort, I’ve come up with a few more reasons why I did this in tinypy: Okay .. those aren’t great reasons. Python-on-a-chip - Google Code. A year with Python. Almost exactly a year ago I wrote here about giving Python a try as my main programming language. Before that I was mainly writing in Perl, and eying Ruby from time to time as the replacement. Well, it will come as no surprise to the readers of this blog that Python won big-time. In the past year I’ve posted more than 30 posts in the Python category of this blog, and it’s clear than Python has indeed become my main programming language.

In this post I want to summarize what I’ve done with Python over the last year, and my general thoughts about the language. General impression My thoughts on Python are not much different from the short summary I posted just a few weeks after starting with the language. For example, although Python doesn’t have CPAN, I haven’t yet encountered a need for which no Python library has been written. I also lamented the clutter in Python’s standard library. Python-mania Python is taking over practically all my programming. With Python, this is just gone. Writing a Package in Python. Its intents are: To shorten the time needed to set up everything before starting the real work, in other words the boiler-plate codeTo provide a standardized way to write packagesTo ease the use of a test-driven development approachTo facilitate the releasing process It is organized in the following four parts: A common pattern for all packages that describes the similarities between all Python packages, and how distutils and setuptools play a central roleHow generative programming ( can help this through the template-based approachThe package template creation, where everything needed to work is setSetting up a development cycle A Common Pattern for All Packages The easiest way to organize the code of an application is to split it into several packages using eggs.

This makes the code simpler, and easier to understand, maintain, and change. Applications for a given company can have a set of eggs glued together with a master egg. sdist test. Best PyCon ever! I landed in Chicago midday in hopes of catching the tail-end of the VM summit. After grabbing my luggage and finding the shuttle to the hotel idling at the curb -- which took a little to find as the signage pointing you to where the shuttles wait is not good at ORD -- I got to the hotel, checked in, and went on down to the summit.

There I found a room with a bunch of VM implementors standing around talking. Turns out that the entire summit had been like that. After brief introductions by each team -- including the public unveiling of Unladen Swallow -- apparently everyone just started chatting in small groups and that continued until people broke up for dinner. When I arrived I instantly started chatting with the CPython guys in the back of the room. One of the great things of PyCon is getting to see friends in person that I typically only get to see at the conference. Thursday was the first Python language summit. During the initial session we all just talked about various things. Sharp Variables at noumena. Posted in: javascript I was looking for some way to easily create, read, manipulate and print cyclic or recursive data structures in some programming languages, and got to the cool concept of sharp variables.

Manipulating Recursive Structures in Python A straightforward way of defining a recursive structure is to first assign a base (non-recursive) structure to a variable, and then alter or extend that variable with a recursive expression. For example, in Python you can write: my_rec_var = [1, 2, 3]my_rec_var.append(my_rec_var) That code will create a recursive data structure: [1, 2, 3, [1, 2, 3, [...]]], or a = [1, 2, 3, a]. Python's pickle module lets you dump a recursive data structure into a file. Import pickle #dump it to fileoutput = open("out.pkl", "wb")pickle.dump(my_rec_var, output) However, there's no literal way of creating, reading or modifying that structure: Manipulating Recursive Structures in Lisp The final structure is represented with sharp variables: The Problem with Integer Division. Python's handling of integer division is an example of early mistake with huge consequences.

As mentioned earlier, when Python was created, I abandoned the approach to numbers that had been used in ABC. For example, in ABC, when you divided two integers, the result was an exact rational number representing the result. In Python however, integer division truncated the result to an integer. In my experience, rational numbers didn't pan out as ABC's designers had hoped. A typical experience would be to write a simple program for some business application (say, doing one’s taxes), and find that it was running much slower than expected.

So with Python, I relied on the other numerical model with which I was familiar, C. The major mistake was that I also borrowed a rule that makes sense in C but not so much in a very-high-level language. Unfortunately, the damage was done--integer division returned an integer result. Ruby-style Blocks in Python. Update: I've updated the proposal to use the using keyword instead of overloading the existing semantics of the with keyword — thanks Guido and Todd Lucas! Blocks are supposedly the most liked feature in Ruby. This proposal would enable a similar feature in Python: using webapp.runner do (config): config.time_zone = 'UTC' config.log_level = 'debug' Compare that to the Ruby equivalent: Rails::Initializer.run do |config| config.time_zone = 'UTC' config.log_level = :debugend Unless I am missing something fundamental, adding a do statement seems to lend itself to doing blocks in a Pythonic way.

For those of you that don't know Ruby, blocks are simply syntactic sugar for defining anonymous functions/closures. This is already possible in Python using the rather complicated-looking lambda keyword: employees.select(lambda e: e.salary > developer.salary) In contrast, Ruby provides the really sexy: employees.select {|e| e.salary > developer.salary} employees.select(throwaway_function) What do you think? Dispatching With "with" March 04, 2009 # Since Python 2.5, we've had access to a new contstruct called the with-statement.

Using them is as simple as implementing the context manager protocol for classes. The with-statement makes it possible to factor our try/finally statements that are commonly used to clean up resources created temporarily. Suppose for example, you have a multi-threaded application that makes use of mutexes to guard shared information. And, what happens if an exception occurs before you unlock?

Lock.lock() try: # perform some action finally: lock.unlock() This ensures that lock is unlocked after the action is performed. Now, using the with-statement we get something more like: with lock: # perform some action The beauty is that we don't have to worry about remembering to call unlock, or wrap it up in the try/finally block. But, we're not worried about locks here. URL Dispatching which is a whole web application written in web.py.

@web.expose('/([a-zA-Z]*)') class Hello: ... How Everything Became an Executable Statement. New users to Python are sometimes surprised to find out that every part of the language is an executable statement, including function and class definitions. That means that any statement can appear anywhere in a program. For instance, a function definition could appear inside an "if" statement if you wanted. In a very early version of Python’s grammar, this was not the case: grammar elements that had a “declarative flavor”, like import statements and function definitions, were allowed only at the top level in a module or script (where they were being executed in order to become effective). However, at the time I was adding support for classes, I decided that this was too restrictive. My reasoning went roughly as follows. Although this reasoning allowed me to simplify the grammar and allowed users to place Python statements anywhere, this feature did not necessarily enable certain styles of programming.

Tail Call Optimization Decorator. Python: copying a list the right way. New = old[:] Those proficient in Python know what the previous line do. It copies the list old into new. This is confusing for beginners and should be avoided. Sadly the [:] notation is widely used, probably because most Python programmers don’t know a better way of copying lists. A little bit of pythonic theory First we need to understand how Python manages objects & variables.

Consider the following statement: a = [1, 2, 3] It means that a points to the list [1, 2, 3] we just created, but a is not the list. B = a We didn’t copy the list referenced by a. If you modify a, you also modify b, since they point to the same list: >>> a.append(4) >>> print a [1, 2, 3, 4] >>> print b [1, 2, 3, 4] The built-in function id() helps keeping track of all this. >>> id(a) 3080501452L >>> id(b) 3080501452L >>> c = [] # Create a new list >>> id(c) 3080609228L a and b really do point to the same memory address. c points to a new empty list, different from the one referenced by a and b. Back to our list. Tinypy :: home. Code Like a Pythonista: Idiomatic Python. In this interactive tutorial, we'll cover many essential Python idioms and techniques in depth, adding immediately useful tools to your belt.

There are 3 versions of this presentation: ©2006-2008, licensed under a Creative Commons Attribution/Share-Alike (BY-SA) license. My credentials: I am a resident of Montreal,father of two great kids, husband of one special woman,a full-time Python programmer,author of the Docutils project and reStructuredText,an editor of the Python Enhancement Proposals (or PEPs),an organizer of PyCon 2007, and chair of PyCon 2008,a member of the Python Software Foundation,a Director of the Foundation for the past year, and its Secretary. In the tutorial I presented at PyCon 2006 (called Text & Data Processing), I was surprised at the reaction to some techniques I used that I had thought were common knowledge. Many of you will have seen some of these techniques and idioms before. These are the guiding principles of Python, but are open to interpretation. Import this.

The History of Python - Introduction. Python is 19 years old now. I started the design and implementation of the language on a cold Christmas break in Amsterdam, in late December 1989. It started out as a typical hobby project. Little did I know where it would all lead. With Python's coming of age, I am going to look back on the history of the language, from the conception as a personal tool, through the the early years of community building, (If Guido was hit by a bus?) This won't be an ordinary blog post -- it'll be an open-ended series. I'll start with the gradual publication of material I wrote a few years ago, when I was invited to contribute an article on Python to HOPL-III, the third installment of ACM's prestigious History of Programming Languages conference, held roughly every ten years.

The next destination of the draft was a book on Python to be published by Addison-Wesley. As they tell prospective Ph.D. students, the best way to eat an elephant is one meal at a time. Python extended slice assignment. When you've been using a programming language for a long time, you like to think that syntax-wise, it has no more secrets left for you. Today I was proven wrong and found out about Python's extended slice assignment, which is present since Python 2.3.5. While looking for ways to speed-up my basic implementation of the Sieve of Eratosthenes I stumbled upon the following snippet: def eras(n): siv=range(n+1) siv[1]=0 sqn=int(round(n**0.5)) for i in range(2,sqn+1): if siv[i]! =0: siv[2*i:n/i*i+1:i]=[0]*(n/i-1) return filter(None,siv) While this code does more or less the same thing as my sieve code, I was puzzled about line 7. This syntax was new to me. I knew about the step argument for slices, making things like getting all even numbers from a range as easy as: >>> L = range(10)>>> L[::2][0, 2, 4, 6, 8] What I didn't know, is that you can assign an equal-length sequence to the slice and have it replace those values, given that the sequence is mutable (eg. a list) like this:

A tiny interpreter for a stack-based language. Python's enigmatic self. Python 3.0 makes a big break. Language generation. On Python and static typing. Thinking algebraically: a functional-programming dividend that p. Dive Into Python. Ruby, Python, "Power" Index of /~eppstein/PADS. Building a Python Web Application, Part 1. Python for JavaScript Programmers. Working with the Operating System. Python's Mutable Default Problem. Python Tips, Tricks, and Hacks. Python: Myths about Indentation. Another Do-It-Yourself Framework. Solving the Monty Hall problem with simulation in Python.

On Monkey Patching. Using Python to create UNIX command line tools. Drawing Chessboards.