background preloader

Python 2

Facebook Twitter

Zed

Python3000. Python, Surprise me! Here’s a simple function which converts the third item of a list into an integer and returns it, returning -1 if the list has fewer than three entries or if the third entry fails to convert. Unfortunately this simple function is simply wrong. Evidently some exceptions aren’t being caught. The Real Surprise There’s nothing mysterious or surprising going on here, but I’ll delay answering this question for a moment. For me, the real surprise about Python is that, generally, I get it right first time. Python similarly caught Eric S. Raymond by surprise. My second [surprise] came a couple of hours into the project, when I noticed (allowing for pauses needed to look up new features in Programming Python) I was generating working code nearly as fast as I could type. Parentheses Required(?)

There are some oddities and gotchas though. A side-effect of the whitespace thing is that you can’t just wrap a long line. Alternatively, parenthesize. Parentheses serve more than one role in Python’s syntax. Drupy: Drupal in Python. Build an Ncurses UI with Python | TuxRadar. Picture the scene: you're logged into a remote server via SSH, or you've installed a new graphics card and you're left staring at the command line.

You need to enter a command, but you can't remember the zillion options that go along with it. You're stuck - all you can do is consult the manual pages and pore through pages of waffling technical gobbledygook. We've all been there, and no matter how experienced you are with Linux, sometimes you need to accomplish a job quickly without sifting through masses of reading material. In this coding project, we're going to solve this problem - and have fun along the way! We'll show you how to write a dialog-based program that gives you options one-by-one so that you don't need to consult the man pages. Now, useradd is a fairly trivial tool and there's an alternative command, adduser, which prompts you step-by-step.

As with our previous code projects (check them out - go on, just right-click the link and select Open Link in New Tab!) Python test.py. Urwid. Printing "Hello world!" using curve fitting techniques. Well, I have a computer architecture exam in six hours and can't be bothered, so I figured I would realize a lifelong dream of mine, and make a program that prints "Hello world! " using curve fitting techniques.

Enlisting the help of a good friend with numerous mathematical papers under his belt (ostensibly because he could not afford a tighter belt), MATLAB and a longing for procrastination, we embarked on this perilous journey. After many, many hours of fitting and discarding data, I can finally present to you my masterpiece. This function returns the ascii ordinal for each of the letters of "Hello, world! " at each integer position (0, 1, 2, 3 etc). I call it... The "Hello world! " and that's it! In case you are wondering, here are the plot points and the fitted function: EDIT: My good friend Iain (of "Lasertoast": fame) has sent me this fantastic etching of the curve on stainless steel, so now I'll try to milk him for all the etchings I can.

A Short Introduction to the ABC Language. (Also available in Japanese) The ABC Programmer's Handbook is available from Bosko Books. ABC is an interactive programming language and environment for personal computing, originally intended as a good replacement for BASIC. It was designed by first doing a task analysis of the programming task. ABC is easy to learn (an hour or so for someone who has already programmed), and yet easy to use. Here is an example function words to collect the set of all words in a document: HOW TO RETURN words document: PUT {} IN collection FOR line IN document: FOR word IN split line: IF word not.in collection: INSERT word IN collection RETURN collection Some features of the language: Some features of the environment: no need for files: procedures and functions and global variables remain after logging out one consistent face is shown to the user at all times, whether executing commands, editing, or entering input to a program generalized undo mechanism.

Four Python variable binding oddities. Python has some strange variable binding semantics. Here are some examples. Oddity 1: If Python were a normal lambda language, you would expect the expression x to be equivalent to (lambda: x)(). I mean x to be a variable name here, but you would expect the equivalence to hold if x were any expression. However, there is one context in which the two are not equivalent: class scope. x = 1 class C: x = 2 print x print (lambda: x)() Expected output: Actual output: There is a fairly good reason for this. Oddity 2: This is also about class scope. X = 1 class C: x = 2 print [x for y in (1,2)] print list(x for y in (1,2)) This happens for a mixture of good reasons and bad reasons. Otherwise class scopes would not behave as consistently. Oddity 3: x = "top" print (lambda: (["a" for x in (1,2)], x))() print (lambda: (list("a" for x in (1,2)), x))() Expected output might be: (['a', 'a'], 'top') (['a', 'a'], 'top') Or if you're aware of list comprehension oddness, you might expect it to be: [1 for x in [100]]

How to invoke subprocesses from Python. Steganography made simple. Things to Know About Python Super. The ExplorerThings to Know About Python Super [1 of 3]by Michele SimionatoAugust 12, 2008 Summary super is perhaps the trickiest Python construct: this series aims to unveil its secrets I begun programming with Python in 2002, just after the release of Python 2.2. That release was a major overhaul of the language: new-style classes were introduced, the way inheritance worked changed and the builtin super was introduced.

Therefore, you may correctly say that I have worked with super right from the beginning; still, I never liked it and over the years I have discovered more and more of its dark corners. In 2004 I decided to write a comprehensive paper documenting super pitfalls and traps, with the goal of publishing it on the Python web site, just as I had published my essay on multiple inheritance and the Method Resolution Order. Keeping the draft sitting on my hard disk is doing a disservice to the community. Super(type[, object-or-type]) Return the superclass of type. >>> super(C,c).a 2. Programming Dynamic Models in Python. In this series of tutorials, we are going to focus on the theory and implementation of transmission models in some kind of population.

In epidemiology, it is common to model the transmission of a pathogen from one person to another. In the social sciences and law, we may be interested in thinking about the way in which individuals influence each other’s opinions, ideology and actions. These two examples are different, but in many ways analogous: it is not difficult to imagine the influence that one individual has on another as being similar to the infectivity of a virus in the sense that both have the ability to change the state of an individual.

One may go from being susceptible to being infected, or from unconvinced to convinced. Additionally, social networks have become an important area of study for epidemiological modelers. Model Assumptions 1. Before getting into the mechanics of the model, let’s talk about the theory and assumptions behind the model as it is implemented here: 2. 3. Django guys let us understand python *args and **kwargs. The Anatomy of a Python Project. Version 0.7.1 October 05, 2009 The Goal You have a pile of Python code. You think, “this could be useful to someone else.” This guide will help you release a high-quality Python project. The Anatomy of a Python Project The goal is to address each of these parts in your project before finally releasing it.

Project Hosting Choose a Host Your code needs a home on the Internet: a website where people can download your software, learn how to use it, and provide feedback. Choose a Project Name You’ll need a project name in order to register. NoteYour project name or “short name” may be taken on your host; this may affect the URL of your project’s homepage and detract from its “findability.”

Sign up for an account on your chosen host. Version Control Create a Repository You will need to set up a version control system (VCS; also called a revision control or source code mangagement system) to hold your code on the Internet. Back Up Your Code $ cd /path/to/$ tar czvf googlemaps.tgz googlemaps/ That’s it. Evolving the standard library. As Titusblogged, an interesting discussion was started over on the stdlib-sig about whether argparse should be added to the standard library, and if so how to handle/whether to deprecate getopt and optparse.

Since the discussion showed rather well how people think the standard library should evolve I figured I would blog about those views and my own (assuming I don't mess up and misrepresent people =). Let's begin by examining the "extreme" views of how to evolve the standard library. One view is that it should practically not exist. The thinking is that software evolves, gets replaced, goes stale, etc., so quickly that people should rely more on the Cheeseshop than Python itself for library code. The standard library should come down to only what is required for Python to run, e.g. codecs, or things that are just extremely difficult to do properly on multiple platforms, e.g. os. So people who want a lean standard library would like it stripped down. Problem with this is maintenance. Python and the power of 'first class' everything.

Rx Simplified (Reactive Programming in Python) Lately, there's been interest in "reactive programming", especially with Rx. What is Rx? I've seen descriptions like "reactive programming with LINQ", "the dual of the enumerator/iterator" and even "a variation of the continuation monad". Oh right...uh...monad? Dual? What's going on? If you like things like "monads", "duals", and category theory, go watch this video, especially until the end. But if those things make your eyes glaze over and you're left wondering what Rx really is, I want to give you a simple explanation of what Rx is all about. Step 1: write simple event handlers Imagine we have a mouse click event that fires either "left" or "right", and we want to make a new event that fires "double left" when there's a double left click.

Step 2: refactor event handlers It works and it's pretty simple. That looks better and is more generic. Evt_out = Event() def handler(value): ... evt_out.fire(value) ... evt_in.handle(handler) return evt_out Great. Step 4: add some syntax sugar. Skulpt. The ternary operator in Python. # tl;dr for python >= 2.5 b if a else c # tl;dr for python < 2.5 (b,c)[not a] What’s a ternary operator? Wikipedia can teach you! The ternary operator of C is one of my favorite operators, it may be hard to read at times, but oh so useful. The example reads “If a is true, then return b, else return c.” The other examples will continue the use of a as the condition, b as the positive response and c as the negative response. (a ? B : c) for before python 2.5 In python you can do this in three ways, the third way is only available in python 2.5 and up.

(a and [b] or [c])[0] This works due to the particular nature of and and or. (b,c)[not a] In this instance we rely on the fact that True == 1 and False == 0. For python 2.5 and up b if a else c First a is evaluated, then either b or c is returned based on the truth value of a; if a evaluates to true b is returned, else c is returned. examples Here is an example of each form in action: Tools of the Modern Python Hacker: Virtualenv, Fabric and Pip.