background preloader

30 Python Language Features and Tricks You May Not Know About

30 Python Language Features and Tricks You May Not Know About
1 Introduction Since I started learning Python, I decided to maintain an often visited list of "tricks". Any time I saw a piece of code (in an example, on Stack Overflow, in open source software, etc.) that made me think "Cool! I didn't know you could do that!" Each trick or language feature is demonstrated only through examples, with no explanation. The list is very roughly ordered by difficulty, with the easier and more commonly known language features and tricks appearing first. A table of contents is given at the end. Update - April 9th, 2014 As you can see the article has been growing with currently 38 items in it, mostly thanks to comments from readers. Update - March 14th, 2014 Roy Keyes made a great suggestion of turning this article into a GitHub repository to allow readers to make improvements or additions through pull requests. Update - March 8th, 2014 This article generated a lot of good discussion on Reddit ( Hacker News (

A Guide to Python's Magic Methods « rafekettler.com Rafe Kettler Copyright © 2012 Rafe Kettler Version 1.17 A PDF version of this guide can be obtained from my site or Github. Table of Contents Introduction This guide is the culmination of a few months' worth of blog posts. What are magic methods? So, to fix what I perceived as a flaw in Python's documentation, I set out to provide some more plain-English, example-driven documentation for Python's magic methods. I hope you enjoy it. Construction and Initialization Everyone knows the most basic magic method, __init__. __new__(cls, [...) __new__ is the first method to get called in an object's instantiation. __init__(self, [...) The initializer for the class. __del__(self) If __new__ and __init__ formed the constructor of the object, __del__ is the destructor. Putting it all together, here's an example of __init__ and __del__ in action: Making Operators Work on Custom Classes if instance.equals(other_instance): # do something if instance == other_instance: #do something Comparison magic methods __pow__

Python data tools just keep getting better Here are a few observations inspired by conversations I had during the just concluded PyData conference 1 . The Python data community is well-organized: Besides conferences ( PyData , SciPy, EuroSciPy ), there is a new non-profit ( NumFOCUS ) dedicated to supporting scientific computing and data analytics projects. The list of supported projects are currently Python-based, but in principle NumFOCUS is an entity that can be used to support related efforts from other communities. It’s getting easier to use the Python data stack: There are tools that facilitate the dissemination and sharing of code and programming environments. There are many more visualization tools to choose from: The 2D plotting tool matplotlib is the first tool enthusiasts turn to, but as I learned at the conference, there are a number of other options available. In addition, new tools like H20 and wise.io plan to make their massively scalable algorithms accessible via Python.

Decorators and Functional Python Decorators are one of Python’s great features. In addition to their intrinsic usefulness in the language, they also help us to think in an interesting way — a functional way. I intend to explain how decorators work from the ground up. First, let’s define what a Python function is in the simplest way I can think of. A function is a block of reusable code that performs a specific task. Okay, so then what is a decorator? A decorator is a function that modifies other functions. Now let’s start to expand on that definition of decorators, starting with a couple prerequisite explanations. In Python, everything is an object. traveling_function was assigned as the value of the func key in the function_dict dictionary and can still be called like normal. We can pass functions around like any other object. def self_absorbed_function(): return "I'm an amazing function!" At heart, a decorator is just a function that takes another function as an argument. Closure Hopefully those comments are instructive.

Functional Programming in Python What is Functional Programming ? Functional Programming is when functions, not objects or procedures, are the fundamental building blocks of a program. The idea is that you can pass functions as parameters to other functions and return them as values. Q1. Q2. Functional Programming in Python Before diving into the concepts of Functional Programming in python, lets understand some basic programming concepts like Procedural Programming and Object Oriented Programming. 1. The output of a routine does not always have a direct correlation with the input.Everything is done in a specific order.Execution of a routine may have side effects.Tends to emphasize implementing solutions in a linear fashion. 2. A more complete real world example: 3. 3.1 Itertools Let’s start by looking at an important foundation for writing functional-style programs in Python: iterators. 3.1.1 chain() 3.1.2 izip() Makes an iterator that aggregates elements from each of the iterables. 3.1.3 islice() 3.1.4 imap() 3.1.6 count()

Google's Python Class - Educational Materials Welcome to Google's Python Class -- this is a free class for people with a little bit of programming experience who want to learn Python. The class includes written materials, lecture videos, and lots of code exercises to practice Python coding. These materials are used within Google to introduce Python to people who have just a little programming experience. The first exercises work on basic Python concepts like strings and lists, building up to the later exercises which are full programs dealing with text files, processes, and http connections. The class is geared for people who have a little bit of programming experience in some language, enough to know what a "variable" or "if statement" is. Beyond that, you do not need to be an expert programmer to use this material. This material was created by Nick Parlante working in the engEDU group at Google. Tip: Check out the Python Google Code University Forum to ask and answer questions.

Tutorial - Learn Python in 10 minutes NOTE: If you would like some Python development done, my company, Stochastic Technologies, is available for consulting. This tutorial is available as a short ebook. The e-book features extra content from follow-up posts on various Python best practices, all in a convenient, self-contained format. Preliminary fluff So, you want to learn the Python programming language but can't find a concise and yet full-featured tutorial. Properties Python is strongly typed (i.e. types are enforced), dynamically, implicitly typed (i.e. you don't have to declare variables), case sensitive (i.e. var and VAR are two different variables) and object-oriented (i.e. everything is an object). Getting help Help in Python is always available right in the interpreter. >>> help(5)Help on int object:(etc etc) >>> dir(5)['__abs__', '__add__', ...] >>> abs. Syntax Python has no mandatory statement termination characters and blocks are specified by indentation. Data types You can access array ranges using a colon (:).

Python 2.4 Quick Reference Style chooser: Modern, Modern B&W, Classic, High contrast or Printing [Hint: Use styles Modern B&W or Printing to print. If you get problems, try printing the PDF versions instead] Contents Front matter Version 2.4 Check updates at Creative Commons License. Last modified on May 8, 2007 17 Feb 2005, upgraded by Richard Gruet for Python 2.4 03 Oct 2003, upgraded by Richard Gruet for Python 2.3 11 May 2003, rev 4 upgraded by Richard Gruet for Python 2.2 (restyled by Andrei) 7 Aug 2001 upgraded by Simon Brunning for Python 2.1 16 May 2001 upgraded by Richard Gruet and Simon Brunning for Python 2.0 18 Jun 2000 upgraded by Richard Gruet for Python 1.5.2 30 Oct 1995 created by Chris Hoffmann for Python 1.3 Color coding: Features added in 2.4 since 2.3. Originally based on: Python Bestiary, author: Ken Manheimer Python manuals, authors: Guido van Rossum and Fred Drake python-mode.el, author: Tim Peters and the readers of comp.lang.python Useful links : Keywords Numbers

Python Cheat Sheet String String Methods Array Indexes and Slices a=[0,1,2,3,4,5] 6 len(a) 0 a[0] 5 a[5] 5 a[-1] 4 a[-2] [1,2,3,4,5] a[1:] [0,1,2,3,4] a[:5] [0,1,2,3] a[:-2] [1,2] a[1:3] [1,2,3,4] a[1:-1] Shallow copy of a b=a[:] Math Constants math.pi The mathematical constant π = 3.141592..., to available precision. math.e The mathematical constant e = 2.718281..., to available precision. Random Functions Sys Sys Variables argv Command line args builtin_module_names Linked C modules byteorder Native byte order check_-interval Signal check frequency exec_prefix Root directory executable Name of executable exitfunc Exit function name modules Loaded modules path Search path platform Current platform stdin, stdout, stderr File objects for I/O version_info Python version info winver Version number sys.argv foo.py sys.argv[0] bar sys.argv[1] -c sys.argv[2] qux sys.argv[3] --h sys.argv[4] os Variables Class Special Methods String Formatting Formatting Operations 'd' Signed integer decimal. Date Formatting Date Formatting Ad

Related: